diff --git a/appinfo/routes.php b/appinfo/routes.php index 9a43ac1b1..1c102e8a2 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -7,7 +7,7 @@ * SPDX-License-Identifier: EUPL-1.2 */ -return [ +$routes = [ 'routes' => [ // v2 runtime manifest (ADR-036 Decision 8). Registered FIRST so the // literal '/api/manifest' segment is matched before any wildcard. @@ -20,6 +20,8 @@ // Metrics and health ['name' => 'metrics#index', 'url' => '/api/metrics', 'verb' => 'GET'], ['name' => 'health#index', 'url' => '/api/health', 'verb' => 'GET'], + // The OpenAPI document, public (NL API Design Rules, /core/publish-openapi). + ['name' => 'openApi#show', 'url' => '/api/openapi.json', 'verb' => 'GET'], // Store plane (ADR-080). LaunchPad declares a `type: "store"` page, which // renders CnStorePage, which calls the item routes on mount and on an install @@ -654,3 +656,20 @@ 'requirements' => ['deepLink' => '(?!api(?:/|$)).+']], ], ]; + +// The versioned API base (NL API Design Rules, /core/uri-version): every /api/ route +// also answers under /api/v1/, the server URL the OpenAPI document names. The unversioned +// route stays, so existing clients and the URLs the app generates keep working. Each +// copy gets its own route name through 'postfix'. The deep-link catch-all excludes +// /api/, so the copies can follow it. +foreach ($routes['routes'] as $route) { + if (str_starts_with($route['url'], '/api/') === false) { + continue; + } + + $route['url'] = '/api/v1/'.substr($route['url'], strlen('/api/')); + $route['postfix'] = ($route['postfix'] ?? '').'V1'; + $routes['routes'][] = $route; +} + +return $routes; diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php index 0b7860e23..d48f9f547 100644 --- a/lib/AppInfo/Application.php +++ b/lib/AppInfo/Application.php @@ -36,6 +36,7 @@ use OCA\LaunchPad\Listener\VersionsListener; use OCA\LaunchPad\Listener\ViewAnalyticsListener; use OCA\LaunchPad\Listener\WidgetPlacementsListener; +use OCA\LaunchPad\Middleware\ApiVersionMiddleware; use OCA\LaunchPad\Notification\Notifier; use OCA\LaunchPad\Search\LaunchPadSearchProvider; use OCA\LaunchPad\Service\Connection\ConnectionReporter; @@ -104,6 +105,9 @@ public function register(IRegistrationContext $context): void { // resolved through self::optional(), so an instance without OpenRegister // gets a store that reports `not_configured` rather than a fatal. $this->registerStore(context: $context); + + // Every /api/ response names the answering API version (NL API Design Rules, /core/version-header). + $context->registerMiddleware(ApiVersionMiddleware::class); }//end register() /** diff --git a/lib/Controller/OpenApiController.php b/lib/Controller/OpenApiController.php new file mode 100644 index 000000000..8eb2ccf5f --- /dev/null +++ b/lib/Controller/OpenApiController.php @@ -0,0 +1,117 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Controller; + +use OCA\LaunchPad\AppInfo\Application; +use OCP\App\IAppManager; +use OCP\AppFramework\Controller; +use OCP\AppFramework\Http; +use OCP\AppFramework\Http\Attribute\AnonRateLimit; +use OCP\AppFramework\Http\Attribute\NoCSRFRequired; +use OCP\AppFramework\Http\Attribute\PublicPage; +use OCP\AppFramework\Http\JSONResponse; +use OCP\IRequest; +use stdClass; + +/** + * GET /api/openapi.json. + * + * @category Controller + * @package OCA\LaunchPad\Controller + * @author Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * @psalm-suppress UnusedClass Instantiated by the Nextcloud router. + */ +class OpenApiController extends Controller { + + /** + * Constructor. + * + * @param string $appName The app name. + * @param IRequest $request The request. + * @param IAppManager $appManager Resolves the app path and the installed version. + * + * @psalm-suppress PossiblyUnusedMethod Instantiated via Nextcloud dependency injection. + */ + public function __construct( + string $appName, + IRequest $request, + private readonly IAppManager $appManager, + ) { + parent::__construct(appName: $appName, request: $request); + }//end __construct() + + /** + * The OpenAPI document of this app, readable from any origin. + * + * The document describes the API, not its data, so it is public. Its + * `info.version` is the installed app version, which is also what every + * API response carries in `API-Version`. + * + * @return JSONResponse The document, or 404 when it is not installed. + * + * @PublicPage + * @NoCSRFRequired + */ + #[PublicPage] + #[NoCSRFRequired] + #[AnonRateLimit(limit: 120, period: 60)] + public function show(): JSONResponse { + $document = $this->document(); + $response = new JSONResponse( + ['error' => 'The OpenAPI document is not installed'], + Http::STATUS_NOT_FOUND + ); + if ($document !== null) { + $document->info->version = $this->appManager->getAppVersion(Application::APP_ID); + $response = new JSONResponse($document); + } + + $response->addHeader('Access-Control-Allow-Origin', '*'); + + return $response; + }//end show() + + /** + * The installed OpenAPI document, decoded with empty JSON objects kept as objects. + * + * @return stdClass|null The document, or null when it is missing or not a document. + * + * @psalm-suppress MixedAssignment json_decode() is mixed; the result is checked with instanceof before use. + */ + private function document(): ?stdClass { + $path = $this->appManager->getAppPath(Application::APP_ID).'/openapi.json'; + if (is_readable($path) === false) { + return null; + } + + $document = json_decode((string) file_get_contents($path), false); + if ($document instanceof stdClass && ($document->info ?? null) instanceof stdClass) { + return $document; + } + + return null; + }//end document() +}//end class diff --git a/lib/Middleware/ApiVersionMiddleware.php b/lib/Middleware/ApiVersionMiddleware.php new file mode 100644 index 000000000..dcde3d22d --- /dev/null +++ b/lib/Middleware/ApiVersionMiddleware.php @@ -0,0 +1,101 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Middleware; + +use OCA\LaunchPad\AppInfo\Application; +use OCP\App\IAppManager; +use OCP\AppFramework\Http\Response; +use OCP\AppFramework\Middleware; +use OCP\IRequest; + +/** + * Adds `API-Version` to the responses of LaunchPad's `/api/` endpoints. + * + * @category Middleware + * @package OCA\LaunchPad\Middleware + * @author Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + */ +class ApiVersionMiddleware extends Middleware { + + /** + * The response header that names the answering API version. + */ + public const HEADER = 'API-Version'; + + /** + * Constructor. + * + * @param IRequest $request The current request. + * @param IAppManager $appManager Resolves the installed app version. + * + * @psalm-suppress PossiblyUnusedMethod Instantiated via Nextcloud dependency injection. + */ + public function __construct( + private readonly IRequest $request, + private readonly IAppManager $appManager, + ) { + }//end __construct() + + /** + * Name the API version on a response of an `/api/` endpoint. + * + * Other responses (the SPA pages, public shares, kiosk pages) are returned unchanged. + * + * @param \OCP\AppFramework\Controller $controller The controller that answered. + * @param string $methodName The controller method. + * @param Response $response The response. + * + * @return Response The same response. + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) The signature is the framework's. + */ + public function afterController($controller, $methodName, Response $response): Response { + if ($this->isApiRequest() === false) { + return $response; + } + + $version = $this->appManager->getAppVersion(Application::APP_ID); + if ($version === '') { + return $response; + } + + $response->addHeader(self::HEADER, $version); + + return $response; + }//end afterController() + + /** + * Whether the request is for one of the app's `/api/` endpoints. + * + * @return bool True for an `/api/` path. + */ + private function isApiRequest(): bool { + $path = $this->request->getPathInfo(); + + return is_string($path) === true && str_contains($path, '/api/') === true; + }//end isApiRequest() +}//end class diff --git a/openapi.json b/openapi.json new file mode 100644 index 000000000..a9a8d8600 --- /dev/null +++ b/openapi.json @@ -0,0 +1,198 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "launchpad", + "version": "1.1.7-unstable.20261005190000", + "description": "The LaunchPad API for the endpoints this document covers: the health check and this document. LaunchPad serves more endpoints than are described here (dashboards, widgets, tiles, shares, templates and the admin settings); they are not part of this document yet. The document is served at `/api/openapi.json`, where `info.version` is the installed app version. Every response of an `/api/` endpoint carries that version in the `API-Version` header. Every path also answers without the `/v1` of the server URL.", + "contact": { + "name": "Conduction B.V.", + "email": "info@conduction.nl", + "url": "https://conduction.nl" + }, + "license": { + "name": "EUPL-1.2", + "url": "https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12" + } + }, + "servers": [ + { + "url": "https://{host}/index.php/apps/launchpad/api/v1", + "description": "The LaunchPad API, major version 1, on a Nextcloud instance.", + "variables": { + "host": { + "default": "localhost", + "description": "The host name of the Nextcloud instance." + } + } + } + ], + "tags": [ + { + "name": "health", + "description": "Whether LaunchPad and the apps it depends on are available." + }, + { + "name": "open-api", + "description": "This document." + } + ], + "security": [ + { + "basic_auth": [] + } + ], + "paths": { + "/openapi.json": { + "get": { + "operationId": "open-api-show", + "summary": "The OpenAPI document of this API", + "description": "Returns this document. It needs no authentication and can be read from any origin.", + "tags": [ + "open-api" + ], + "security": [], + "responses": { + "200": { + "description": "The OpenAPI document.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + }, + "404": { + "description": "The document is not installed.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/health": { + "get": { + "operationId": "health-show", + "summary": "Health check", + "description": "The health checks LaunchPad declares in its manifest, run by the OpenRegister observability engine. It needs no authentication.", + "tags": [ + "health" + ], + "security": [], + "responses": { + "200": { + "description": "The checks ran and no critical check failed (`status` `ok` or `degraded`).", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Health" + } + } + } + }, + "503": { + "description": "A critical check failed (`status` `error`), or the observability engine (OpenRegister) is unavailable (`status` `unavailable`, with `error` saying why).", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Health" + } + } + } + } + } + } + } + }, + "components": { + "securitySchemes": { + "basic_auth": { + "type": "http", + "scheme": "basic", + "description": "A Nextcloud user name and password or app password." + } + }, + "headers": { + "API-Version": { + "description": "The version of the API that answered: the installed LaunchPad version.", + "schema": { + "type": "string", + "example": "1.4.0" + } + } + }, + "schemas": { + "Error": { + "type": "object", + "required": [ + "error" + ], + "properties": { + "error": { + "type": "string", + "description": "What went wrong." + } + } + }, + "Health": { + "type": "object", + "required": [ + "status", + "app", + "checks" + ], + "properties": { + "status": { + "type": "string", + "description": "The overall result: `ok`, `degraded`, `error`, or `unavailable` when the engine cannot run." + }, + "app": { + "type": "string", + "example": "launchpad" + }, + "version": { + "type": "string", + "description": "The installed app version; absent when the engine is unavailable." + }, + "error": { + "type": "string", + "description": "Why the health check could not run; only when `status` is `unavailable`." + }, + "checks": { + "type": "array", + "description": "The result of each declared check.", + "items": { + "type": "object", + "additionalProperties": true + } + } + } + } + } + } +} diff --git a/tests/Unit/AppInfo/VersionedRoutesTest.php b/tests/Unit/AppInfo/VersionedRoutesTest.php new file mode 100644 index 000000000..a7248e9b6 --- /dev/null +++ b/tests/Unit/AppInfo/VersionedRoutesTest.php @@ -0,0 +1,59 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace Unit\AppInfo; + +use PHPUnit\Framework\TestCase; + +/** + * Every /api/ route also answers under /api/v1/, the OpenAPI server URL. + */ +class VersionedRoutesTest extends TestCase { + + public function testEveryApiRouteHasAVersionedTwinWithItsOwnName(): void { + $routes = (include dirname(__DIR__, 3).'/appinfo/routes.php')['routes']; + + $plain = []; + $versioned = []; + $names = []; + foreach ($routes as $route) { + $key = ($route['verb'] ?? 'GET').' '.$route['url']; + if (str_starts_with($route['url'], '/api/v1/') === true) { + $versioned[$key] = $route; + } else if (str_starts_with($route['url'], '/api/') === true) { + $plain[$key] = $route; + } + + $name = strtolower($route['name'].($route['postfix'] ?? '')); + $this->assertArrayNotHasKey($name, $names, $name.' is registered twice, so Nextcloud keeps only the last one'); + $names[$name] = true; + } + + $this->assertArrayHasKey('GET /api/openapi.json', $plain); + $this->assertCount(count($plain), $versioned); + foreach ($plain as $key => $route) { + [$verb, $url] = explode(' ', $key, 2); + $twin = ($versioned[$verb.' /api/v1/'.substr($url, 5)] ?? null); + $this->assertNotNull($twin, $key.' has no /api/v1/ twin'); + $this->assertSame($route['name'], $twin['name']); + $this->assertSame(($route['postfix'] ?? '').'V1', $twin['postfix']); + $this->assertSame(($route['requirements'] ?? null), ($twin['requirements'] ?? null)); + $this->assertSame(($route['defaults'] ?? null), ($twin['defaults'] ?? null)); + } + } +} diff --git a/tests/Unit/Controller/OpenApiControllerTest.php b/tests/Unit/Controller/OpenApiControllerTest.php new file mode 100644 index 000000000..30f626d8c --- /dev/null +++ b/tests/Unit/Controller/OpenApiControllerTest.php @@ -0,0 +1,99 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace Unit\Controller; + +use OCA\LaunchPad\Controller\OpenApiController; +use OCP\App\IAppManager; +use OCP\AppFramework\Http\Response; +use OCP\IRequest; +use PHPUnit\Framework\TestCase; +use ReflectionProperty; +use stdClass; + +/** + * The served document, its version, and the missing-document answer. + * + * @covers \OCA\LaunchPad\Controller\OpenApiController + */ +class OpenApiControllerTest extends TestCase { + + private string $dir; + + protected function setUp(): void { + $this->dir = sys_get_temp_dir().'/launchpad-openapi-'.bin2hex(random_bytes(4)); + mkdir($this->dir); + } + + protected function tearDown(): void { + @unlink($this->dir.'/openapi.json'); + @rmdir($this->dir); + } + + private function controller(string $appPath): OpenApiController { + $apps = $this->createMock(IAppManager::class); + $apps->method('getAppPath')->with('launchpad')->willReturn($appPath); + $apps->method('getAppVersion')->with('launchpad')->willReturn('1.2.3'); + + return new OpenApiController('launchpad', $this->createMock(IRequest::class), $apps); + } + + /** + * The headers set on a response, without the defaults getHeaders() merges in from the server. + */ + private function headers(Response $response): array { + return (new ReflectionProperty(Response::class, 'headers'))->getValue($response); + } + + public function testTheDocumentIsServedWithTheInstalledVersion(): void { + file_put_contents($this->dir.'/openapi.json', '{"openapi":"3.0.3","info":{"title":"launchpad","version":"0.0.0"},"paths":{},"components":{"schemas":{}}}'); + + $response = $this->controller($this->dir)->show(); + $data = $response->getData(); + + $this->assertSame(200, $response->getStatus()); + $this->assertInstanceOf(stdClass::class, $data); + $this->assertSame('{"openapi":"3.0.3","info":{"title":"launchpad","version":"1.2.3"},"paths":{},"components":{"schemas":{}}}', json_encode($data)); + $this->assertSame('*', $this->headers($response)['Access-Control-Allow-Origin']); + } + + public function testAMissingDocumentIs404(): void { + $response = $this->controller($this->dir)->show(); + + $this->assertSame(404, $response->getStatus()); + $this->assertSame(['error' => 'The OpenAPI document is not installed'], $response->getData()); + $this->assertSame('*', $this->headers($response)['Access-Control-Allow-Origin']); + } + + public function testAFileWithoutAnInfoObjectIs404(): void { + file_put_contents($this->dir.'/openapi.json', '["not", "a", "document"]'); + + $this->assertSame(404, $this->controller($this->dir)->show()->getStatus()); + } + + public function testTheShippedDocumentIsServed(): void { + $response = $this->controller(dirname(__DIR__, 3))->show(); + $data = $response->getData(); + + $this->assertSame(200, $response->getStatus()); + $this->assertSame('1.2.3', $data->info->version); + $this->assertObjectHasProperty('/openapi.json', $data->paths); + $this->assertObjectHasProperty('contact', $data->info); + $this->assertStringEndsWith('/api/v1', $data->servers[0]->url); + } +} diff --git a/tests/Unit/Middleware/ApiVersionMiddlewareTest.php b/tests/Unit/Middleware/ApiVersionMiddlewareTest.php new file mode 100644 index 000000000..699dd9f61 --- /dev/null +++ b/tests/Unit/Middleware/ApiVersionMiddlewareTest.php @@ -0,0 +1,72 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace Unit\Middleware; + +use OCA\LaunchPad\Middleware\ApiVersionMiddleware; +use OCP\App\IAppManager; +use OCP\AppFramework\Controller; +use OCP\AppFramework\Http\JSONResponse; +use OCP\AppFramework\Http\Response; +use OCP\IRequest; +use PHPUnit\Framework\TestCase; +use ReflectionProperty; + +/** + * Which responses get the header, and with what value. + * + * @covers \OCA\LaunchPad\Middleware\ApiVersionMiddleware + */ +class ApiVersionMiddlewareTest extends TestCase { + + private function middleware(?string $path, string $version = '1.2.3'): ApiVersionMiddleware { + $request = $this->createMock(IRequest::class); + $request->method('getPathInfo')->willReturn($path ?? false); + + $apps = $this->createMock(IAppManager::class); + $apps->method('getAppVersion')->with('launchpad')->willReturn($version); + + return new ApiVersionMiddleware($request, $apps); + } + + private function after(ApiVersionMiddleware $middleware, JSONResponse $response): array { + $this->assertSame($response, $middleware->afterController($this->createMock(Controller::class), 'index', $response)); + + return (new ReflectionProperty(Response::class, 'headers'))->getValue($response); + } + + public function testAnApiResponseNamesTheInstalledVersion(): void { + $this->assertSame('1.2.3', $this->after($this->middleware('/apps/launchpad/api/health'), new JSONResponse([]))['API-Version']); + } + + public function testAVersionedApiResponseNamesItToo(): void { + $this->assertSame('1.2.3', $this->after($this->middleware('/apps/launchpad/api/v1/dashboards'), new JSONResponse([], 404))['API-Version']); + } + + public function testAPageResponseIsLeftAlone(): void { + $this->assertArrayNotHasKey('API-Version', $this->after($this->middleware('/apps/launchpad/s/abc'), new JSONResponse([]))); + } + + public function testARequestWithoutAPathIsLeftAlone(): void { + $this->assertArrayNotHasKey('API-Version', $this->after($this->middleware(null), new JSONResponse([]))); + } + + public function testAnUnknownVersionAddsNoHeader(): void { + $this->assertArrayNotHasKey('API-Version', $this->after($this->middleware('/apps/launchpad/api/x', ''), new JSONResponse([]))); + } +} diff --git a/tests/Unit/Support/StoreWiringTest.php b/tests/Unit/Support/StoreWiringTest.php index 9d0b32611..a79d5b23c 100644 --- a/tests/Unit/Support/StoreWiringTest.php +++ b/tests/Unit/Support/StoreWiringTest.php @@ -67,7 +67,8 @@ private function manifest(): array { public function testTheStorePageCanReachItsEndpoints(): void { $urls = []; foreach ($this->routes() as $route) { - $urls[$route['name']] = $route['url']; + // Keyed as Nextcloud registers it: the /api/v1/ twin carries its own postfix. + $urls[$route['name'].($route['postfix'] ?? '')] = $route['url']; } $this->assertSame('/api/store/items', ($urls['store#search'] ?? null));