Lines 90.82% 208 / 229
Methods 71.87% 23 / 32
Classes 0.00% 0 / 1
Covered by tests of size
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 isSecured 100.00% 1 / 1 100.00% 1 / 1 1
 check 100.00% 21 / 21 100.00% 1 / 1 6
 backup 80.95% 17 / 21 0.00% 0 / 1 6.25
 updateDatabase 100.00% 20 / 20 100.00% 1 / 1 6
 createUpdate 100.00% 8 / 8 100.00% 1 / 1 1
 denyUnauthorizedRequest 100.00% 9 / 9 100.00% 1 / 1 2
 isAuthorizedForUpdate 100.00% 3 / 3 100.00% 1 / 1 2
 isAuthenticatedAdministrator 70.00% 7 / 10 0.00% 0 / 1 4.43
 getUpdateToken 100.00% 1 / 1 100.00% 1 / 1 1
 [phpMyFAQ\Controller\AbstractController] setContainer 100.00% 2 / 2 100.00% 1 / 1 1
 [phpMyFAQ\Controller\AbstractController] initializeFromContainer 78.57% 11 / 14 0.00% 0 / 1 4.16
 [phpMyFAQ\Controller\AbstractController] render 100.00% 5 / 5 100.00% 1 / 1 1
 [phpMyFAQ\Controller\AbstractController] renderView 0.00% 0 / 3 0.00% 0 / 1 2
 [phpMyFAQ\Controller\AbstractController] json 100.00% 1 / 1 100.00% 1 / 1 1
 [phpMyFAQ\Controller\AbstractController] getJsonObject 75.00% 3 / 4 0.00% 0 / 1 2.06
 [phpMyFAQ\Controller\AbstractController] getTwigWrapper 100.00% 10 / 10 100.00% 1 / 1 3
 [phpMyFAQ\Controller\AbstractController] hasValidToken 85.71% 6 / 7 0.00% 0 / 1 5.07
 [phpMyFAQ\Controller\AbstractController] isPublicAuthenticationPath 100.00% 23 / 23 100.00% 1 / 1 1
 [phpMyFAQ\Controller\AbstractController] userIsAuthenticated 100.00% 2 / 2 100.00% 1 / 1 2
 [phpMyFAQ\Controller\AbstractController] userIsSuperAdmin 100.00% 2 / 2 100.00% 1 / 1 2
 [phpMyFAQ\Controller\AbstractController] userHasGroupPermission 100.00% 8 / 8 100.00% 1 / 1 6
 [phpMyFAQ\Controller\AbstractController] userHasUserPermission 100.00% 7 / 7 100.00% 1 / 1 5
 [phpMyFAQ\Controller\AbstractController] userHasPermission 100.00% 5 / 5 100.00% 1 / 1 3
 [phpMyFAQ\Controller\AbstractController] userHasAnyPermission 100.00% 10 / 10 100.00% 1 / 1 4
 [phpMyFAQ\Controller\AbstractController] verifySessionCsrfToken 70.00% 7 / 10 0.00% 0 / 1 4.43
 [phpMyFAQ\Controller\AbstractController] captchaCodeIsValid 85.71% 6 / 7 0.00% 0 / 1 2.01
 [phpMyFAQ\Controller\AbstractController] isApiEnabled 100.00% 1 / 1 100.00% 1 / 1 1
 [phpMyFAQ\Controller\AbstractController] addExtension 100.00% 1 / 1 100.00% 1 / 1 1
 [phpMyFAQ\Controller\AbstractController] addFilter 100.00% 1 / 1 100.00% 1 / 1 1
 [phpMyFAQ\Controller\AbstractController] getRateLimiter 100.00% 4 / 4 100.00% 1 / 1 3
 [phpMyFAQ\Controller\AbstractController] createFallbackContainer 71.42% 5 / 7 0.00% 0 / 1 2.09
