Merge "FauxRequest: don’t override getValues()"
[lhc/web/wiklou.git] / includes / Rest / Router.php
1 <?php
2
3 namespace MediaWiki\Rest;
4
5 use AppendIterator;
6 use BagOStuff;
7 use Wikimedia\Message\MessageValue;
8 use MediaWiki\Rest\BasicAccess\BasicAuthorizerInterface;
9 use MediaWiki\Rest\PathTemplateMatcher\PathMatcher;
10 use MediaWiki\Rest\Validator\Validator;
11 use Wikimedia\ObjectFactory;
12
13 /**
14 * The REST router is responsible for gathering handler configuration, matching
15 * an input path and HTTP method against the defined routes, and constructing
16 * and executing the relevant handler for a request.
17 */
18 class Router {
19 /** @var string[] */
20 private $routeFiles;
21
22 /** @var array */
23 private $extraRoutes;
24
25 /** @var array|null */
26 private $routesFromFiles;
27
28 /** @var int[]|null */
29 private $routeFileTimestamps;
30
31 /** @var string */
32 private $rootPath;
33
34 /** @var \BagOStuff */
35 private $cacheBag;
36
37 /** @var PathMatcher[]|null Path matchers by method */
38 private $matchers;
39
40 /** @var string|null */
41 private $configHash;
42
43 /** @var ResponseFactory */
44 private $responseFactory;
45
46 /** @var BasicAuthorizerInterface */
47 private $basicAuth;
48
49 /** @var ObjectFactory */
50 private $objectFactory;
51
52 /** @var Validator */
53 private $restValidator;
54
55 /**
56 * @param string[] $routeFiles List of names of JSON files containing routes
57 * @param array $extraRoutes Extension route array
58 * @param string $rootPath The base URL path
59 * @param BagOStuff $cacheBag A cache in which to store the matcher trees
60 * @param ResponseFactory $responseFactory
61 * @param BasicAuthorizerInterface $basicAuth
62 * @param ObjectFactory $objectFactory
63 * @param Validator $restValidator
64 */
65 public function __construct( $routeFiles, $extraRoutes, $rootPath,
66 BagOStuff $cacheBag, ResponseFactory $responseFactory,
67 BasicAuthorizerInterface $basicAuth, ObjectFactory $objectFactory,
68 Validator $restValidator
69 ) {
70 $this->routeFiles = $routeFiles;
71 $this->extraRoutes = $extraRoutes;
72 $this->rootPath = $rootPath;
73 $this->cacheBag = $cacheBag;
74 $this->responseFactory = $responseFactory;
75 $this->basicAuth = $basicAuth;
76 $this->objectFactory = $objectFactory;
77 $this->restValidator = $restValidator;
78 }
79
80 /**
81 * Get the cache data, or false if it is missing or invalid
82 *
83 * @return bool|array
84 */
85 private function fetchCacheData() {
86 $cacheData = $this->cacheBag->get( $this->getCacheKey() );
87 if ( $cacheData && $cacheData['CONFIG-HASH'] === $this->getConfigHash() ) {
88 unset( $cacheData['CONFIG-HASH'] );
89 return $cacheData;
90 } else {
91 return false;
92 }
93 }
94
95 /**
96 * @return string The cache key
97 */
98 private function getCacheKey() {
99 return $this->cacheBag->makeKey( __CLASS__, '1' );
100 }
101
102 /**
103 * Get a config version hash for cache invalidation
104 *
105 * @return string
106 */
107 private function getConfigHash() {
108 if ( $this->configHash === null ) {
109 $this->configHash = md5( json_encode( [
110 $this->extraRoutes,
111 $this->getRouteFileTimestamps()
112 ] ) );
113 }
114 return $this->configHash;
115 }
116
117 /**
118 * Load the defined JSON files and return the merged routes
119 *
120 * @return array
121 */
122 private function getRoutesFromFiles() {
123 if ( $this->routesFromFiles === null ) {
124 $this->routeFileTimestamps = [];
125 foreach ( $this->routeFiles as $fileName ) {
126 $this->routeFileTimestamps[$fileName] = filemtime( $fileName );
127 $routes = json_decode( file_get_contents( $fileName ), true );
128 if ( $this->routesFromFiles === null ) {
129 $this->routesFromFiles = $routes;
130 } else {
131 $this->routesFromFiles = array_merge( $this->routesFromFiles, $routes );
132 }
133 }
134 }
135 return $this->routesFromFiles;
136 }
137
138 /**
139 * Get an array of last modification times of the defined route files.
140 *
141 * @return int[] Last modification times
142 */
143 private function getRouteFileTimestamps() {
144 if ( $this->routeFileTimestamps === null ) {
145 $this->routeFileTimestamps = [];
146 foreach ( $this->routeFiles as $fileName ) {
147 $this->routeFileTimestamps[$fileName] = filemtime( $fileName );
148 }
149 }
150 return $this->routeFileTimestamps;
151 }
152
153 /**
154 * Get an iterator for all defined routes, including loading the routes from
155 * the JSON files.
156 *
157 * @return AppendIterator
158 */
159 private function getAllRoutes() {
160 $iterator = new AppendIterator;
161 $iterator->append( new \ArrayIterator( $this->getRoutesFromFiles() ) );
162 $iterator->append( new \ArrayIterator( $this->extraRoutes ) );
163 return $iterator;
164 }
165
166 /**
167 * Get an array of PathMatcher objects indexed by HTTP method
168 *
169 * @return PathMatcher[]
170 */
171 private function getMatchers() {
172 if ( $this->matchers === null ) {
173 $cacheData = $this->fetchCacheData();
174 $matchers = [];
175 if ( $cacheData ) {
176 foreach ( $cacheData as $method => $data ) {
177 $matchers[$method] = PathMatcher::newFromCache( $data );
178 }
179 } else {
180 foreach ( $this->getAllRoutes() as $spec ) {
181 $methods = $spec['method'] ?? [ 'GET' ];
182 if ( !is_array( $methods ) ) {
183 $methods = [ $methods ];
184 }
185 foreach ( $methods as $method ) {
186 if ( !isset( $matchers[$method] ) ) {
187 $matchers[$method] = new PathMatcher;
188 }
189 $matchers[$method]->add( $spec['path'], $spec );
190 }
191 }
192
193 $cacheData = [ 'CONFIG-HASH' => $this->getConfigHash() ];
194 foreach ( $matchers as $method => $matcher ) {
195 $cacheData[$method] = $matcher->getCacheData();
196 }
197 $this->cacheBag->set( $this->getCacheKey(), $cacheData );
198 }
199 $this->matchers = $matchers;
200 }
201 return $this->matchers;
202 }
203
204 /**
205 * Remove the path prefix $this->rootPath. Return the part of the path with the
206 * prefix removed, or false if the prefix did not match.
207 *
208 * @param string $path
209 * @return false|string
210 */
211 private function getRelativePath( $path ) {
212 if ( strlen( $this->rootPath ) > strlen( $path ) ||
213 substr_compare( $path, $this->rootPath, 0, strlen( $this->rootPath ) ) !== 0
214 ) {
215 return false;
216 }
217 return substr( $path, strlen( $this->rootPath ) );
218 }
219
220 /**
221 * Find the handler for a request and execute it
222 *
223 * @param RequestInterface $request
224 * @return ResponseInterface
225 */
226 public function execute( RequestInterface $request ) {
227 $path = $request->getUri()->getPath();
228 $relPath = $this->getRelativePath( $path );
229 if ( $relPath === false ) {
230 return $this->responseFactory->createLocalizedHttpError( 404,
231 ( new MessageValue( 'rest-prefix-mismatch' ) )
232 ->plaintextParams( $path, $this->rootPath )
233 );
234 }
235
236 $requestMethod = $request->getMethod();
237 $matchers = $this->getMatchers();
238 $matcher = $matchers[$requestMethod] ?? null;
239 $match = $matcher ? $matcher->match( $relPath ) : null;
240
241 // For a HEAD request, execute the GET handler instead if one exists.
242 // The webserver will discard the body.
243 if ( !$match && $requestMethod === 'HEAD' && isset( $matchers['GET'] ) ) {
244 $match = $matchers['GET']->match( $relPath );
245 }
246
247 if ( !$match ) {
248 // Check for 405 wrong method
249 $allowed = [];
250 foreach ( $matchers as $allowedMethod => $allowedMatcher ) {
251 if ( $allowedMethod === $requestMethod ) {
252 continue;
253 }
254 if ( $allowedMatcher->match( $relPath ) ) {
255 $allowed[] = $allowedMethod;
256 }
257 }
258 if ( $allowed ) {
259 $response = $this->responseFactory->createLocalizedHttpError( 405,
260 ( new MessageValue( 'rest-wrong-method' ) )
261 ->textParams( $requestMethod )
262 ->commaListParams( $allowed )
263 ->numParams( count( $allowed ) )
264 );
265 $response->setHeader( 'Allow', $allowed );
266 return $response;
267 } else {
268 // Did not match with any other method, must be 404
269 return $this->responseFactory->createLocalizedHttpError( 404,
270 ( new MessageValue( 'rest-no-match' ) )
271 ->plaintextParams( $relPath )
272 );
273 }
274 }
275
276 $request->setPathParams( array_map( 'rawurldecode', $match['params'] ) );
277 $spec = $match['userData'];
278 $objectFactorySpec = array_intersect_key( $spec,
279 // @todo ObjectFactory supports more keys than this.
280 [ 'factory' => true, 'class' => true, 'args' => true ] );
281 /** @var $handler Handler (annotation for PHPStorm) */
282 $handler = $this->objectFactory->createObject( $objectFactorySpec );
283 $handler->init( $this, $request, $spec, $this->responseFactory );
284
285 try {
286 return $this->executeHandler( $handler );
287 } catch ( HttpException $e ) {
288 return $this->responseFactory->createFromException( $e );
289 }
290 }
291
292 /**
293 * Execute a fully-constructed handler
294 *
295 * @param Handler $handler
296 * @return ResponseInterface
297 */
298 private function executeHandler( $handler ): ResponseInterface {
299 // @phan-suppress-next-line PhanAccessMethodInternal
300 $authResult = $this->basicAuth->authorize( $handler->getRequest(), $handler );
301 if ( $authResult ) {
302 return $this->responseFactory->createHttpError( 403, [ 'error' => $authResult ] );
303 }
304
305 $handler->validate( $this->restValidator );
306
307 $response = $handler->execute();
308 if ( !( $response instanceof ResponseInterface ) ) {
309 $response = $this->responseFactory->createFromReturnValue( $response );
310 }
311 return $response;
312 }
313 }