Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
84.38% covered (warning)
84.38%
81 / 96
58.33% covered (warning)
58.33%
7 / 12
CRAP
0.00% covered (danger)
0.00%
0 / 1
ExtraRoutesModule
84.38% covered (warning)
84.38%
81 / 96
58.33% covered (warning)
58.33%
7 / 12
29.78
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 getConfigHash
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 getRoutesFromFiles
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
3.01
 getRouteFileTimestamps
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
4.94
 getDefinedPaths
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 getAllRoutes
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 initRoutes
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
3.02
 makeRouteInfo
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
3
 getOpenApiInfo
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 getOpenApiContact
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 getOpenApiExternalDocs
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 getDeprecatedDate
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace MediaWiki\Rest\Module;
4
5use AppendIterator;
6use ArrayIterator;
7use Iterator;
8use MediaWiki\Config\ServiceOptions;
9use MediaWiki\HookContainer\HookContainer;
10use MediaWiki\MainConfigNames;
11use MediaWiki\Rest\BasicAccess\BasicAuthorizerInterface;
12use MediaWiki\Rest\Handler\RedirectHandler;
13use MediaWiki\Rest\JsonLocalizer;
14use MediaWiki\Rest\PathTemplateMatcher\ModuleConfigurationException;
15use MediaWiki\Rest\Reporter\ErrorReporter;
16use MediaWiki\Rest\RouteDefinitionException;
17use MediaWiki\Rest\Router;
18use MediaWiki\Rest\Validator\Validator;
19use Wikimedia\ObjectFactory\ObjectFactory;
20
21/**
22 * A Module that is based on flat route definitions in the form originally
23 * introduced in MW 1.35. This module acts as a "catch all" since it doesn't
24 * use a module prefix. So it handles all routes that do not explicitly belong
25 * to a module.
26 *
27 * This module responds to requests by matching the requested path against a
28 * list of known routes to identify the appropriate handler.
29 * The routes are loaded from the route definition files or in extension.json
30 * files using the RestRoutes key.
31 *
32 * Flat files just contain a list (a JSON array) or route definitions (see below).
33 * Annotated route definition files contain a map (a JSON object) with the
34 * following fields:
35 * - "module": the module name (string). The router uses this name to find the
36 *   correct module for handling a request by matching it against the prefix
37 *   of the request path. The module name must be unique.
38 * - "routes": a list (JSON array) or route definitions (see below).
39 *
40 * Each route definition maps a path pattern to a handler class. It is given as
41 * a map (JSON object) with the following fields:
42 * - "path": the path pattern (string) relative to the module prefix. Required.
43 *   The path may contain placeholders for path parameters.
44 * - "method": the HTTP method(s) or "verbs" supported by the route. If not given,
45 *   it is assumed that the route supports the "GET" method. The "OPTIONS" method
46 *   for CORS is supported implicitly.
47 * - "class" or "factory": The handler class (string) or factory function
48 *   (callable) of an "object spec" for use with ObjectFactory::createObject.
49 *   See there for the usage of additional fields like "services". If a shorthand
50 *   is used (see below), no object spec is needed.
51 *
52 * The following fields are supported as a shorthand notation:
53 * - "redirect": the route represents a redirect and will be handled by
54 *   the RedirectHandler class. The redirect is specified as a JSON object
55 *   that specifies the target "path", and optionally the redirect "code".
56 *
57 * More shorthands may be added in the future.
58 *
59 * Route definitions can contain additional fields to configure the handler.
60 * The handler can access the route definition by calling getConfig().
61 *
62 * @internal
63 * @since 1.43
64 */
65class ExtraRoutesModule extends MatcherBasedModule {
66
67    public const CONSTRUCTOR_OPTIONS = [
68        MainConfigNames::Sitename,
69        MainConfigNames::CanonicalServer,
70        MainConfigNames::EmergencyContact,
71        MainConfigNames::RestTermsOfServiceUrl,
72    ];
73
74    /**
75     * @var array<int,array>|null A list of route definitions loaded from
76     * the files specified by $routeFiles
77     */
78    private ?array $routesFromFiles = null;
79
80    /** @var int[]|null */
81    private ?array $routeFileTimestamps = null;
82
83    private ?string $configHash = null;
84
85    /**
86     * @param string[] $routeFiles List of names of JSON files containing routes
87     *        See the documentation of this class for a description of the file
88     *        format.
89     * @param array<int,array> $extraRoutes Extension route array. The content of
90     *        this array must be a list of route definitions. See the documentation
91     *        of this class for a description of the expected structure.
92     */
93    public function __construct(
94        private array $routeFiles,
95        private readonly array $extraRoutes,
96        Router $router,
97        JsonLocalizer $jsonLocalizer,
98        BasicAuthorizerInterface $basicAuth,
99        ObjectFactory $objectFactory,
100        Validator $restValidator,
101        ErrorReporter $errorReporter,
102        HookContainer $hookContainer,
103        private readonly ServiceOptions $options,
104    ) {
105        parent::__construct(
106            $router,
107            '',
108            $jsonLocalizer,
109            $basicAuth,
110            $objectFactory,
111            $restValidator,
112            $errorReporter,
113            $hookContainer
114        );
115        $this->options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
116    }
117
118    /**
119     * Get a config version hash for cache invalidation
120     */
121    protected function getConfigHash(): string {
122        if ( $this->configHash === null ) {
123            $this->configHash = md5( json_encode( [
124                'class' => __CLASS__,
125                'version' => 1,
126                'extraRoutes' => $this->extraRoutes,
127                'fileTimestamps' => $this->getRouteFileTimestamps()
128            ] ) );
129        }
130        return $this->configHash;
131    }
132
133    /**
134     * Load the defined JSON files and return the merged routes.
135     *
136     * @return array<int,array> A list of route definitions. See this class's
137     *         documentation for a description of the format of route definitions.
138     * @throws ModuleConfigurationException If a route file cannot be loaded or processed.
139     */
140    private function getRoutesFromFiles(): array {
141        if ( $this->routesFromFiles !== null ) {
142            return $this->routesFromFiles;
143        }
144
145        $this->routesFromFiles = [];
146        $this->routeFileTimestamps = [];
147        foreach ( $this->routeFiles as $fileName ) {
148            $this->routeFileTimestamps[$fileName] = filemtime( $fileName );
149
150            $routes = $this->loadJsonFile( $fileName );
151
152            $this->routesFromFiles = array_merge( $this->routesFromFiles, $routes );
153        }
154
155        return $this->routesFromFiles;
156    }
157
158    /**
159     * Get an array of last modification times of the defined route files.
160     *
161     * @return int[] Last modification times
162     */
163    private function getRouteFileTimestamps(): array {
164        if ( $this->routeFileTimestamps === null ) {
165            $this->routeFileTimestamps = [];
166            foreach ( $this->routeFiles as $fileName ) {
167                $this->routeFileTimestamps[$fileName] = filemtime( $fileName );
168            }
169        }
170        return $this->routeFileTimestamps;
171    }
172
173    /**
174     * @return array[]
175     */
176    public function getDefinedPaths(): array {
177        $paths = [];
178        foreach ( $this->getAllRoutes() as $spec ) {
179            $key = $spec['path'];
180
181            $methods = isset( $spec['method'] ) ? (array)$spec['method'] : [ 'GET' ];
182
183            $paths[$key] = array_merge( $paths[$key] ?? [], $methods );
184        }
185
186        return $paths;
187    }
188
189    /**
190     * @return Iterator<array>
191     */
192    private function getAllRoutes() {
193        $iterator = new AppendIterator;
194        $iterator->append( new ArrayIterator( $this->getRoutesFromFiles() ) );
195        $iterator->append( new ArrayIterator( $this->extraRoutes ) );
196        return $iterator;
197    }
198
199    protected function initRoutes(): void {
200        $routeDefs = $this->getAllRoutes();
201
202        foreach ( $routeDefs as $route ) {
203            if ( !isset( $route['path'] ) ) {
204                throw new RouteDefinitionException( 'Missing path' );
205            }
206
207            $path = $route['path'];
208            $method = $route['method'] ?? 'GET';
209            $info = $this->makeRouteInfo( $route );
210
211            $this->addRoute( $method, $path, $info );
212        }
213    }
214
215    /**
216     * Generate a route info array to be stored in the matcher tree,
217     * in the form expected by MatcherBasedModule::addRoute()
218     * and ultimately Module::getHandlerForPath().
219     */
220    private function makeRouteInfo( array $route ): array {
221        static $objectSpecKeys = [
222            'class',
223            'factory',
224            'services',
225            'optional_services',
226            'args',
227        ];
228
229        if ( isset( $route['redirect'] ) ) {
230            // Redirect shorthand
231            $info = [
232                'spec' => [ 'class' => RedirectHandler::class ],
233                'config' => $route,
234            ];
235        } else {
236            // Object spec at the top level
237            $info = [
238                'spec' => array_intersect_key( $route, array_flip( $objectSpecKeys ) ),
239                'config' => array_diff_key( $route, array_flip( $objectSpecKeys ) ),
240            ];
241        }
242        if ( isset( $route['openApiSpec'] ) ) {
243            $jsonLocalizer = $this->getJsonLocalizer();
244            $info['openApiSpec'] = $jsonLocalizer->localizeJson( $route['openApiSpec'] );
245        }
246
247        $info['path'] = $route['path'];
248        return $info;
249    }
250
251    /** @inheritDoc */
252    public function getOpenApiInfo() {
253        // Note that mwapi-1.0 is based on OAS 3.0, so it doesn't support the
254        // "summary" property introduced in 3.1.
255        $jsonLocalizer = $this->getJsonLocalizer();
256        $info = [
257            'title' => $jsonLocalizer->getFormattedMessage( 'rest-module-extra-routes-title' ),
258            'description' => $jsonLocalizer->getFormattedMessage( 'rest-module-extra-routes-desc' ),
259            'version' => '0.1.0',
260            'contact' => $this->getOpenApiContact(),
261        ];
262
263        $termsOfService = $this->options->get( MainConfigNames::RestTermsOfServiceUrl );
264        if ( is_string( $termsOfService ) && $termsOfService !== '' ) {
265            $info['termsOfService'] = $termsOfService;
266        }
267
268        return $info;
269    }
270
271    public function getOpenApiContact(): array {
272        $contact = [
273            'name' => $this->options->get( MainConfigNames::Sitename ),
274            'url' => $this->options->get( MainConfigNames::CanonicalServer ),
275        ];
276
277        $email = $this->options->get( MainConfigNames::EmergencyContact );
278        // OpenAPI requires contact.email to be a valid email address. Keep the rest
279        // of the contact object intact and omit the field when the configured value
280        // does not satisfy that format.
281        if ( is_string( $email ) && filter_var( $email, FILTER_VALIDATE_EMAIL ) !== false ) {
282            $contact['email'] = $email;
283        }
284
285        return $contact;
286    }
287
288    /** @inheritDoc */
289    public function getOpenApiExternalDocs(): array {
290        return [
291            'description' => 'API documentation',
292            'url' => 'https://www.mediawiki.org/wiki/API:REST_API',
293        ];
294    }
295
296    /** @inheritDoc */
297    public function getDeprecatedDate(): ?int {
298        return null;
299    }
300}