36final class SetupController extends AbstractController
37{
38    public const string TOKEN_HEADER = 'x-pmf-update-token';
39
40    /**
41     * @param ?Closure(System, \phpMyFAQ\Configuration): Update $updateFactory
42     */
43    public function __construct(
44        private readonly ?Closure $updateFactory = null,
45    ) {
46        parent::__construct();
47    }
48
49    /**
50     * Setup endpoints cannot rely on the regular login, so we override the security
51     * check from AbstractController. Every endpoint checks for itself that the caller
52     * is allowed to run the update, see isAuthorizedForUpdate().
53     */
54    protected function isSecured(): void
55    {
56        // No-op: authorization is handled per endpoint by isAuthorizedForUpdate()
57    }
58
59    #[Route(path: 'setup/check', name: 'api.private.setup.check', methods: ['POST'])]
60    public function check(Request $request): JsonResponse
61    {
62        $unauthorized = $this->denyUnauthorizedRequest($request);
63        if ($unauthorized instanceof JsonResponse) {
64            return $unauthorized;
65        }
66
67        if (trim($request->getContent()) === '') {
68            return $this->json(['message' => 'No version given.'], Response::HTTP_BAD_REQUEST);
69        }
70
71        $installedVersion = Filter::filterVar($request->getContent(), FILTER_SANITIZE_SPECIAL_CHARS, '');
72
73        $update = $this->createUpdate($installedVersion);
74
75        if (!$update->checkMaintenanceMode()) {
76            return $this->json([
77                'message' => 'Maintenance mode is not enabled. Please enable it first.',
78            ], Response::HTTP_CONFLICT);
79        }
80
81        if (!$update->checkMinimumUpdateVersion($installedVersion)) {
82            $message =
83                'Your installed version is phpMyFAQ '
84                . $installedVersion
85                . '. Please update to at least phpMyFAQ 3.0 first.';
86            return $this->json(['message' => $message], Response::HTTP_CONFLICT);
87        }
88
89        // Check hard requirements
90        try {
91            $update->checkPreUpgrade(Database::getType());
92        } catch (Exception $exception) {
93            return $this->json(['message' => $exception->getMessage()], Response::HTTP_BAD_REQUEST);
94        }
95
96        return $this->json(['message' => 'Installation check successful'], Response::HTTP_OK);
97    }
98
99    #[Route(path: 'setup/backup', name: 'api.private.setup.backup', methods: ['POST'])]
100    public function backup(Request $request): JsonResponse
101    {
102        $unauthorized = $this->denyUnauthorizedRequest($request);
103        if ($unauthorized instanceof JsonResponse) {
104            return $unauthorized;
105        }
106
107        if (trim($request->getContent()) === '') {
108            return $this->json(['message' => 'No version given.'], Response::HTTP_BAD_REQUEST);
109        }
110
111        $update = $this->createUpdate($this->configuration->getVersion());
112
113        if (!$update->checkMaintenanceMode()) {
114            return $this->json([
115                'message' => 'Maintenance mode is not enabled. Please enable it first.',
116            ], Response::HTTP_CONFLICT);
117        }
118
119        $installedVersion = Filter::filterVar($request->getContent(), FILTER_SANITIZE_SPECIAL_CHARS, '');
120
121        $configPath = (string) PMF_ROOT_DIR . '/content/core/config';
122        if (version_compare(version1: $installedVersion, version2: '4.0.0-alpha', operator: '<')) {
123            $configPath = (string) PMF_ROOT_DIR . '/config';
124        }
125
126        try {
127            $pathToBackup = $update->createConfigBackup($configPath);
128        } catch (Exception $exception) {
129            return $this->json(['message' => $exception->getMessage()], Response::HTTP_BAD_GATEWAY);
130        }
131
132        // The archive contains the database credentials, so we only report its name
133        // and never a URL that could be used to download it.
134        return $this->json([
135            'message' => 'Backup successful',
136            'backupFile' => basename($pathToBackup),
137        ], Response::HTTP_OK);
138    }
139
140    #[Route(path: 'setup/update-database', name: 'api.private.setup.update-database', methods: ['POST'])]
141    public function updateDatabase(Request $request): JsonResponse
142    {
143        $unauthorized = $this->denyUnauthorizedRequest($request);
144        if ($unauthorized instanceof JsonResponse) {
145            return $unauthorized;
146        }
147
148        if (trim($request->getContent()) === '') {
149            return $this->json(['message' => 'No version given.'], Response::HTTP_BAD_REQUEST);
150        }
151
152        $installedVersion = Filter::filterVar($request->getContent(), FILTER_SANITIZE_SPECIAL_CHARS, '');
153
154        $update = $this->createUpdate($installedVersion);
155
156        if (!$update->checkMaintenanceMode()) {
157            return $this->json([
158                'message' => 'Maintenance mode is not enabled. Please enable it first.',
159            ], Response::HTTP_CONFLICT);
160        }
161
162        try {
163            if ($update->applyUpdates()) {
164                $this->configuration->set(key: 'main.maintenanceMode', value: 'false');
165                // The update is done, so the token must not authorize another run
166                $this->getUpdateToken()->delete();
167                return new JsonResponse(['success' => 'Database successfully updated.'], Response::HTTP_OK);
168            }
169
170            return new JsonResponse(['error' => 'Update database failed.'], Response::HTTP_BAD_GATEWAY);
171        } catch (Exception|\Exception $exception) {
172            return new JsonResponse([
173                'error' => 'Update database failed: ' . $exception->getMessage(),
174            ], Response::HTTP_BAD_GATEWAY);
175        }
176    }
177
178    private function createUpdate(string $version): Update
179    {
180        $system = new System();
181        $update = ($this->updateFactory
182        ?? static fn(System $system, \phpMyFAQ\Configuration $configuration): Update => new Update(
183            $system,
184            $configuration,
185        ))($system, $this->configuration);
186        $update->version = $version;
187
188        return $update;
189    }
190
191    /**
192     * Returns a 401 response if the caller is not allowed to run the update, otherwise null.
193     */
194    private function denyUnauthorizedRequest(Request $request): ?JsonResponse
195    {
196        if ($this->isAuthorizedForUpdate($request)) {
197            return null;
198        }
199
200        return $this->json([
201            'message' =>
202                'You are not allowed to run the update. Please log in as an administrator or provide the '
203                    . 'update token from '
204                    . UpdateToken::TOKEN_FILENAME
205                    . ' in the configuration directory.',
206        ], Response::HTTP_UNAUTHORIZED);
207    }
208
209    /**
210     * The update may run either for a logged-in administrator, or for someone who can
211     * prove access to the file system of the server by sending the update token. The
212     * second way is needed because the login can be broken until the migration has run.
213     */
214    private function isAuthorizedForUpdate(Request $request): bool
215    {
216        if ($this->isAuthenticatedAdministrator()) {
217            return true;
218        }
219
220        return $this->getUpdateToken()->isValid($request->headers->get(self::TOKEN_HEADER));
221    }
222
223    private function isAuthenticatedAdministrator(): bool
224    {
225        try {
226            if (!$this->currentUser->isLoggedIn()) {
227                return false;
228            }
229
230            if ($this->currentUser->isSuperAdmin()) {
231                return true;
232            }
233
234            return $this->currentUser->perm->hasPermission(
235                $this->currentUser->getUserId(),
236                PermissionType::CONFIGURATION_EDIT->value,
237            );
238        } catch (\Throwable) {
239            // A database that is not migrated yet can break the permission lookup,
240            // in that case the update token is the only way in.
241            return false;
242        }
243    }
244
245    private function getUpdateToken(): UpdateToken
246    {
247        return new UpdateToken((string) PMF_CONFIG_DIR);
248    }
249}

