diff --git a/appinfo/routes.php b/appinfo/routes.php index 6011967e4..28a0d65b7 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -2,8 +2,11 @@ declare(strict_types=1); -return [ +// Every unversioned API route is also served under /api/v1/; see ApiPathAliases. +return \OCA\Thematiq\Middleware\Support\ApiPathAliases::withVersionedAliases([ 'routes' => [ + // The OpenAPI document of thematiq's own API, public, served under /api/v1/ too. + ['name' => 'openApi#show', 'url' => '/api/openapi.json', 'verb' => 'GET'], // Metrics — served by nldesign's own MetricsController (domain theme // metrics: token sets, custom overrides, theming syncs). Admin-only: // no #[PublicPage]/#[NoAdminRequired], so the SecurityMiddleware @@ -199,4 +202,4 @@ ['name' => 'documentStyle#upload', 'url' => '/settings/document-style/{kind}', 'verb' => 'POST'], ['name' => 'documentStyle#remove', 'url' => '/settings/document-style/{kind}', 'verb' => 'DELETE'], ], -]; +]); diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php index 74f1cf6e6..b24442377 100644 --- a/lib/AppInfo/Application.php +++ b/lib/AppInfo/Application.php @@ -25,6 +25,7 @@ use OCA\Thematiq\Capabilities; use OCA\Thematiq\Listener\ThemeInjectionListener; use OCA\Thematiq\Listener\WorkspaceIconListener; +use OCA\Thematiq\Middleware\ApiContractMiddleware; use OCA\Thematiq\Middleware\ConfigSourceLockMiddleware; use OCA\Thematiq\Service\RuntimeFile\AppDataRuntimeFileStore; use OCA\Thematiq\Service\RuntimeFile\RuntimeFileStore; @@ -109,6 +110,10 @@ public function __construct() { * @spec openspec/specs/mobile-logo-and-touch-icon/spec.md#requirement-the-mobile-logo-and-the-touch-icon-reach-every-page */ public function register(IRegistrationContext $context): void { + // The API contract (version header, deprecation of unversioned paths, + // problem details). Registered first: Nextcloud runs afterController in + // reverse order, so it sees the final response of every other middleware. + $context->registerMiddleware(class: ApiContractMiddleware::class); // Load the app's composer autoloader so this app's classes are resolvable // process-wide, not only inside this app's own container — required so a // cross-app event listener (e.g. the OpenRegister federated-config type) diff --git a/lib/Controller/OpenApiController.php b/lib/Controller/OpenApiController.php new file mode 100644 index 000000000..75991965c --- /dev/null +++ b/lib/Controller/OpenApiController.php @@ -0,0 +1,118 @@ + + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * @spec openspec/specs/api-contract/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\Thematiq\Controller; + +use OCA\Thematiq\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\Thematiq\Controller + * @author Conduction Development Team + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * @spec openspec/specs/api-contract/spec.md + */ +class OpenApiController extends Controller { + + /** + * Constructor. + * + * @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( + IRequest $request, + private readonly IAppManager $appManager, + ) { + parent::__construct(appName: Application::APP_ID, 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 + * + * @spec openspec/specs/api-contract/spec.md + */ + #[PublicPage] + #[NoCSRFRequired] + #[AnonRateLimit(limit: 120, period: 60)] + public function show(): JSONResponse { + $document = $this->document(); + $response = new JSONResponse( + data: ['error' => 'The OpenAPI document is not installed'], + statusCode: Http::STATUS_NOT_FOUND + ); + if ($document !== null) { + $document->info->version = $this->appManager->getAppVersion(appId: Application::APP_ID); + $response = new JSONResponse(data: $document); + } + + $response->addHeader(name: 'Access-Control-Allow-Origin', value: '*'); + + 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. + * + * @spec openspec/specs/api-contract/spec.md + */ + private function document(): ?stdClass { + $path = $this->appManager->getAppPath(appId: 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/ApiContractMiddleware.php b/lib/Middleware/ApiContractMiddleware.php new file mode 100644 index 000000000..2c859a898 --- /dev/null +++ b/lib/Middleware/ApiContractMiddleware.php @@ -0,0 +1,339 @@ + + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * @spec openspec/specs/api-contract/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\Thematiq\Middleware; + +use OCA\Thematiq\AppInfo\Application; +use OCA\Thematiq\Middleware\Support\ApiPathAliases; +use OCA\Thematiq\Middleware\Support\StandardProtocolPaths; +use OCP\App\IAppManager; +use OCP\AppFramework\Http\JSONResponse; +use OCP\AppFramework\Http\Response; +use OCP\AppFramework\Middleware; +use OCP\IRequest; + +/** + * Stamps `API-Version` on API responses, marks an unversioned path deprecated + * in favour of its `/api/v1/` alias, and turns JSON error bodies into problem + * details. Paths that speak a protocol defined elsewhere + * ({@see StandardProtocolPaths}) are left exactly as they are. + * + * An error body keeps every member it already had, so existing callers that + * read `error` or `message` see no change. A body that already uses `type`, + * `title` or `status` for something else is left as it is, because rewriting + * those members would break its callers. + * + * @category Middleware + * @package OCA\Thematiq\Middleware + * @author Conduction Development Team + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * @spec openspec/specs/api-contract/spec.md + */ +class ApiContractMiddleware extends Middleware { + + /** + * The path fragment that marks a request as part of the JSON API. + * + * @var string + */ + private const API_PATH_MARKER = '/api/'; + + /** + * The media type of an RFC 9457 problem details document. + * + * @var string + */ + public const PROBLEM_CONTENT_TYPE = 'application/problem+json; charset=utf-8'; + + /** + * The HTTP reason phrase used as `title` for each error status. + * + * @var array + */ + private const TITLES = [ + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 409 => 'Conflict', + 410 => 'Gone', + 412 => 'Precondition Failed', + 413 => 'Content Too Large', + 415 => 'Unsupported Media Type', + 422 => 'Unprocessable Content', + 423 => 'Locked', + 424 => 'Failed Dependency', + 428 => 'Precondition Required', + 429 => 'Too Many Requests', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + ]; + + /** + * Constructor. + * + * @param IRequest $request The incoming 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() + + /** + * Add the version header and, for a JSON error, the problem details shape. + * + * @param mixed $controller The controller that ran. + * @param string $methodName The method that ran. + * @param Response $response The controller's response. + * + * @return Response The same response, decorated. + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) The Middleware contract fixes this signature. + * + * @spec openspec/specs/api-contract/spec.md + */ + public function afterController($controller, $methodName, Response $response): Response { + return $this->decorate(response: $response); + }//end afterController() + + /** + * Decorate a response when the request is part of the JSON API. + * + * @param Response $response The controller's response. + * + * @return Response The same response, decorated. + * + * @spec openspec/specs/api-contract/spec.md + */ + private function decorate(Response $response): Response { + if ($this->isApiRequest() === false) { + return $response; + } + + $response->addHeader(name: 'API-Version', value: $this->appManager->getAppVersion(appId: Application::APP_ID)); + $this->announceSuccessor(response: $response); + if ($response instanceof JSONResponse) { + $this->decorateError(response: $response); + } + + return $response; + }//end decorate() + + /** + * Whether the request path lies under the app's `/api/` and is not a standard protocol path. + * + * @return bool True for a request on the app's own API. + * + * @SuppressWarnings(PHPMD.StaticAccess) StandardProtocolPaths is a pure lookup that routes.php shares, outside any container. + * + * @spec openspec/specs/api-contract/spec.md + */ + private function isApiRequest(): bool { + $path = $this->request->getPathInfo(); + if (is_string($path) === false || str_contains($path, self::API_PATH_MARKER) === false) { + return false; + } + + return StandardProtocolPaths::matches(path: $path) === false; + }//end isApiRequest() + + /** + * Add the RFC 9745 `Deprecation` header and a `Link` to the successor on an unversioned path. + * + * The path keeps answering exactly as before; only the headers are added. + * + * @param Response $response The response. + * + * @return void + * + * @SuppressWarnings(PHPMD.StaticAccess) ApiPathAliases is a pure lookup that routes.php shares, outside any container. + * + * @spec openspec/specs/api-contract/spec.md + */ + private function announceSuccessor(Response $response): void { + $path = (string)$this->request->getPathInfo(); + $successor = ApiPathAliases::successorOf(path: $path); + if ($successor === null) { + return; + } + + $response->addHeader(name: 'Deprecation', value: ApiPathAliases::DEPRECATED_SINCE); + $response->addHeader( + name: 'Link', + value: '<' . $this->scriptPrefix(pathInfo: $path) . $successor . '>; rel="successor-version"' + ); + }//end announceSuccessor() + + /** + * The front controller that precedes the path info in the request URI, such as `/index.php`. + * + * @param string $pathInfo The request path info. + * + * @return string The prefix, or '' when the URI carries none. + */ + private function scriptPrefix(string $pathInfo): string { + $uri = $this->request->getRequestUri(); + $position = strpos($uri, $pathInfo); + if ($pathInfo === '' || $position === false) { + return ''; + } + + return substr($uri, 0, $position); + }//end scriptPrefix() + + /** + * Serve a JSON error response as problem details when its body allows it. + * + * @param JSONResponse $response The response. + * + * @return void + * + * @spec openspec/specs/api-contract/spec.md + */ + private function decorateError(JSONResponse $response): void { + if ($response->getStatus() < 400) { + return; + } + + $problem = $this->problemFor(data: $response->getData(), status: $response->getStatus()); + if ($problem === null) { + return; + } + + $response->setData(data: $problem); + $response->addHeader(name: 'Content-Type', value: self::PROBLEM_CONTENT_TYPE); + }//end decorateError() + + /** + * The problem details form of an error body, or null when it cannot take that form. + * + * @param mixed $data The error body. + * @param int $status The response status. + * + * @return array|null The body with the problem members first, or null. + * + * @spec openspec/specs/api-contract/spec.md + */ + private function problemFor(mixed $data, int $status): ?array { + if (is_array($data) === false || $this->isListBody(data: $data) === true) { + return null; + } + + $problem = [ + 'type' => 'about:blank', + 'title' => $this->titleOf(status: $status), + 'status' => $status, + ]; + if ($this->conflicts(problem: $problem, data: $data) === true) { + return null; + } + + $detail = $this->detailOf(data: $data); + if ($detail !== null) { + $problem['detail'] = $detail; + } + + return array_merge($problem, $data); + }//end problemFor() + + /** + * The HTTP reason phrase of an error status. + * + * @param int $status The response status. + * + * @return string The reason phrase, or `Error` for a status without one here. + * + * @spec openspec/specs/api-contract/spec.md + */ + private function titleOf(int $status): string { + return (self::TITLES[$status] ?? 'Error'); + }//end titleOf() + + /** + * Whether an error body is a non-empty JSON list, which has no members to keep. + * + * @param array $data The error body. + * + * @return bool True for a list. + * + * @spec openspec/specs/api-contract/spec.md + */ + private function isListBody(array $data): bool { + return $data !== [] && array_is_list($data) === true; + }//end isListBody() + + /** + * Whether the body already uses a problem member with another value. + * + * @param array $problem The problem members. + * @param array $data The error body. + * + * @return bool True when rewriting the body would change one of its members. + * + * @spec openspec/specs/api-contract/spec.md + */ + private function conflicts(array $problem, array $data): bool { + foreach ($problem as $member => $value) { + if (array_key_exists($member, $data) === true && $data[$member] !== $value) { + return true; + } + } + + return false; + }//end conflicts() + + /** + * The human-readable explanation already present in an error body, if any. + * + * @param array $data The error body. + * + * @return string|null The `detail`, `message` or `error` text, or null. + * + * @spec openspec/specs/api-contract/spec.md + */ + private function detailOf(array $data): ?string { + foreach (['detail', 'message', 'error'] as $member) { + $value = ($data[$member] ?? null); + if (is_string($value) === true && $value !== '') { + return $value; + } + } + + return null; + }//end detailOf() +}//end class diff --git a/lib/Middleware/Support/ApiPathAliases.php b/lib/Middleware/Support/ApiPathAliases.php new file mode 100644 index 000000000..4d8eb3c95 --- /dev/null +++ b/lib/Middleware/Support/ApiPathAliases.php @@ -0,0 +1,261 @@ + + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * @spec openspec/specs/api-contract/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\Thematiq\Middleware\Support; + +/** + * Serves every API route under `/api/v1/` as well as at its unversioned path, + * which keeps working and is deprecated. + * + * `/api/` is also served as `/api/v1/`, with the same controller, + * requirements and defaults. Routes that already carry a version + * (`/api/v1/...`, `/api/zgw/zaken/v1/...`) and standard protocol paths + * ({@see StandardProtocolPaths}) get no alias and are not deprecated. + * + * @category Middleware + * @package OCA\Thematiq\Middleware\Support + * @author Conduction Development Team + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * @spec openspec/specs/api-contract/spec.md + */ +final class ApiPathAliases { + + /** + * The prefix of the versioned paths. + * + * @var string + */ + public const VERSION_PREFIX = '/api/v1'; + + /** + * The date the unversioned paths were deprecated (2026-11-12), as an RFC 9745 `Deprecation` value. + * + * @var string + */ + public const DEPRECATED_SINCE = '@1794441600'; + + /** + * Unversioned paths that keep no successor, because a route the app already + * declares under `/api/v1/` answers their versioned form with something else. + * + * @var array + */ + public const WITHOUT_SUCCESSOR = [ + ]; + + /** + * Paths whose versioned form has a new name, as a pattern over the + * unversioned path and its replacement, which follows the kebab-case rule. + * + * @var array + */ + public const RENAMED = [ + ]; + + /** + * The pattern of a path that already names a version. + * + * @var string + */ + private const VERSIONED = '#^/api/(?:[a-z0-9-]+/)*v[0-9]{1,3}(?:/|$)#i'; + + /** + * Whether a path is an unversioned API path, deprecated in favour of its `/api/v1/` alias. + * + * @param string $path An app-relative path or a request path under the app root. + * + * @return bool True for a deprecated unversioned API path. + * + * @SuppressWarnings(PHPMD.StaticAccess) StandardProtocolPaths is a pure lookup, shared with routes.php. + * + * @spec openspec/specs/api-contract/spec.md + */ + public static function isDeprecated(string $path): bool { + $relative = StandardProtocolPaths::appRelative(path: $path); + if (str_starts_with($relative, '/api/') === false || preg_match(self::VERSIONED, $relative) === 1) { + return false; + } + + foreach (self::withoutSuccessor() as $pattern) { + if (preg_match($pattern, $relative) === 1) { + return false; + } + } + + return StandardProtocolPaths::matches(path: $relative) === false; + }//end isDeprecated() + + /** + * The `/api/v1/` path that replaces a deprecated path, keeping whatever precedes the app root. + * + * @param string $path A request path, or an app-relative path. + * + * @return string|null The successor path, or null when the path is not deprecated. + * + * @SuppressWarnings(PHPMD.StaticAccess) StandardProtocolPaths is a pure lookup, shared with routes.php. + * + * @spec openspec/specs/api-contract/spec.md + */ + public static function successorOf(string $path): ?string { + if (self::isDeprecated(path: $path) === false) { + return null; + } + + $relative = StandardProtocolPaths::appRelative(path: $path); + $prefix = substr($path, 0, (strlen($path) - strlen($relative))); + + return $prefix . self::versioned(path: self::renamed(path: $relative)); + }//end successorOf() + + /** + * A routes.php declaration with an `/api/v1/` alias of every unversioned API route. + * + * Routes match in declaration order. The aliases come right after the last + * route the app already declares under `/api/v1/`, so those keep answering + * their paths, and before every other route, so an unversioned route with a + * placeholder as its first segment (`/api/{slug}/...`) or a catch-all can + * never answer a `/api/v1/` request meant for an alias. Among themselves the + * aliases keep the order of the routes they copy. + * + * @param array> $routes The declaration. + * + * @return array> The declaration with the aliases added to `routes`. + * + * @spec openspec/specs/api-contract/spec.md + */ + public static function withVersionedAliases(array $routes): array { + $declared = []; + $insertAt = 0; + foreach (array_values($routes['routes'] ?? []) as $index => $route) { + $declared[self::key(route: $route)] = true; + if (str_starts_with('/' . ltrim((string)($route['url'] ?? ''), '/'), self::VERSION_PREFIX . '/') === true) { + $insertAt = ($index + 1); + } + } + + $aliases = []; + foreach (($routes['routes'] ?? []) as $route) { + $url = '/' . ltrim((string)($route['url'] ?? ''), '/'); + if (self::isDeprecated(path: $url) === false || self::isApiFallback(route: $route) === true) { + continue; + } + + $alias = array_merge( + $route, + [ + 'url' => self::versioned(path: self::renamed(path: $url)), + 'postfix' => ($route['postfix'] ?? '') . 'v1', + ] + ); + if (isset($declared[self::key(route: $alias)]) === false) { + $aliases[] = $alias; + } + } + + $original = array_values($routes['routes'] ?? []); + $routes['routes'] = array_merge(array_slice($original, 0, $insertAt), $aliases, array_slice($original, $insertAt)); + + return $routes; + }//end withVersionedAliases() + + /** + * Whether a route is the API fallback, a single placeholder after `/api/` that spans segments. + * + * It answers every API path no other route does, versioned ones included, + * so it needs no alias, and an alias placed before the versioned routes + * would take their requests. + * + * @param array $route The route. + * + * @return bool True for the API fallback. + * + * @spec openspec/specs/api-contract/spec.md + */ + public static function isApiFallback(array $route): bool { + $url = '/' . ltrim((string)($route['url'] ?? ''), '/'); + if (preg_match('#^/api/\{(\w+)\}$#', $url, $match) !== 1) { + return false; + } + + $requirement = (string)($route['requirements'][$match[1]] ?? '[^/]+'); + + return preg_match('#^(?:' . $requirement . ')$#', 'a/b') === 1; + }//end isApiFallback() + + /** + * The current name of a path, which differs from the path only when RENAMED lists it. + * + * @param string $path An app-relative path. + * + * @return string The path, renamed where it has a new name. + */ + private static function renamed(string $path): string { + foreach (self::renames() as $pattern => $replacement) { + $current = preg_replace($pattern, $replacement, $path); + if (is_string($current) === true && $current !== $path) { + return $current; + } + } + + return $path; + }//end renamed() + + /** + * The renamed paths. + * + * @return array The replacements by pattern. + */ + private static function renames(): array { + return self::RENAMED; + }//end renames() + + /** + * The patterns of the unversioned paths that keep no successor. + * + * @return array The patterns by reason. + */ + private static function withoutSuccessor(): array { + return self::WITHOUT_SUCCESSOR; + }//end withoutSuccessor() + + /** + * The verb and path a route registers, which two routes cannot share. + * + * @param array $route The route. + * + * @return string The verb and the path with one leading slash. + */ + private static function key(array $route): string { + return strtoupper((string)($route['verb'] ?? 'GET')) . ' /' . ltrim((string)($route['url'] ?? ''), '/'); + }//end key() + + /** + * The `/api/v1/` form of an unversioned API path. + * + * @param string $path An app-relative path starting with `/api/`. + * + * @return string The versioned path. + */ + private static function versioned(string $path): string { + return self::VERSION_PREFIX . substr($path, strlen('/api')); + }//end versioned() +}//end class diff --git a/lib/Middleware/Support/StandardProtocolPaths.php b/lib/Middleware/Support/StandardProtocolPaths.php new file mode 100644 index 000000000..7d2cfa931 --- /dev/null +++ b/lib/Middleware/Support/StandardProtocolPaths.php @@ -0,0 +1,96 @@ + + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * @spec openspec/specs/api-contract/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\Thematiq\Middleware\Support; + +/** + * Recognises the API paths whose request, response and error formats a + * standard or a peer instance defines, so the app's own API conventions + * (versioned paths, problem details, the `API-Version` header) leave them alone. + * + * Paths are relative to the app root (`/api/...`); a full request path such as + * `/index.php/apps/thematiq/api/health` is accepted too. + * + * @category Middleware + * @package OCA\Thematiq\Middleware\Support + * @author Conduction Development Team + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * @spec openspec/specs/api-contract/spec.md + */ +final class StandardProtocolPaths { + + /** + * The app root that precedes every app-relative path in a request path. + * + * @var string + */ + private const APP_ROOT = '/apps/thematiq'; + + /** + * One pattern per protocol, matched against the app-relative path. + * + * @var array + */ + public const PATTERNS = [ + 'Health check' => '#^/api/health$#', + 'Prometheus metrics' => '#^/api/metrics$#', + ]; + + /** + * Whether a path speaks a protocol defined outside the app. + * + * @param string $path An app-relative path or a request path under the app root. + * + * @return bool True for a standard protocol path. + * + * @spec openspec/specs/api-contract/spec.md + */ + public static function matches(string $path): bool { + $relative = self::appRelative(path: $path); + foreach (self::PATTERNS as $pattern) { + if (preg_match($pattern, $relative) === 1) { + return true; + } + } + + return false; + }//end matches() + + /** + * The path relative to the app root, leading slash included. + * + * @param string $path An app-relative path or a request path under the app root. + * + * @return string The app-relative path. + * + * @spec openspec/specs/api-contract/spec.md + */ + public static function appRelative(string $path): string { + $candidate = '/' . ltrim($path, '/'); + $rootAt = strpos($candidate, self::APP_ROOT . '/'); + if ($rootAt === false) { + return $candidate; + } + + return substr($candidate, $rootAt + strlen(self::APP_ROOT)); + }//end appRelative() +}//end class diff --git a/openapi.json b/openapi.json new file mode 100644 index 000000000..c051563e7 --- /dev/null +++ b/openapi.json @@ -0,0 +1,700 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Thematiq", + "version": "1.2.28-unstable.20261014120000", + "description": "The JSON API of Thematiq, the theming app for Nextcloud: design token sets and their deprecations, app brands, document styles, workspace icons, contrast checks and the settings behind them.\n\nEvery path is served under `/api/v1/`, the version this document describes. The unversioned `/api/` paths keep working, are deprecated, and name their `/api/v1/` successor in a `Link` header next to a `Deprecation` header. Errors are RFC 9457 problem details (`application/problem+json`), and every response carries an `API-Version` header. Paths that implement an external standard keep the formats of that standard and are not described here.", + "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/thematiq/api/v1", + "description": "The Thematiq API, version 1, on a Nextcloud instance.", + "variables": { + "host": { + "default": "localhost", + "description": "The host name of the Nextcloud instance." + } + } + } + ], + "security": [ + { + "basic_auth": [] + }, + { + "bearer_auth": [] + } + ], + "tags": [ + { + "name": "app-brand", + "description": "The Brand per app block (`/settings/app-brands`, admin) and the logos (`/api/app-brands/{appId}/logo/{size}`, signed-in users, since branded pages are signed-in pages)." + }, + { + "name": "assistant-mark", + "description": "`GET /api/assistant-mark` for signed-in users (the contract with the assistant panel in nextcloud-vue), `GET` and `POST /settings/assistant-mark` for administrators." + }, + { + "name": "catalog", + "description": "Non-admin, read-only token-set catalogue endpoint for a leaf app's own picker (e.g. a builder tool inside another Conduction app)." + }, + { + "name": "contrast", + "description": "Shared WCAG contrast-evaluation endpoint for a leaf app's own picker or free-hand color authoring feature." + }, + { + "name": "document-style", + "description": "Signed-in users read the profile (`GET /api/document-style`) and its assets; administrators manage the Documents block under `/settings/document-style`." + }, + { + "name": "my-groups", + "description": "`GET /api/my-groups/house-style` lists the delegated groups the signed-in user is subadmin of; `POST /api/my-groups/{group}/house-style` sets one. Both need the delegated setting {@see GroupHouseStyle} (an administrator, or a member of a group the administrator granted it to); the write also checks, on every call, that the user is subadmin of the named group and that the set is on its allowed list, answering 403 otherwise." + }, + { + "name": "open-api", + "description": "The OpenAPI document that describes this API." + }, + { + "name": "shell-token", + "description": "GET /api/shell-tokens: the active token set as eighteen shell roles and a logo, for a product that wears the same shell as this Nextcloud (the OpenProject plugin is the first)." + }, + { + "name": "token-reference", + "description": "The token reference of any available token set, custom sets included, for any signed-in user. `#[NoAdminRequired]`, never `#[PublicPage]`: a custom set is the organisation's own and may not be published yet. A controller of its own next to CatalogController, whose constructor other code and tests pin." + }, + { + "name": "workspace-icon", + "description": "The two workspace images." + } + ], + "paths": { + "/app-brands/{appId}/logo/{size}": { + "get": { + "operationId": "app-brand-logo", + "summary": "A brand logo, for signed-in users", + "description": "A brand logo, for signed-in users. Needs a signed-in Nextcloud user.", + "tags": [ + "app-brand" + ], + "parameters": [ + { + "name": "appId", + "in": "path", + "required": true, + "description": "The app id.", + "schema": { + "type": "string" + } + }, + { + "name": "size", + "in": "path", + "required": true, + "description": "`large` or `small`.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/assistant-mark": { + "get": { + "operationId": "assistant-mark-show", + "summary": "The mark for the signed-in user's assistant panel. No session, no answer: the route has no public-page attribute, so Nextcloud refuses anonymous calls", + "description": "The mark for the signed-in user's assistant panel. No session, no answer: the route has no public-page attribute, so Nextcloud refuses anonymous calls. Needs a signed-in Nextcloud user.", + "tags": [ + "assistant-mark" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/contrast/evaluate": { + "post": { + "operationId": "contrast-evaluate", + "summary": "POST /api/contrast/evaluate — evaluate arbitrary candidate colors against a caller-supplied background", + "description": "POST /api/contrast/evaluate — evaluate arbitrary candidate colors against a caller-supplied background. Accepts `{ candidates: [{ name, value, role: \"text\"|\"ui\" }], background: string }` and returns `{ results: [{ name, ratio, threshold, level, pass, unevaluated? }] }`. A malformed request (missing/invalid `candidates` or `background`) returns 400, never a silent 200 with fabricated results. Public: it needs no login.", + "tags": [ + "contrast" + ], + "security": [], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + } + } + } + }, + "/document-style": { + "get": { + "operationId": "document-style-show", + "summary": "The profile for the signed-in user. Without a session Nextcloud refuses the request", + "description": "The profile for the signed-in user. Without a session Nextcloud refuses the request. Needs a signed-in Nextcloud user.", + "tags": [ + "document-style" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/document-style/{kind}": { + "get": { + "operationId": "document-style-asset", + "summary": "A document asset, for signed-in users", + "description": "A document asset, for signed-in users. Needs a signed-in Nextcloud user.", + "tags": [ + "document-style" + ], + "parameters": [ + { + "name": "kind", + "in": "path", + "required": true, + "description": "`logo` or `cover`.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/my-groups/house-style": { + "get": { + "operationId": "my-groups-index", + "summary": "The delegated groups of the signed-in user", + "description": "The delegated groups of the signed-in user. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "my-groups" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/my-groups/{group}/house-style": { + "post": { + "operationId": "my-groups-update", + "summary": "Set the house style of a delegated group", + "description": "Set the house style of a delegated group. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "my-groups" + ], + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "description": "The group id.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tokenSet": { + "type": "string", + "description": "The chosen set." + } + }, + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "422": { + "$ref": "#/components/responses/Problem422" + } + } + } + }, + "/openapi.json": { + "get": { + "operationId": "open-api-show", + "summary": "The OpenAPI document of this API", + "description": "Returns this document, with `info.version` set to the installed version. It needs no login 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" + }, + "access-control-allow-origin": { + "description": "Always `*`.", + "schema": { + "type": "string", + "enum": [ + "*" + ] + } + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/shell-tokens": { + "get": { + "operationId": "shell-token-show", + "summary": "The shell tokens document, or 304 when the reader already holds this revision", + "description": "The shell tokens document, or 304 when the reader already holds this revision. `Cache-Control: no-cache` lets a reader keep the answer and ask again with `If-None-Match`, where Nextcloud's default forbids storing it. Public: it needs no login.", + "tags": [ + "shell-token" + ], + "security": [], + "responses": { + "304": { + "description": "A redirect to the result.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + }, + "Location": { + "description": "Where the result is.", + "schema": { + "type": "string" + } + } + } + } + } + } + }, + "/token-deprecations": { + "get": { + "operationId": "catalog-deprecations", + "summary": "GET /api/token-deprecations — every token deprecation, for consuming apps", + "description": "GET /api/token-deprecations — every token deprecation, for consuming apps. Token names and dates only, the same for every user, so there is no per-object check to make; a request without a session is refused by the absence of `#[PublicPage]`. Public: it needs no login.", + "tags": [ + "catalog" + ], + "security": [], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + } + } + } + }, + "/token-sets": { + "get": { + "operationId": "catalog-token-sets", + "summary": "GET /api/token-sets — the closed, non-admin catalogue projection", + "description": "GET /api/token-sets — the closed, non-admin catalogue projection. Reuses `TokenSetService::getAvailableTokenSets()` for discovery via `getPublicCatalogue()` (zero duplication of the scan/manifest-merge logic) and returns exactly the 5-field shape: `id`, `name`, `design_system`, `theming` (`primary_color`, `background_color`, `logo?`), `wcagLevel`. No `description`, `custom`, `warnings`, `upstreamVersion`, or `upstreamRef` — those are admin-only fields on the existing `GET /settings/tokensets` response. Needs a signed-in Nextcloud user.", + "tags": [ + "catalog" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/token-sets/{id}/reference": { + "get": { + "operationId": "token-reference-show", + "summary": "GET /api/token-sets/{id}/reference?format=md|html[&download=1]", + "description": "GET /api/token-sets/{id}/reference?format=md|html[&download=1]. Needs a signed-in Nextcloud user.", + "tags": [ + "token-reference" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The token set id.", + "schema": { + "type": "string" + } + }, + { + "name": "download", + "in": "query", + "required": false, + "description": "The download.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/workspace-icons/{kind}": { + "get": { + "operationId": "workspace-icon-show", + "summary": "Serve an image to anyone: a phone fetches the touch icon without a session, and the login page draws the header too. Instance-wide brand images,...", + "description": "Serve an image to anyone: a phone fetches the touch icon without a session, and the login page draws the header too. Instance-wide brand images, the same for every visitor. Public: it needs no login.", + "tags": [ + "workspace-icon" + ], + "security": [], + "parameters": [ + { + "name": "kind", + "in": "path", + "required": true, + "description": "`mobile-logo` or `touch-icon`.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + } + }, + "components": { + "securitySchemes": { + "basic_auth": { + "type": "http", + "scheme": "basic", + "description": "A Nextcloud user name with an app password." + }, + "bearer_auth": { + "type": "http", + "scheme": "bearer", + "description": "A Nextcloud OAuth2 access token." + } + }, + "headers": { + "API-Version": { + "description": "The version of the API that answered, which is the installed app version.", + "schema": { + "type": "string", + "example": "1.0.0" + } + } + }, + "schemas": { + "Problem": { + "type": "object", + "description": "An RFC 9457 problem details document. The members the error already had are kept next to these.", + "properties": { + "type": { + "type": "string", + "description": "A URI reference that identifies the problem type.", + "example": "about:blank" + }, + "title": { + "type": "string", + "description": "A short summary of the problem type.", + "example": "Not Found" + }, + "status": { + "type": "integer", + "description": "The HTTP status code.", + "example": 404 + }, + "detail": { + "type": "string", + "description": "An explanation of this occurrence of the problem." + }, + "instance": { + "type": "string", + "description": "A URI reference that identifies this occurrence." + } + }, + "required": [ + "type", + "title", + "status" + ], + "additionalProperties": true + } + }, + "responses": { + "Problem400": { + "description": "Bad request", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem401": { + "description": "Unauthorized", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem403": { + "description": "Forbidden", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem404": { + "description": "Not found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem422": { + "description": "Unprocessable content", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + } + } + } +} diff --git a/openspec/specs/api-contract/spec.md b/openspec/specs/api-contract/spec.md new file mode 100644 index 000000000..461afa197 --- /dev/null +++ b/openspec/specs/api-contract/spec.md @@ -0,0 +1,82 @@ +--- +status: done +--- + +# API contract + +## Purpose + +How Thematiq's JSON API meets the NL API Design Rules that apply to every endpoint, whatever it does: each path carries the major version, each response says which version answered it, errors come back as RFC 9457 problem details, and the OpenAPI document that describes the API is published by the API itself. The document lives at `openapi.json` in the repository root and is linted with the Spectral ruleset of the API Design Rules (`https://static.developer.overheid.nl/adr/ruleset.yaml`). + +## Requirements + +### Requirement: Every API response carries the API version + +Every response of an endpoint under `/api/` MUST carry an `API-Version` header with the installed app version, which is also the `info.version` of the OpenAPI document (/core/version-header). Responses outside `/api/` MUST NOT carry it. + +#### Scenario: A successful API call names its version + +@e2e exclude a response header, not browser behaviour; covered by PHPUnit ApiContractMiddlewareTest. + +- GIVEN Thematiq is installed at version 1.2.3 +- WHEN a client calls any endpoint under `/index.php/apps/thematiq/api/` +- THEN the response MUST carry `API-Version: 1.2.3` + +### Requirement: API errors are problem details + +A JSON error response (status 400 or higher) of an endpoint under `/api/` MUST be served as `application/problem+json` with the members `type`, `title` and `status`, plus `detail` when the body already carries a `detail`, `message` or `error` text (/core/error-handling/problem-details). Every member the body already had MUST be kept, so existing callers see no change. A body that already uses `type`, `title` or `status` for something else, or that is a JSON list, MUST be left as it is. + +#### Scenario: A not-found error becomes problem details + +@e2e exclude a content type and a body shape, not browser behaviour; covered by PHPUnit ApiContractMiddlewareTest. + +- GIVEN an endpoint answers `404` with `{"error": "Thing not found"}` +- WHEN the response leaves the app +- THEN its content type MUST be `application/problem+json` +- AND its body MUST be `{"type": "about:blank", "title": "Not Found", "status": 404, "detail": "Thing not found", "error": "Thing not found"}` + +### Requirement: The API publishes its own OpenAPI document + +`GET /index.php/apps/thematiq/api/v1/openapi.json` MUST return the OpenAPI document without authentication, with `Access-Control-Allow-Origin: *` and with `info.version` set to the installed app version (/core/publish-openapi). When the document is not installed it MUST answer 404. + +#### Scenario: Anyone can read the API description + +@e2e exclude an anonymous JSON endpoint, not browser behaviour; covered by PHPUnit OpenApiControllerTest. + +- GIVEN a client that is not logged in +- WHEN it requests `/index.php/apps/thematiq/api/v1/openapi.json` +- THEN it MUST receive the OpenAPI document with status 200 +- AND the response MUST carry `Access-Control-Allow-Origin: *` + +### Requirement: Every API path is served under its major version + +Every route under `/api/` MUST also be served under `/api/v1/`, with the same controller, requirements and defaults (/core/uri-version). A route the app already declares under `/api/v1/` keeps its path; an unversioned path whose versioned form such a route answers keeps no successor and is listed in `ApiPathAliases::WITHOUT_SUCCESSOR`. The unversioned path MUST keep answering exactly as before, and its responses MUST carry a `Deprecation` header and a `Link` header naming the `/api/v1/` successor with `rel="successor-version"` (/core/deprecation-schedule). The OpenAPI document MUST name `/index.php/apps/thematiq/api/v1` as its server and MUST describe every versioned path the app routes, and no other path. + +#### Scenario: An unversioned path names its successor + +@e2e exclude response headers, not browser behaviour; covered by PHPUnit ApiContractMiddlewareTest and ApiPathAliasesTest. + +- GIVEN a client calls `GET /index.php/apps/thematiq/api/settings` +- THEN it MUST receive the same answer as before +- AND the response MUST carry `Deprecation: @1794441600` +- AND the response MUST carry `Link: ; rel="successor-version"` + +#### Scenario: The versioned path answers the same request + +@e2e exclude a route table property; covered by PHPUnit ApiPathAliasesTest and OpenApiDocumentTest. + +- GIVEN a route `/api/settings` +- WHEN a client calls `/index.php/apps/thematiq/api/v1/settings` +- THEN the same controller method MUST answer it, without a `Deprecation` header + +### Requirement: Standard protocol paths keep their own formats + +Paths that implement a protocol defined elsewhere (Health check, Prometheus metrics) MUST NOT get a `/api/v1/` alias, a `Deprecation` header, an `API-Version` header or a problem details rewrite: their formats belong to their standard. They are listed in `lib/Middleware/Support/StandardProtocolPaths.php` and are not described in the OpenAPI document. + +#### Scenario: A protocol path is left alone + +@e2e exclude a response shape, not browser behaviour; covered by PHPUnit ApiContractMiddlewareTest. + +- GIVEN a client calls `/index.php/apps/thematiq/api/health` and it answers `400` with `{"error": "x"}` +- THEN the body MUST stay `{"error": "x"}` +- AND the response MUST carry no `API-Version` and no `Deprecation` header diff --git a/tests/Unit/Controller/OpenApiControllerTest.php b/tests/Unit/Controller/OpenApiControllerTest.php new file mode 100644 index 000000000..85016870f --- /dev/null +++ b/tests/Unit/Controller/OpenApiControllerTest.php @@ -0,0 +1,109 @@ + + * @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 OCA\Thematiq\Tests\Unit\Controller; + +use OCA\Thematiq\Controller\OpenApiController; +use OCP\App\IAppManager; +use OCP\AppFramework\Http\Response; +use OCP\IRequest; +use PHPUnit\Framework\TestCase; +use ReflectionProperty; + +/** + * Pins what GET /api/openapi.json serves. + * + * @covers \OCA\Thematiq\Controller\OpenApiController + */ +class OpenApiControllerTest extends TestCase { + + /** + * Build the controller over an app directory. + * + * @param string $appPath The app directory. + * + * @return OpenApiController The controller. + */ + private function controller(string $appPath): OpenApiController { + $appManager = $this->createMock(originalClassName: IAppManager::class); + $appManager->method('getAppPath')->willReturn($appPath); + $appManager->method('getAppVersion')->willReturn('9.8.7'); + + return new OpenApiController( + request: $this->createMock(originalClassName: IRequest::class), + appManager: $appManager + ); + }//end controller() + + /** + * The shipped document is served with the installed version, readable from any origin. + * + * @return void + */ + public function testServesTheShippedDocument(): void { + $response = $this->controller(appPath: dirname(__DIR__, 3))->show(); + $document = json_decode((string)json_encode($response->getData()), true); + + $this->assertSame(expected: 200, actual: $response->getStatus()); + $this->assertSame(expected: '*', actual: $this->headersOf(response: $response)['Access-Control-Allow-Origin']); + $this->assertSame(expected: '9.8.7', actual: $document['info']['version']); + $this->assertArrayHasKey(key: '/openapi.json', array: $document['paths']); + }//end testServesTheShippedDocument() + + /** + * Empty JSON objects in the document stay objects when served. + * + * @return void + */ + public function testEmptyObjectsStayObjects(): void { + $dir = sys_get_temp_dir() . '/openapi-' . uniqid(); + mkdir($dir); + file_put_contents($dir . '/openapi.json', '{"openapi":"3.0.3","info":{"version":"0"},"paths":{"/x":{"get":{"security":[{}]}}}}'); + + $response = $this->controller(appPath: $dir)->show(); + unlink($dir . '/openapi.json'); + rmdir($dir); + + $this->assertStringContainsString(needle: '"security":[{}]', haystack: (string)json_encode($response->getData())); + }//end testEmptyObjectsStayObjects() + + /** + * Without a document the endpoint answers 404 rather than an empty document. + * + * @return void + */ + public function testMissingDocumentIsNotFound(): void { + $response = $this->controller(appPath: sys_get_temp_dir() . '/no-such-app-' . uniqid())->show(); + + $this->assertSame(expected: 404, actual: $response->getStatus()); + $this->assertSame(expected: '*', actual: $this->headersOf(response: $response)['Access-Control-Allow-Origin']); + }//end testMissingDocumentIsNotFound() + + /** + * The headers a response set, read without the server container that + * Response::getHeaders() needs. + * + * @param Response $response The response. + * + * @return array The headers by name. + */ + private function headersOf(Response $response): array { + $property = new ReflectionProperty(Response::class, 'headers'); + + return $property->getValue($response); + }//end headersOf() +}//end class diff --git a/tests/Unit/Middleware/ApiContractMiddlewareTest.php b/tests/Unit/Middleware/ApiContractMiddlewareTest.php new file mode 100644 index 000000000..e9cb11e65 --- /dev/null +++ b/tests/Unit/Middleware/ApiContractMiddlewareTest.php @@ -0,0 +1,223 @@ + + * @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 OCA\Thematiq\Tests\Unit\Middleware; + +use OCA\Thematiq\Middleware\ApiContractMiddleware; +use OCP\App\IAppManager; +use OCP\AppFramework\Http\DataDisplayResponse; +use OCP\AppFramework\Http\JSONResponse; +use OCP\AppFramework\Http\Response; +use OCP\IRequest; +use PHPUnit\Framework\TestCase; +use ReflectionProperty; + +/** + * Pins the `API-Version` header, the deprecation of unversioned paths and the + * problem details shape of API errors. + * + * @covers \OCA\Thematiq\Middleware\ApiContractMiddleware + * @uses \OCA\Thematiq\Middleware\Support\ApiPathAliases + * @uses \OCA\Thematiq\Middleware\Support\StandardProtocolPaths + */ +class ApiContractMiddlewareTest extends TestCase { + + /** + * Run the middleware for a request on the given path. + * + * @param string|false $path The request path info. + * @param Response $response The controller response. + * + * @return Response The decorated response. + */ + private function decorate(string|false $path, Response $response): Response { + $request = $this->createMock(originalClassName: IRequest::class); + $request->method('getPathInfo')->willReturn($path); + $request->method('getRequestUri')->willReturn('/index.php' . (string)$path . '?q=1'); + $appManager = $this->createMock(originalClassName: IAppManager::class); + $appManager->method('getAppVersion')->willReturn('1.2.3'); + + return (new ApiContractMiddleware(request: $request, appManager: $appManager)) + ->afterController(controller: null, methodName: 'any', response: $response); + }//end decorate() + + /** + * A successful API response carries the installed version and keeps its body. + * + * @return void + */ + public function testApiResponseCarriesTheVersionHeader(): void { + $response = $this->decorate(path: '/apps/thematiq/api/things', response: new JSONResponse(data: ['id' => 1])); + + $this->assertSame(expected: '1.2.3', actual: $this->headersOf(response: $response)['API-Version']); + $this->assertSame(expected: ['id' => 1], actual: $response->getData()); + $this->assertSame(expected: 'application/json; charset=utf-8', actual: $this->headersOf(response: $response)['Content-Type']); + }//end testApiResponseCarriesTheVersionHeader() + + /** + * A page response outside the API is left alone. + * + * @return void + */ + public function testNonApiResponseIsUntouched(): void { + $response = $this->decorate(path: '/apps/thematiq/', response: new JSONResponse(data: ['error' => 'x'], statusCode: 404)); + + $this->assertArrayNotHasKey(key: 'API-Version', array: $this->headersOf(response: $response)); + $this->assertSame(expected: ['error' => 'x'], actual: $response->getData()); + + $missing = $this->decorate(path: false, response: new JSONResponse(data: [])); + $this->assertArrayNotHasKey(key: 'API-Version', array: $this->headersOf(response: $missing)); + }//end testNonApiResponseIsUntouched() + + /** + * A JSON error becomes problem details and keeps the members it had. + * + * @return void + */ + public function testJsonErrorBecomesProblemDetails(): void { + $response = $this->decorate( + path: '/apps/thematiq/api/things/7', + response: new JSONResponse(data: ['error' => 'Thing not found'], statusCode: 404) + ); + + $expected = [ + 'type' => 'about:blank', + 'title' => 'Not Found', + 'status' => 404, + 'detail' => 'Thing not found', + 'error' => 'Thing not found', + ]; + $this->assertSame(expected: $expected, actual: $response->getData()); + $this->assertSame(expected: ApiContractMiddleware::PROBLEM_CONTENT_TYPE, actual: $this->headersOf(response: $response)['Content-Type']); + $this->assertSame(expected: '1.2.3', actual: $this->headersOf(response: $response)['API-Version']); + }//end testJsonErrorBecomesProblemDetails() + + /** + * `message` is used as detail when there is no `detail`, and an unknown status still gets a title. + * + * @return void + */ + public function testMessageIsUsedAsDetailAndUnknownStatusHasATitle(): void { + $response = $this->decorate( + path: '/apps/thematiq/api/things', + response: new JSONResponse(data: ['message' => 'Teapot', 'error' => 'ignored'], statusCode: 418) + ); + + $data = $response->getData(); + $this->assertSame(expected: 'Error', actual: $data['title']); + $this->assertSame(expected: 'Teapot', actual: $data['detail']); + $this->assertSame(expected: 418, actual: $data['status']); + }//end testMessageIsUsedAsDetailAndUnknownStatusHasATitle() + + /** + * A body that uses a problem member for something else, or is a list, keeps its shape. + * + * @return void + */ + public function testConflictingOrListBodiesAreLeftAlone(): void { + $conflict = $this->decorate( + path: '/apps/thematiq/api/things', + response: new JSONResponse(data: ['status' => 'error', 'message' => 'No'], statusCode: 400) + ); + $this->assertSame(expected: ['status' => 'error', 'message' => 'No'], actual: $conflict->getData()); + $this->assertSame(expected: 'application/json; charset=utf-8', actual: $this->headersOf(response: $conflict)['Content-Type']); + + $list = $this->decorate(path: '/apps/thematiq/api/things', response: new JSONResponse(data: ['a', 'b'], statusCode: 400)); + $this->assertSame(expected: ['a', 'b'], actual: $list->getData()); + }//end testConflictingOrListBodiesAreLeftAlone() + + /** + * A body that already is problem details is kept, and an empty body gets the members. + * + * @return void + */ + public function testExistingProblemAndEmptyBodies(): void { + $problem = ['type' => 'about:blank', 'title' => 'Forbidden', 'status' => 403, 'detail' => 'No access']; + $kept = $this->decorate(path: '/apps/thematiq/api/things', response: new JSONResponse(data: $problem, statusCode: 403)); + $this->assertSame(expected: $problem, actual: $kept->getData()); + + $empty = $this->decorate(path: '/apps/thematiq/api/things', response: new JSONResponse(data: [], statusCode: 500)); + $this->assertSame(expected: ['type' => 'about:blank', 'title' => 'Internal Server Error', 'status' => 500], actual: $empty->getData()); + }//end testExistingProblemAndEmptyBodies() + + /** + * A non-JSON error response gets the header but no body rewrite. + * + * @return void + */ + public function testNonJsonErrorOnlyGetsTheHeader(): void { + $response = $this->decorate(path: '/apps/thematiq/api/files', response: new DataDisplayResponse(data: 'gone', statusCode: 410)); + + $this->assertSame(expected: '1.2.3', actual: $this->headersOf(response: $response)['API-Version']); + $this->assertSame(expected: 'gone', actual: $response->getData()); + }//end testNonJsonErrorOnlyGetsTheHeader() + + /** + * An unversioned API path keeps answering and names its `/api/v1/` successor. + * + * @return void + */ + public function testUnversionedPathAnnouncesItsSuccessor(): void { + $response = $this->decorate(path: '/apps/thematiq/api/things/7/parts', response: new JSONResponse(data: ['id' => 7])); + $headers = $this->headersOf(response: $response); + + $this->assertSame(expected: ['id' => 7], actual: $response->getData()); + $this->assertSame(expected: '@1794441600', actual: $headers['Deprecation']); + $this->assertSame(expected: '; rel="successor-version"', actual: $headers['Link']); + }//end testUnversionedPathAnnouncesItsSuccessor() + + /** + * A versioned API path is not deprecated, and still carries the version. + * + * @return void + */ + public function testVersionedPathIsNotDeprecated(): void { + $headers = $this->headersOf(response: $this->decorate(path: '/apps/thematiq/api/v1/things/7', response: new JSONResponse(data: []))); + + $this->assertSame(expected: '1.2.3', actual: $headers['API-Version']); + $this->assertArrayNotHasKey(key: 'Deprecation', array: $headers); + $this->assertArrayNotHasKey(key: 'Link', array: $headers); + }//end testVersionedPathIsNotDeprecated() + + /** + * A path that speaks a protocol defined elsewhere keeps that protocol's formats. + * + * @return void + */ + public function testStandardProtocolPathIsUntouched(): void { + $response = $this->decorate(path: '/apps/thematiq/api/health', response: new JSONResponse(data: ['error' => 'x'], statusCode: 400)); + $headers = $this->headersOf(response: $response); + + $this->assertSame(expected: ['error' => 'x'], actual: $response->getData()); + $this->assertArrayNotHasKey(key: 'API-Version', array: $headers); + $this->assertArrayNotHasKey(key: 'Deprecation', array: $headers); + }//end testStandardProtocolPathIsUntouched() + + /** + * The headers a response set, read without the server container that + * Response::getHeaders() needs. + * + * @param Response $response The response. + * + * @return array The headers by name. + */ + private function headersOf(Response $response): array { + $property = new ReflectionProperty(Response::class, 'headers'); + + return $property->getValue($response); + }//end headersOf() +}//end class diff --git a/tests/Unit/Middleware/Support/ApiPathAliasesTest.php b/tests/Unit/Middleware/Support/ApiPathAliasesTest.php new file mode 100644 index 000000000..da8663459 --- /dev/null +++ b/tests/Unit/Middleware/Support/ApiPathAliasesTest.php @@ -0,0 +1,306 @@ + + * @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 OCA\Thematiq\Tests\Unit\Middleware\Support; + +use OCA\Thematiq\Middleware\Support\ApiPathAliases; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\TestCase; + +/** + * Every unversioned API route is also served under `/api/v1/`, the old paths + * keep working, and no alias takes a request meant for another route. + * + * @covers \OCA\Thematiq\Middleware\Support\ApiPathAliases + * @uses \OCA\Thematiq\Middleware\Support\StandardProtocolPaths + */ +class ApiPathAliasesTest extends TestCase { + + /** + * Paths and their successor, null when the path is not deprecated. + * + * @return array + */ + public static function successors(): array { + return [ + 'api path' => ['/api/things/7/parts', '/api/v1/things/7/parts'], + 'request path' => ['/index.php/apps/thematiq/api/things/7/parts', '/index.php/apps/thematiq/api/v1/things/7/parts'], + 'already v1' => ['/api/v1/things/7/parts', null], + 'versioned family' => ['/api/zgw/zaken/v1/zaken', null], + 'protocol' => ['/api/health', null], + 'page' => ['/apps/thematiq/things', null], + ]; + }//end successors() + + /** + * Each path has the expected successor. + * + * @param string $path The path. + * @param string|null $successor The expected successor. + * + * @return void + */ + #[DataProvider('successors')] + public function testTheSuccessorOfAPath(string $path, ?string $successor): void { + $this->assertSame(expected: $successor, actual: ApiPathAliases::successorOf(path: $path)); + $this->assertSame(expected: $successor !== null, actual: ApiPathAliases::isDeprecated(path: $path)); + }//end testTheSuccessorOfAPath() + + /** + * Aliases come right after the routes already declared under `/api/v1/`, and + * the declared routes stay exactly as they were. + * + * @return void + */ + public function testAliasesComeAfterTheDeclaredVersionedRoutes(): void { + $original = [ + 'routes' => [ + ['name' => 'things#versioned', 'url' => '/api/v1/other/x/y', 'verb' => 'GET'], + ['name' => 'things#index', 'url' => '/api/things/{id}/parts', 'verb' => 'GET', 'requirements' => ['id' => '\d+']], + ['name' => 'things#update', 'url' => 'api/things/all/parts', 'verb' => 'PUT', 'postfix' => 'put'], + ['name' => 'other#legacy', 'url' => '/api/other/x/y', 'verb' => 'GET'], + ['name' => 'dashboard#page', 'url' => '/', 'verb' => 'GET'], + ], + ]; + + $declared = ApiPathAliases::withVersionedAliases(routes: $original); + + $this->assertSame( + expected: [ + $original['routes'][0], + ['name' => 'things#index', 'url' => '/api/v1/things/{id}/parts', 'verb' => 'GET', 'requirements' => ['id' => '\d+'], 'postfix' => 'v1'], + ['name' => 'things#update', 'url' => '/api/v1/things/all/parts', 'verb' => 'PUT', 'postfix' => 'putv1'], + ], + actual: array_slice($declared['routes'], 0, 3) + ); + $this->assertSame(expected: array_slice($original['routes'], 1), actual: array_slice($declared['routes'], 3)); + }//end testAliasesComeAfterTheDeclaredVersionedRoutes() + + /** + * The API fallback gets no alias: it already answers the versioned paths no route does. + * + * @return void + */ + public function testTheApiFallbackHasNoAlias(): void { + $fallback = ['name' => 'apiFallback#notFound', 'url' => '/api/{path}', 'verb' => 'GET', 'requirements' => ['path' => '.+']]; + $slug = ['name' => 'things#show', 'url' => '/api/{slug}', 'verb' => 'GET']; + + $this->assertTrue(condition: ApiPathAliases::isApiFallback(route: $fallback)); + $this->assertFalse(condition: ApiPathAliases::isApiFallback(route: $slug)); + $this->assertSame( + expected: ['/api/v1/{slug}', '/api/{path}', '/api/{slug}'], + actual: array_column(ApiPathAliases::withVersionedAliases(routes: ['routes' => [$fallback, $slug]])['routes'], 'url') + ); + }//end testTheApiFallbackHasNoAlias() + + /** + * Every deprecated route of the shipped routes.php has a `/api/v1/` twin with + * the same controller, requirements and defaults, and a request on the twin's + * path reaches it, or an alias that already answered the original path first. + * + * @return void + */ + public function testEveryDeprecatedRouteHasAReachableTwin(): void { + $routes = self::shippedRoutes(); + $names = []; + foreach ($routes as $route) { + $names[] = strtolower($route['name'] . ($route['postfix'] ?? '')); + } + + $twins = 0; + foreach ($routes as $route) { + $url = self::url(route: $route); + if (ApiPathAliases::isDeprecated(path: $url) === false || ApiPathAliases::isApiFallback(route: $route) === true) { + continue; + } + + $path = (string)ApiPathAliases::successorOf(path: $url); + $twin = self::find(routes: $routes, verb: $route['verb'], url: $path, name: $route['name']); + $sample = self::sample(route: $route); + $this->assertNotNull(actual: $twin, message: $route['verb'] . ' ' . $url . ' has no /api/v1/ twin'); + $this->assertSame(expected: ($route['requirements'] ?? null), actual: ($twin['requirements'] ?? null)); + $this->assertSame(expected: ($route['defaults'] ?? null), actual: ($twin['defaults'] ?? null)); + if ($sample !== null) { + $first = self::firstMatch(routes: $routes, verb: $route['verb'], path: (string)ApiPathAliases::successorOf(path: $sample)); + $this->assertTrue( + condition: self::isAlias(route: $first), + message: $route['verb'] . ' ' . $path . ' is answered by ' . ($first['name'] ?? 'no route') . ', not by the twin of ' . $route['name'] + ); + } + + $twins++; + } + + $this->assertGreaterThan(expected: 0, actual: $twins); + $this->assertSame(expected: count($names), actual: count(array_unique($names)), message: 'a route name is registered twice'); + }//end testEveryDeprecatedRouteHasAReachableTwin() + + /** + * No alias answers a request meant for a route the app declares under `/api/v1/`. + * + * @return void + */ + public function testNoAliasTakesARequestMeantForADeclaredVersionedRoute(): void { + $routes = self::shippedRoutes(); + $taken = []; + foreach ($routes as $route) { + $sample = self::sample(route: $route); + if (str_starts_with(self::url(route: $route), '/api/v1/') === false || self::isAlias(route: $route) === true || $sample === null) { + continue; + } + + $first = self::firstMatch(routes: $routes, verb: $route['verb'], path: $sample); + if (self::isAlias(route: $first) === true) { + $taken[] = $route['verb'] . ' ' . $sample . ' is meant for ' . $route['name'] . ' but the alias of ' . $first['name'] . ' answers it'; + } + } + + $this->assertSame(expected: [], actual: $taken); + }//end testNoAliasTakesARequestMeantForADeclaredVersionedRoute() + + /** + * The route registered for a verb and url, preferring the one with the given name. + * + * @param array> $routes The routes. + * @param string $verb The verb. + * @param string $url The url. + * @param string $name The preferred route name. + * + * @return array|null The route, or null when none is registered there. + */ + private static function find(array $routes, string $verb, string $url, string $name): ?array { + $found = null; + foreach ($routes as $route) { + if ($route['verb'] === $verb && self::url(route: $route) === $url) { + if ($route['name'] === $name) { + return $route; + } + + $found = ($found ?? $route); + } + } + + return $found; + }//end find() + + /** + * The first route, in declaration order, that answers a request. + * + * @param array> $routes The routes. + * @param string $verb The verb. + * @param string $path The request path. + * + * @return array The route, or an empty array when none answers. + */ + private static function firstMatch(array $routes, string $verb, string $path): array { + foreach ($routes as $route) { + if ($route['verb'] === $verb && preg_match(self::pattern(route: $route), $path) === 1) { + return $route; + } + } + + return []; + }//end firstMatch() + + /** + * The routes the app declares, with the aliases. + * + * @return array> + */ + private static function shippedRoutes(): array { + $declared = require dirname(__DIR__, 4) . '/appinfo/routes.php'; + + return $declared['routes']; + }//end shippedRoutes() + + /** + * The url of a route with one leading slash. + * + * @param array $route The route. + * + * @return string The url. + */ + private static function url(array $route): string { + return '/' . ltrim((string)$route['url'], '/'); + }//end url() + + /** + * Whether a route is an alias added by ApiPathAliases. + * + * @param array $route The route. + * + * @return bool True for an alias. + */ + private static function isAlias(array $route): bool { + return $route !== [] + && str_ends_with((string)($route['postfix'] ?? ''), 'v1') === true + && str_starts_with(self::url(route: $route), '/api/v1/') === true; + }//end isAlias() + + /** + * The regular expression a route's url compiles to, as Symfony routing matches it. + * + * @param array $route The route. + * + * @return string The pattern. + */ + private static function pattern(array $route): string { + $requirements = ($route['requirements'] ?? []); + $defaults = ($route['defaults'] ?? []); + $pattern = ''; + foreach ((array)preg_split('#(/?\{\w+\})#', self::url(route: $route), -1, PREG_SPLIT_DELIM_CAPTURE) as $part) { + if (preg_match('#^(/?)\{(\w+)\}$#', (string)$part, $match) !== 1) { + $pattern .= preg_quote((string)$part, '#'); + continue; + } + + $pattern .= '(?:' . preg_quote($match[1], '#') . '(?:' . ($requirements[$match[2]] ?? '[^/]+') . '))'; + if (array_key_exists($match[2], $defaults) === true) { + $pattern .= '?'; + } + } + + return '#^' . $pattern . '$#'; + }//end pattern() + + /** + * A request path that the route matches, or null when no sample value fits its requirements. + * + * @param array $route The route. + * + * @return string|null The path. + */ + private static function sample(array $route): ?string { + $path = self::url(route: $route); + foreach (($route['requirements'] ?? []) as $name => $requirement) { + foreach (['sample', '1', 'a-b', 'a.b', 'a/b'] as $value) { + if (preg_match('#^(?:' . $requirement . ')$#', $value) === 1) { + $path = str_replace('{' . $name . '}', $value, $path); + break; + } + } + } + + $path = (string)preg_replace('#\{\w+\}#', 'sample', $path); + + if (preg_match(self::pattern(route: $route), $path) !== 1) { + return null; + } + + return $path; + }//end sample() +}//end class diff --git a/tests/Unit/Middleware/Support/OpenApiDocumentTest.php b/tests/Unit/Middleware/Support/OpenApiDocumentTest.php new file mode 100644 index 000000000..e648abb96 --- /dev/null +++ b/tests/Unit/Middleware/Support/OpenApiDocumentTest.php @@ -0,0 +1,117 @@ + + * @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 OCA\Thematiq\Tests\Unit\Middleware\Support; + +use OCA\Thematiq\Middleware\Support\StandardProtocolPaths; +use PHPUnit\Framework\TestCase; + +/** + * The OpenAPI document describes the `/api/v1/` paths, and exactly the ones + * the app routes: no documented path without a route, no versioned route + * left out. + * + * @covers \OCA\Thematiq\Middleware\Support\StandardProtocolPaths + * @uses \OCA\Thematiq\Middleware\Support\ApiPathAliases + */ +class OpenApiDocumentTest extends TestCase { + + /** + * The document is OpenAPI 3.0 and its server is the versioned API root. + * + * @return void + */ + public function testTheServerIsVersioned(): void { + $document = self::document(); + + $this->assertStringStartsWith(prefix: '3.0.', string: $document['openapi']); + $this->assertStringEndsWith(suffix: '/apps/thematiq/api/v1', string: $document['servers'][0]['url']); + }//end testTheServerIsVersioned() + + /** + * Every documented operation has a versioned route, and every versioned route is documented. + * + * @return void + */ + public function testTheDocumentMatchesTheRoutes(): void { + // Operations marked x-provided-by come from OpenRegister's AppHost route table, which tests may not load. + $documented = []; + $hosted = []; + $protocol = []; + foreach (self::document()['paths'] as $path => $item) { + if (isset($item['servers']) === true) { + // A path that implements an external standard keeps its unversioned URL and names that base. + $this->assertStringEndsWith(suffix: '/apps/thematiq/api', string: $item['servers'][0]['url']); + $this->assertTrue(condition: StandardProtocolPaths::matches(path: '/api' . $path), message: $path . ' is not a standard protocol path'); + $protocol[] = '/api' . self::shape(path: $path); + continue; + } + + foreach ($item as $verb => $operation) { + if (in_array($verb, ['get', 'put', 'post', 'delete', 'patch', 'options', 'head'], true) === false) { + continue; + } + + if (($operation['x-provided-by'] ?? null) === 'openregister') { + $hosted[] = strtoupper($verb) . ' ' . self::shape(path: '/api/v1' . $path); + } else { + $documented[] = strtoupper($verb) . ' ' . self::shape(path: '/api/v1' . $path); + } + } + } + + $routed = []; + $declared = require dirname(__DIR__, 4) . '/appinfo/routes.php'; + $urls = array_map(static fn (array $route): string => self::shape(path: '/' . ltrim((string)$route['url'], '/')), $declared['routes']); + $this->assertSame(expected: [], actual: array_values(array_diff($protocol, $urls)), message: 'documented protocol paths without a route'); + foreach ($declared['routes'] as $route) { + $url = '/' . ltrim((string)$route['url'], '/'); + if (str_starts_with($url, '/api/v1/') === true && StandardProtocolPaths::matches(path: $url) === false) { + $routed[] = strtoupper((string)($route['verb'] ?? 'GET')) . ' ' . self::shape(path: $url); + } + } + + $routed = array_values(array_unique(array_diff($routed, $hosted))); + sort($documented); + sort($routed); + $this->assertSame(expected: [], actual: array_values(array_diff($documented, $routed)), message: 'documented but not routed'); + $this->assertSame(expected: [], actual: array_values(array_diff($routed, $documented)), message: 'routed but not documented'); + }//end testTheDocumentMatchesTheRoutes() + + /** + * The decoded openapi.json. + * + * @return array + */ + private static function document(): array { + $document = json_decode((string)file_get_contents(dirname(__DIR__, 4) . '/openapi.json'), true); + self::assertIsArray(actual: $document); + + return $document; + }//end document() + + /** + * A path with its placeholder names left out, so `/a/{id}` and `/a/{uuid}` compare equal. + * + * @param string $path The path. + * + * @return string The shape of the path. + */ + private static function shape(string $path): string { + return (string)preg_replace('#\{[^}]+\}#', '{}', $path); + }//end shape() +}//end class