Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use OCA\AppAPI\Middleware\AppAPIAuthMiddleware;
use OCA\AppAPI\Middleware\ExAppUIL10NMiddleware;
use OCA\AppAPI\Middleware\ExAppUiMiddleware;
use OCA\AppAPI\Middleware\MaintenanceModeMiddleware;
use OCA\AppAPI\Notifications\ExAppNotifier;
use OCA\AppAPI\PublicCapabilities;
use OCA\AppAPI\SetupChecks\DaemonCheck;
Expand Down Expand Up @@ -60,6 +61,7 @@ public function register(IRegistrationContext $context): void {
$context->registerEventListener(LoadAdditionalScriptsEvent::class, LoadFilesPluginListener::class);
$context->registerCapability(Capabilities::class);
$context->registerCapability(PublicCapabilities::class);
$context->registerMiddleware(MaintenanceModeMiddleware::class);
$context->registerMiddleware(AppAPIAuthMiddleware::class);
$context->registerMiddleware(ExAppUiMiddleware::class);
$context->registerMiddleware(ExAppUIL10NMiddleware::class, true);
Expand Down
21 changes: 21 additions & 0 deletions lib/Attribute/MaintenanceModeAvailable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\AppAPI\Attribute;

use Attribute;

/**
* Marks a controller method that stays reachable while the server is in maintenance mode.
*
* @since 35.0.0
*/
#[Attribute]
class MaintenanceModeAvailable {
}
2 changes: 2 additions & 0 deletions lib/Controller/HarpController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
namespace OCA\AppAPI\Controller;

use OCA\AppAPI\AppInfo\Application;
use OCA\AppAPI\Attribute\MaintenanceModeAvailable;
use OCA\AppAPI\Db\ExApp;
use OCA\AppAPI\Service\ExAppService;
use OCA\AppAPI\Service\HarpService;
Expand Down Expand Up @@ -69,6 +70,7 @@ private function validateHarpSharedKey(ExApp $exApp): bool {

#[PublicPage]
#[NoCSRFRequired]
#[MaintenanceModeAvailable]
public function getExAppMetadata(string $appId): DataResponse {
$exApp = $this->exAppService->getExApp($appId);
if ($exApp === null) {
Expand Down
6 changes: 6 additions & 0 deletions lib/Controller/OCSApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

use OCA\AppAPI\AppInfo\Application;
use OCA\AppAPI\Attribute\AppAPIAuth;
use OCA\AppAPI\Attribute\MaintenanceModeAvailable;
use OCA\AppAPI\Service\AppAPIService;
use OCA\AppAPI\Service\ExAppService;
use OCP\AppFramework\Http;
Expand Down Expand Up @@ -49,6 +50,7 @@ public function __construct(
#[PublicPage]
#[NoAdminRequired]
#[NoCSRFRequired]
#[MaintenanceModeAvailable]
public function log(int $level, string $message): DataResponse {
try {
$this->logger->log($level, $message, [
Expand All @@ -71,6 +73,7 @@ public function getNCUsersList(): DataResponse {
#[AppAPIAuth]
#[PublicPage]
#[NoCSRFRequired]
#[MaintenanceModeAvailable]
public function setAppInitProgressDeprecated(string $appId, int $progress, string $error = ''): DataResponse {
$exApp = $this->exAppService->getExApp($appId);
if (!$exApp) {
Expand All @@ -83,6 +86,7 @@ public function setAppInitProgressDeprecated(string $appId, int $progress, strin
#[AppAPIAuth]
#[PublicPage]
#[NoCSRFRequired]
#[MaintenanceModeAvailable]
public function setAppInitProgress(int $progress, string $error = ''): DataResponse {
$exApp = $this->exAppService->getExApp($this->request->getHeader('EX-APP-ID'));
if (!$exApp) {
Expand All @@ -101,6 +105,7 @@ public function setAppInitProgress(int $progress, string $error = ''): DataRespo
#[AppAPIAuth]
#[PublicPage]
#[NoCSRFRequired]
#[MaintenanceModeAvailable]
public function getEnabledState(): DataResponse {
$exApp = $this->exAppService->getExApp($this->request->getHeader('EX-APP-ID'));
if (!$exApp) {
Expand All @@ -112,6 +117,7 @@ public function getEnabledState(): DataResponse {
#[AppAPIAuth]
#[PublicPage]
#[NoCSRFRequired]
#[MaintenanceModeAvailable]
public function getNextcloudAbsoluteUrl(string $url): DataResponse {
return new DataResponse([
'absolute_url' => rtrim($this->config->getSystemValueString('overwrite.cli.url'), '/') . '/' . ltrim($url, '/'),
Expand Down
22 changes: 22 additions & 0 deletions lib/Exceptions/MaintenanceModeException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\AppAPI\Exceptions;

use Exception;
use OCP\AppFramework\Http;

/**
* @package OCA\AppAPI\Exceptions
*/
class MaintenanceModeException extends Exception {
public function __construct($message = 'Service unavailable while the server is in maintenance mode', $code = Http::STATUS_SERVICE_UNAVAILABLE) {
parent::__construct($message, $code);
}
}
53 changes: 53 additions & 0 deletions lib/Middleware/MaintenanceModeMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\AppAPI\Middleware;

use Exception;
use OCA\AppAPI\Attribute\MaintenanceModeAvailable;
use OCA\AppAPI\Exceptions\MaintenanceModeException;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Middleware;
use OCP\IConfig;
use ReflectionMethod;

class MaintenanceModeMiddleware extends Middleware {

public function __construct(
private IConfig $config,
) {
}

/**
* @throws MaintenanceModeException when the server is in maintenance mode and the route is not allowed during it
* @throws \ReflectionException
*/
public function beforeController($controller, $methodName) {
if (!$this->config->getSystemValueBool('maintenance', false)) {
return;
}
$reflectionMethod = new ReflectionMethod($controller, $methodName);
if (!empty($reflectionMethod->getAttributes(MaintenanceModeAvailable::class))) {
return;
}
throw new MaintenanceModeException();
}

public function afterException($controller, $methodName, Exception $exception): Response {
if ($exception instanceof MaintenanceModeException) {
$response = new JSONResponse(['message' => $exception->getMessage()], $exception->getCode());
$response->addHeader('X-Nextcloud-Maintenance-Mode', '1');
$response->addHeader('Retry-After', '120');
return $response;
}

throw $exception;
}
}
144 changes: 144 additions & 0 deletions tests/php/Middleware/MaintenanceModeMiddlewareTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\AppAPI\Tests\php\Middleware;

use OCA\AppAPI\Attribute\MaintenanceModeAvailable;
use OCA\AppAPI\Controller\AppConfigController;
use OCA\AppAPI\Controller\ExAppsPageController;
use OCA\AppAPI\Controller\HarpController;
use OCA\AppAPI\Controller\OCSApiController;
use OCA\AppAPI\Controller\OCSExAppController;
use OCA\AppAPI\Controller\PreferencesController;
use OCA\AppAPI\Controller\TalkBotController;
use OCA\AppAPI\Exceptions\MaintenanceModeException;
use OCA\AppAPI\Middleware\MaintenanceModeMiddleware;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
use OCP\IConfig;
use OCP\IRequest;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use ReflectionMethod;

class MaintenanceModeTestController extends Controller {
#[MaintenanceModeAvailable]
public function allowedRoute(): void {
}

public function blockedRoute(): void {
}
}

class MaintenanceModeMiddlewareTest extends TestCase {
private IConfig $config;
private MaintenanceModeTestController $controller;

protected function setUp(): void {
parent::setUp();
$this->config = $this->createMock(IConfig::class);
$this->controller = new MaintenanceModeTestController('app_api', $this->createMock(IRequest::class));
}

private function middleware(bool $maintenance): MaintenanceModeMiddleware {
$this->config->method('getSystemValueBool')->with('maintenance', false)->willReturn($maintenance);
return new MaintenanceModeMiddleware($this->config);
}

public function testPassesEveryRouteWhenNotInMaintenance(): void {
$this->middleware(false)->beforeController($this->controller, 'blockedRoute');
$this->addToAssertionCount(1);
}

public function testPassesAllowedRouteDuringMaintenance(): void {
$this->middleware(true)->beforeController($this->controller, 'allowedRoute');
$this->addToAssertionCount(1);
}

public function testBlocksUnmarkedRouteDuringMaintenance(): void {
$this->expectException(MaintenanceModeException::class);
$this->middleware(true)->beforeController($this->controller, 'blockedRoute');
}

public function testExceptionIsAnsweredWithMaintenanceResponse(): void {
$exception = new MaintenanceModeException();
$response = $this->middleware(false)->afterException($this->controller, 'blockedRoute', $exception);

self::assertInstanceOf(JSONResponse::class, $response);
self::assertSame(Http::STATUS_SERVICE_UNAVAILABLE, $response->getStatus());
self::assertSame('1', $response->getHeaders()['X-Nextcloud-Maintenance-Mode']);
self::assertSame('120', $response->getHeaders()['Retry-After']);
self::assertSame(['message' => $exception->getMessage()], $response->getData());
}

public function testBlockedRouteInMaintenanceYields503EndToEnd(): void {
$middleware = $this->middleware(true);

try {
$middleware->beforeController($this->controller, 'blockedRoute');
self::fail('Expected MaintenanceModeException to be thrown');
} catch (MaintenanceModeException $exception) {
$response = $middleware->afterException($this->controller, 'blockedRoute', $exception);
}

self::assertSame(Http::STATUS_SERVICE_UNAVAILABLE, $response->getStatus());
self::assertSame('1', $response->getHeaders()['X-Nextcloud-Maintenance-Mode']);
self::assertSame('120', $response->getHeaders()['Retry-After']);
}

public function testUnrelatedExceptionIsRethrown(): void {
$exception = new \RuntimeException('boom');
$this->expectExceptionObject($exception);
$this->middleware(false)->afterException($this->controller, 'blockedRoute', $exception);
}

/**
* @return list<array{class-string, string}>
*/
public static function allowlistedRoutes(): array {
return [
[HarpController::class, 'getExAppMetadata'],
[OCSApiController::class, 'setAppInitProgress'],
[OCSApiController::class, 'setAppInitProgressDeprecated'],
[OCSApiController::class, 'getEnabledState'],
[OCSApiController::class, 'getNextcloudAbsoluteUrl'],
[OCSApiController::class, 'log'],
];
}

#[DataProvider('allowlistedRoutes')]
public function testAllowlistedRouteCarriesAttribute(string $class, string $method): void {
$attributes = (new ReflectionMethod($class, $method))->getAttributes(MaintenanceModeAvailable::class);
self::assertNotEmpty($attributes, $class . '::' . $method . ' must stay reachable during maintenance');
}

/**
* @return list<array{class-string, string}>
*/
public static function blockedRoutes(): array {
return [
[HarpController::class, 'getUserInfo'],
[OCSApiController::class, 'getNCUsersList'],
[OCSExAppController::class, 'getExAppsList'],
[AppConfigController::class, 'setAppConfigValue'],
[AppConfigController::class, 'getAppConfigValues'],
[PreferencesController::class, 'setUserConfigValue'],
[PreferencesController::class, 'getUserConfigValues'],
[ExAppsPageController::class, 'uninstallApp'],
[TalkBotController::class, 'registerExAppTalkBot'],
];
}

#[DataProvider('blockedRoutes')]
public function testNonAllowlistedRouteHasNoAttribute(string $class, string $method): void {
$attributes = (new ReflectionMethod($class, $method))->getAttributes(MaintenanceModeAvailable::class);
self::assertEmpty($attributes, $class . '::' . $method . ' must return 503 during maintenance');
}
}
Loading