Inherited from phpMyFAQ\Controller\AbstractController

93    public function setContainer(ContainerInterface $container): void
94    {
95        $this->container = $container;
96        $this->initializeFromContainer();
97    }
104    protected function initializeFromContainer(): void
105    {
106        $configuration = $this->container->get(id: 'phpmyfaq.configuration');
107        if (!$configuration instanceof Configuration) {
108            throw new LogicException('Configuration service not found in container.');
109        }
110
111        $this->configuration = $configuration;
112
113        $currentUser = $this->container->get(id: 'phpmyfaq.user.current_user');
114        if (!$currentUser instanceof CurrentUser) {
115            throw new LogicException('CurrentUser service not found in container.');
116        }
117
118        $this->currentUser = $currentUser;
119
120        $session = $this->container->get(id: 'session');
121        if (!$session instanceof FlashBagAwareSessionInterface) {
122            throw new LogicException('Session service not found in container.');
123        }
124
125        $this->session = $session;
126
127        TwigWrapper::setTemplateSetName($this->configuration->getTemplateSet());
128        $this->isSecured();
129    }
137    public function render(string $file, array $context = [], ?Response $response = null): Response
138    {
139        $response ??= new Response();
140        $twigWrapper = $this->getTwigWrapper();
141        $templateWrapper = $twigWrapper->loadTemplate($file);
142
143        $response->setContent($templateWrapper->render($context));
144
145        return $response;
146    }
154    public function renderView(string $pathToTwigFile, array $templateVars = []): string
155    {
156        $twigWrapper = $this->getTwigWrapper();
157        $templateWrapper = $twigWrapper->loadTemplate($pathToTwigFile);
158
159        return $templateWrapper->render($templateVars);
160    }
167    public function json(mixed $data, int $status = 200, array $headers = []): JsonResponse
168    {
169        return new JsonResponse($data, $status, $headers);
170    }
182    protected function getJsonObject(Request $request): \stdClass
183    {
184        /* @mago-expect analysis:mixed-assignment - json_decode() is mixed by nature; validated to stdClass below */
185        $data = json_decode($request->getContent(), associative: false, depth: 512, flags: JSON_THROW_ON_ERROR);
186
187        if (!$data instanceof \stdClass) {
188            throw new JsonException('The request body must be a JSON object.');
189        }
190
191        return $data;
192    }
197    public function getTwigWrapper(): TwigWrapper
198    {
199        $twigWrapper = new TwigWrapper(
200            (string) PMF_ROOT_DIR . '/assets/templates',
201            false,
202            $this->configuration->getTemplateSet(),
203        );
204
205        foreach ($this->twigExtensions as $twigExtension) {
206            $twigWrapper->addExtension($twigExtension);
207        }
208
209        foreach ($this->twigFilters as $twigFilter) {
210            $twigWrapper->addFilter($twigFilter);
211        }
212
213        return $twigWrapper;
214    }
219    protected function hasValidToken(): void
220    {
221        $configuredToken = $this->configuration->get(item: 'api.apiClientToken');
222        if (!is_string($configuredToken) || $configuredToken === '') {
223            throw new UnauthorizedHttpException(challenge: '"x-pmf-token" is not valid.');
224        }
225
226        $request = Request::createFromGlobals();
227        $requestToken = $request->headers->get(key: 'x-pmf-token');
228        if (!is_string($requestToken) || !hash_equals($configuredToken, $requestToken)) {
229            throw new UnauthorizedHttpException(challenge: '"x-pmf-token" is not valid.');
230        }
231    }
257    private function isPublicAuthenticationPath(string $pathInfo): bool
258    {
259        $publicAuthenticationPaths = [
260            '/login',
261            '/authenticate',
262            '/forgot-password',
263            '/token',
264            '/check',
265            '/contact.html',
266            '/imprint.html',
267            '/privacy.html',
268            '/terms.html',
269            '/accessibility.html',
270            '/auth/azure/authorize',
271            '/auth/azure/callback',
272            '/auth/azure/callback.php',
273            '/auth/keycloak/authorize',
274            '/auth/keycloak/callback',
275            '/auth/keycloak/logout',
276            '/services/azure/callback',
277            '/services/azure/callback.php',
278            '/api/webauthn/prepare-login',
279            '/api/webauthn/login',
280        ];
281
282        return in_array($pathInfo, $publicAuthenticationPaths, strict: true);
283    }
288    public function userIsAuthenticated(): void
289    {
290        if (!$this->currentUser->isLoggedIn()) {
291            throw new UnauthorizedHttpException(challenge: 'User is not authenticated.');
292        }
293    }
298    protected function userIsSuperAdmin(): void
299    {
300        if (!$this->currentUser->isSuperAdmin()) {
301            throw new UnauthorizedHttpException(challenge: 'User is not super admin.');
302        }
303    }
308    protected function userHasGroupPermission(): void
309    {
310        if (!$this->currentUser->isLoggedIn()) {
311            throw new UnauthorizedHttpException(challenge: 'User is not authenticated.');
312        }
313
314        $currentUser = $this->currentUser;
315        if (
316            !$currentUser->perm->hasPermission($currentUser->getUserId(), PermissionType::USER_ADD->value)
317            || !$currentUser->perm->hasPermission($currentUser->getUserId(), PermissionType::USER_EDIT->value)
318            || !$currentUser->perm->hasPermission($currentUser->getUserId(), PermissionType::USER_DELETE->value)
319            || !$currentUser->perm->hasPermission($currentUser->getUserId(), PermissionType::GROUP_EDIT->value)
320        ) {
321            throw new ForbiddenException(message: 'User has no group permission.');
322        }
323    }
328    protected function userHasUserPermission(): void
329    {
330        if (!$this->currentUser->isLoggedIn()) {
331            throw new UnauthorizedHttpException(challenge: 'User is not authenticated.');
332        }
333
334        $currentUser = $this->currentUser;
335        if (
336            !$currentUser->perm->hasPermission($currentUser->getUserId(), PermissionType::USER_ADD->value)
337            || !$currentUser->perm->hasPermission($currentUser->getUserId(), PermissionType::USER_EDIT->value)
338            || !$currentUser->perm->hasPermission($currentUser->getUserId(), PermissionType::USER_DELETE->value)
339        ) {
340            throw new ForbiddenException(message: 'User has no user permission.');
341        }
342    }
347    protected function userHasPermission(PermissionType $permissionType): void
348    {
349        if (!$this->currentUser->isLoggedIn()) {
350            throw new UnauthorizedHttpException(challenge: 'User is not authenticated.');
351        }
352
353        $currentUser = $this->currentUser;
354        if (!$currentUser?->perm->hasPermission($currentUser->getUserId(), $permissionType->value)) {
355            throw new ForbiddenException(message: sprintf('User has no "%s" permission.', $permissionType->name));
356        }
357    }
364    protected function userHasAnyPermission(PermissionType ...$permissionTypes): void
365    {
366        if (!$this->currentUser->isLoggedIn()) {
367            throw new UnauthorizedHttpException(challenge: 'User is not authenticated.');
368        }
369
370        $currentUser = $this->currentUser;
371        foreach ($permissionTypes as $permissionType) {
372            if ($currentUser->perm->hasPermission($currentUser->getUserId(), $permissionType->value)) {
373                return;
374            }
375        }
376
377        throw new ForbiddenException(message: sprintf('User has none of the required permissions: %s.', implode(', ', array_map(
378            static fn(PermissionType $type): string => $type->name,
379            $permissionTypes,
380        ))));
381    }
389    protected function verifySessionCsrfToken(string $page, #[\SensitiveParameter] string $requestToken): bool
390    {
391        if ($requestToken === '') {
392            return false;
393        }
394
395        $sessionKey = sprintf('pmf-csrf-token.%s', $page);
396        $storedToken = $this->session->get($sessionKey);
397
398        if (!$storedToken instanceof Token) {
399            return false;
400        }
401
402        if (time() > $storedToken->getExpiry()) {
403            $this->session->remove($sessionKey);
404            return false;
405        }
406
407        return hash_equals($storedToken->getSessionToken(), $requestToken);
408    }
414    protected function captchaCodeIsValid(Request $request): bool
415    {
416        $captcha = Captcha::getInstance($this->configuration);
417        $captcha->setUserIsLoggedIn($this->currentUser->isLoggedIn());
418
419        $data = json_decode($request->getContent(), associative: false, depth: 512, flags: JSON_THROW_ON_ERROR);
420
421        $code = Filter::filterVar($data->captcha ?? '', FILTER_SANITIZE_SPECIAL_CHARS);
422        if ($this->configuration->get(item: 'security.enableGoogleReCaptchaV2')) {
423            $code = Filter::filterVar($data->{'g-recaptcha-response'} ?? '', FILTER_SANITIZE_SPECIAL_CHARS);
424        }
425
426        return $captcha->checkCaptchaCode((string) $code);
427    }
429    public function isApiEnabled(): bool
430    {
431        return (bool) $this->configuration->get(item: 'api.enableAccess');
432    }
434    public function addExtension(ExtensionInterface $extension): void
435    {
436        $this->twigExtensions[] = $extension;
437    }
439    public function addFilter(TwigFilter $twigFilter): void
440    {
441        $this->twigFilters[] = $twigFilter;
442    }
444    protected function getRateLimiter(): ?RateLimiter
445    {
446        if (!$this->container->has('phpmyfaq.http.rate-limiter')) {
447            return null;
448        }
449
450        $rateLimiter = $this->container->get('phpmyfaq.http.rate-limiter');
451
452        return $rateLimiter instanceof RateLimiter ? $rateLimiter : null;
453    }
455    private function createFallbackContainer(): ContainerBuilder
456    {
457        $containerBuilder = new ContainerBuilder();
458        $phpFileLoader = new PhpFileLoader($containerBuilder, new FileLocator(__DIR__));
459        try {
460            $phpFileLoader->load(resource: '../../services.php');
461        } catch (\Exception $exception) {
462            error_log($exception->getMessage());
463        }
464
465        // Register Forms services
466        FormsServiceProvider::register($containerBuilder);
467
468        return $containerBuilder;
469    }