diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f00ba71 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +/.github export-ignore +/tests export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/AGENTS.md export-ignore +/CLAUDE.md export-ignore +/codestyle.php export-ignore +/docker-compose.yml export-ignore +/Makefile export-ignore diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 8250c42..f3a76af 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -16,24 +16,24 @@ jobs: strategy: matrix: - php: [ "8.3", "8.4" ] + php: [ "8.5" ] steps: - - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 # https://github.com/actions/checkout + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 # https://github.com/actions/checkout - name: Setup PHP - uses: shivammathur/setup-php@c541c155eee45413f5b09a52248675b1a2575231 # 2.31.1 # https://github.com/shivammathur/setup-php + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 # https://github.com/shivammathur/setup-php with: php-version: ${{ matrix.php }} coverage: none - name: Cache composer dependencies - uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf # v4.2.2 # https://github.com/actions/cache + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 # https://github.com/actions/cache with: path: vendor - key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + key: ${{ runner.os }}-php${{ matrix.php }}-composer-${{ hashFiles('composer.json') }} restore-keys: | - ${{ runner.os }}-composer- + ${{ runner.os }}-php${{ matrix.php }}-composer- - name: Validate composer.json run: composer validate diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..28f8bac --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,31 @@ +# AGENTS.md + +Laravel package `blumilksoftware/openapi-toolbox`: serves OpenAPI documentation UI, builds (merges) specification files, validates them with an Artisan command and validates HTTP requests/responses in tests. + +## Commands + +Run inside the Docker container (`make run`, then `make shell`) or locally with PHP matching `composer.json`: + +- `composer test` - PHPUnit tests (`tests/`, Orchestra Testbench) +- `composer cs` - code style check (php-cs-fixer with `blumilksoftware/codestyle`, config in `codestyle.php`) +- `composer csf` - code style fix + +CI (`.github/workflows/check.yml`) runs `composer validate`, `composer cs` and `composer test`. + +## Structure + +- `src/OpenApiToolboxServiceProvider.php` - registers the `openapi:validate` command, config publishing (tag `openapi-toolbox-config`), routes and views. +- `src/Config/DocumentationConfig.php` - typed accessors over one entry of `openapi_toolbox.documentations`; `Format` enum. +- `src/OpenApiSpecification/SpecificationBuilder.php` - picks one of four builders in `DocumentationBuilders/` (single/multiple files x cached/not cached). Caching lives in the `CacheActions` trait and is invalidated by an md5 checksum of the specification directory. +- `src/OpenApiValidation/` - `openapi:validate` command and validator (checks that files parse and merge). +- `src/OpenApiCompatibility/OpenApiCompatibility.php` - test trait on top of `kirschbaum-development/laravel-openapi-validator`. +- `src/DocumentationUI/` - controller and `UIProvider` enum; views in `resources/views`, routes in `routes/routes.php` (one set per documentation with `ui.enabled`). +- `config/openapi_toolbox.php` - published config; keep it in sync with the config example in `readme.md`. +- `resources/boost/` - guidelines and skill for Laravel Boost, shipped to applications using the package. Update them when public behaviour (config keys, command, trait methods, routes) changes. +- `tests/mocks/` - sample specifications (yml/json, single/multiple files, valid/invalid). + +## Conventions + +- `declare(strict_types=1);` in every PHP file, double quotes for strings, trailing commas in multiline lists. +- Use constructor property promotion and typed enums for config values. +- Public behaviour changes must be reflected in `readme.md` and `resources/boost/`. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/composer.json b/composer.json index 40414ad..181aa8a 100644 --- a/composer.json +++ b/composer.json @@ -10,19 +10,19 @@ "homepage": "https://github.com/blumilksoftware/openapi-toolbox", "license": "MIT", "require": { - "php": "^8.3", - "illuminate/config": "^12.7.2", - "illuminate/console": "^12.7.2", - "illuminate/http": "^12.7.2", - "illuminate/support": "^12.7.2", - "illuminate/testing": "^12.7.2", - "kirschbaum-development/laravel-openapi-validator": "^1.1.0", - "marcelthole/openapi-merge": "^2.4.0" + "php": "^8.5", + "illuminate/config": "^13.0", + "illuminate/console": "^13.0", + "illuminate/http": "^13.0", + "illuminate/support": "^13.0", + "illuminate/testing": "^13.0", + "kirschbaum-development/laravel-openapi-validator": "^2.0.2", + "marcelthole/openapi-merge": "^2.6.0" }, "require-dev": { - "blumilksoftware/codestyle": "^4.1.0", - "orchestra/testbench": "^10.2.0", - "phpunit/phpunit": "^12.1.0" + "blumilksoftware/codestyle": "^5.1.1", + "orchestra/testbench": "^11.3.0", + "phpunit/phpunit": "^13.4.0" }, "autoload": { "psr-4": { diff --git a/config/openapi_toolbox.php b/config/openapi_toolbox.php index f60488a..8b4a212 100644 --- a/config/openapi_toolbox.php +++ b/config/openapi_toolbox.php @@ -36,22 +36,22 @@ "providers" => [ "elements" => [ "script" => [ - "src" => "https://unpkg.com/@stoplight/elements@7.7.16/web-components.min.js", - "sri" => "sha384-bwBnouovwwSJc5fWe7VFNxRg+T2lPHhUcHIzdf7mFfqTZkYtM3T/ehzfEr8F02yY", + "src" => "https://unpkg.com/@stoplight/elements@9.0.29/web-components.min.js", + "sri" => "sha384-enyjBaVmV00WFIo0D7AIVgtZ/4x0idVNWHotG8WUpvQo9HXgMSGAAW2YEOpiJTpP", ], "stylesheet" => [ - "href" => "https://unpkg.com/@stoplight/elements@7.7.16/styles.min.css", - "sri" => "sha384-1lLf7J28IOR7k5RlItk6Y+G3hDgVB3y4RCgWNq6ZSwjYfvJXPtZAdW0uklsAZbGW", + "href" => "https://unpkg.com/@stoplight/elements@9.0.29/styles.min.css", + "sri" => "sha384-iVQBHadsD+eV0M5+ubRCEVXrXEBj+BqcuwjUwPoVJc0Pb1fmrhYSAhL+BFProHdV", ], ], "swagger" => [ "script" => [ - "src" => "https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui-bundle.js", - "sri" => "sha384-xy3YXp34ftsoHshRtcUFjOl/M22B5OEHD5S9AjtVzQokz+BxNff8vNW08msKmH46", + "src" => "https://unpkg.com/swagger-ui-dist@5.34.0/swagger-ui-bundle.js", + "sri" => "sha384-9Td7MKiIr2S83E1kZyyVi8KdJw/S8CpAvu0llLyMeg0xq/hDGiZJfVn0fV4llCmK", ], "stylesheet" => [ - "href" => "https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui.css", - "sri" => "sha384-pzdBB6iZwPIzBHgXle+9cgvKuMgtWNrBopXkjrWnKCi3m4uJsPPdLQ4IPMqRDirS", + "href" => "https://unpkg.com/swagger-ui-dist@5.34.0/swagger-ui.css", + "sri" => "sha384-4c3vsE5f+trhFyHrFrLM1fFGUn531NIaC7dcqEWIJdoRQJ5CkJbSuSCwXLpaS1KF", ], ], ], diff --git a/docker-compose.yml b/docker-compose.yml index b1ba5c6..5c84eba 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,6 @@ services: php: - image: ghcr.io/blumilksoftware/php:8.4 + image: ghcr.io/blumilksoftware/php:8.5 container_name: blumilk-openapi-toolbox-php working_dir: /application user: ${CURRENT_UID:-1000} diff --git a/index.php b/index.php deleted file mode 100644 index 82619c8..0000000 --- a/index.php +++ /dev/null @@ -1,8 +0,0 @@ - .toolbox.cache'); - -$files = shell_exec('md5sum -c .toolbox.cache 2>/dev/null'); -var_dump(count(array_filter(explode("\n", $files), fn(string $line): bool => str_ends_with($line, ": FAILED")))); diff --git a/readme.md b/readme.md index ce2121e..23c7202 100644 --- a/readme.md +++ b/readme.md @@ -12,19 +12,19 @@ Install package via Composer and publish configuration file: ``` composer require blumilksoftware/openapi-toolbox -php artisan vendor:publish +php artisan vendor:publish --tag=openapi-toolbox-config ``` If you need it only for internal development (no documentation serving) you can install it with a development flag: ``` composer require blumilksoftware/openapi-toolbox --dev -php artisan vendor:publish +php artisan vendor:publish --tag=openapi-toolbox-config ``` ### Configuration -Configuration file should be published into your application after running `php artisan vendor:publish` command. It should look like below: +Configuration file should be published into your application as `config/openapi_toolbox.php` after running `php artisan vendor:publish --tag=openapi-toolbox-config` command. It should look like below: ```php return [ @@ -58,22 +58,22 @@ return [ "providers" => [ "elements" => [ "script" => [ - "src" => "https://unpkg.com/@stoplight/elements@7.7.16/web-components.min.js", - "sri" => "sha384-bwBnouovwwSJc5fWe7VFNxRg+T2lPHhUcHIzdf7mFfqTZkYtM3T/ehzfEr8F02yY", + "src" => "https://unpkg.com/@stoplight/elements@9.0.29/web-components.min.js", + "sri" => "sha384-enyjBaVmV00WFIo0D7AIVgtZ/4x0idVNWHotG8WUpvQo9HXgMSGAAW2YEOpiJTpP", ], "stylesheet" => [ - "href" => "https://unpkg.com/@stoplight/elements@7.7.16/styles.min.css", - "sri" => "sha384-1lLf7J28IOR7k5RlItk6Y+G3hDgVB3y4RCgWNq6ZSwjYfvJXPtZAdW0uklsAZbGW", + "href" => "https://unpkg.com/@stoplight/elements@9.0.29/styles.min.css", + "sri" => "sha384-iVQBHadsD+eV0M5+ubRCEVXrXEBj+BqcuwjUwPoVJc0Pb1fmrhYSAhL+BFProHdV", ], ], "swagger" => [ "script" => [ - "src" => "https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui-bundle.js", - "sri" => "sha384-xy3YXp34ftsoHshRtcUFjOl/M22B5OEHD5S9AjtVzQokz+BxNff8vNW08msKmH46", + "src" => "https://unpkg.com/swagger-ui-dist@5.34.0/swagger-ui-bundle.js", + "sri" => "sha384-9Td7MKiIr2S83E1kZyyVi8KdJw/S8CpAvu0llLyMeg0xq/hDGiZJfVn0fV4llCmK", ], "stylesheet" => [ - "href" => "https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui.css", - "sri" => "sha384-pzdBB6iZwPIzBHgXle+9cgvKuMgtWNrBopXkjrWnKCi3m4uJsPPdLQ4IPMqRDirS", + "href" => "https://unpkg.com/swagger-ui-dist@5.34.0/swagger-ui.css", + "sri" => "sha384-4c3vsE5f+trhFyHrFrLM1fFGUn531NIaC7dcqEWIJdoRQJ5CkJbSuSCwXLpaS1KF", ], ], ], @@ -84,11 +84,13 @@ return [ #### Multiple documentations -You can create more than one documentation by adding element to `openapi_toolbox.documentations` array. +You can create more than one documentation by adding element to `openapi_toolbox.documentations` array. Make sure every documentation has its own `ui.routing.prefix`, `ui.routing.name` and `cache.key`. ```php - -return { +"documentations" => [ + "openapi" => [ + // ... + ], "test" => [ "format" => Format::YmlToJson, "specification" => [ @@ -99,7 +101,7 @@ return { "cache" => [ "enabled" => false, "driver" => "default", - "key" => "openapi", + "key" => "openapi.test", ], "ui" => [ "enabled" => false, @@ -113,7 +115,7 @@ return { "provider" => UIProvider::Elements, ], ], -} +], ``` #### OpenAPI documentation UI @@ -133,9 +135,11 @@ Serving a documentation itself can be tricky, especially if specification is bui OpenAPI specification files will be built accordingly to configuration and validated on demand by running an Artisan command: ``` -php artisan openapi:validate {documentation} +php artisan openapi:validate {documentation?} ``` +The `documentation` argument is optional; the `openapi_toolbox.default` documentation is validated when it is omitted. + Good example of usage would be adding this command to CI pipeline for opened pull requests. #### Testing requests and responses against OpenAPI specification @@ -152,3 +156,33 @@ Every time any HTTP call to application would be performed during tests, additio With configuration `cache.enabled = true` internal builders will use cached OpenAPI specifications. You can change the cache store by setting the `cache.driver` option, for example: `cache.driver = redis`. Make sure to use one of the cache drivers available in your Laravel application. + +### AI assistants + +The package ships guidelines and a skill for [Laravel Boost](https://github.com/laravel/boost) in `resources/boost`. If your application uses Boost, run `php artisan boost:install` (or `php artisan boost:update` when Boost is already installed) and select this package. Your AI agent will then know how to edit the specification, validate it and write tests against it without analysing the package source. + +Without Boost, point your agent to these files manually. Both are plain Markdown (despite the `.blade.php` extension of the guidelines file): + +- `resources/boost/guidelines/core.blade.php` - short rules worth keeping always in the agent's context, +- `resources/boost/skills/openapi-toolbox/SKILL.md` - step-by-step recipes loaded on demand. + +For Claude Code, import the guidelines and reference the skill in your application's `CLAUDE.md`: + +```markdown +@vendor/blumilksoftware/openapi-toolbox/resources/boost/guidelines/core.blade.php + +Before working with OpenAPI specification read vendor/blumilksoftware/openapi-toolbox/resources/boost/skills/openapi-toolbox/SKILL.md +``` + +For other agents (Cursor, Codex etc.) add the same reference to `AGENTS.md`: + +```markdown +Before working with OpenAPI specification read vendor/blumilksoftware/openapi-toolbox/resources/boost/guidelines/core.blade.php and vendor/blumilksoftware/openapi-toolbox/resources/boost/skills/openapi-toolbox/SKILL.md +``` + +Both variants stay up to date with `composer update`. Alternatively, copy the skill into your project to make it a native Claude Code skill (remember to copy it again after updating the package): + +``` +mkdir -p .claude/skills/openapi-toolbox +cp vendor/blumilksoftware/openapi-toolbox/resources/boost/skills/openapi-toolbox/SKILL.md .claude/skills/openapi-toolbox/ +``` diff --git a/resources/boost/guidelines/core.blade.php b/resources/boost/guidelines/core.blade.php new file mode 100644 index 0000000..85208c3 --- /dev/null +++ b/resources/boost/guidelines/core.blade.php @@ -0,0 +1,16 @@ +## blumilksoftware/openapi-toolbox + +This application keeps its OpenAPI specification as files and uses `blumilksoftware/openapi-toolbox` to serve, validate and test against it. The specification is the contract: change it first, then the code. + +### Where things are +- Configuration: `config/openapi_toolbox.php`. Documentations are defined under `documentations`, the default one is named by `default` (usually `openapi`). +- Specification files: `specification.path` + `specification.index` of a documentation (by default `resource_path("openapi")` and `openapi.yml`). +- With `specification.allow_multiple_files = true` the index file references sibling files via `$ref` (e.g. `"/ping": { "$ref": ping.yml }`). Only files placed directly in `specification.path` (no subdirectories) with the extension matching `format` are merged (`.yml` for `Format::Yml` and `Format::YmlToJson`, `.yaml` for `Format::Yaml`, `.json` for `Format::Json`). + +### Rules +- After every change in specification files run `php artisan openapi:validate` (or `php artisan openapi:validate ` for a non-default one). It checks that the files parse and merge; it does not replace request/response validation in tests. +- Feature tests that hit HTTP endpoints should use the `Blumilk\OpenApiToolbox\OpenApiCompatibility\OpenApiCompatibility` trait. Every request and response made in such a test is validated against the specification, so an undocumented endpoint, field or status code fails the test. +- When a test intentionally sends an invalid request or expects an undocumented response, call `$this->withoutRequestValidation()` and/or `$this->withoutResponseValidation()` before the request. Do not disable validation just to make a test pass; fix the specification or the code instead. +- To test against a documentation other than the default one, override `getDocumentationName(): string` in the test case. +- When `ui.enabled = true`, the UI is served at `GET /{ui.routing.prefix}` and the built specification at `GET /{ui.routing.prefix}/raw` (route names `{ui.routing.name}` and `{ui.routing.name}.raw`). +- When `cache.enabled = true`, the built specification is cached and invalidated automatically by a checksum of files in `specification.path`; no manual cache clearing is needed after editing the specification. diff --git a/resources/boost/skills/openapi-toolbox/SKILL.md b/resources/boost/skills/openapi-toolbox/SKILL.md new file mode 100644 index 0000000..f722302 --- /dev/null +++ b/resources/boost/skills/openapi-toolbox/SKILL.md @@ -0,0 +1,108 @@ +--- +name: openapi-toolbox +description: Work with OpenAPI specification in a Laravel application using blumilksoftware/openapi-toolbox. Use when adding or changing API endpoints, editing OpenAPI files, writing feature tests validated against the specification, adding another documentation, or enabling the documentation UI or cache. +--- + +# OpenAPI Toolbox + +`blumilksoftware/openapi-toolbox` serves, validates and tests a Laravel application against its OpenAPI specification files. Configuration lives in `config/openapi_toolbox.php`. + +## Before you start + +1. Read `config/openapi_toolbox.php` and note for the documentation you work on: `format`, `specification.path`, `specification.index`, `specification.allow_multiple_files`. +2. If the config file does not exist, publish it: + ``` + php artisan vendor:publish --tag=openapi-toolbox-config + ``` +3. Open the index file (`specification.path`/`specification.index`) to learn the existing structure, naming of schemas and tags before adding anything. + +## Configuration reference + +| Key | Meaning | +| --- | --- | +| `format` | `Format::Yml`, `Format::Yaml`, `Format::Json` or `Format::YmlToJson` (YAML files served as JSON). Enum `Blumilk\OpenApiToolbox\Config\Format`. | +| `specification.path` | Directory with specification files. | +| `specification.index` | Entry file name inside `path`. | +| `specification.allow_multiple_files` | Merge the index with sibling files referenced by `$ref`. | +| `cache.enabled` / `cache.driver` / `cache.key` | Cache the built specification; `driver` is a Laravel cache store name or `default`. | +| `ui.enabled` | Register UI routes. | +| `ui.single_source` | `true`: UI loads the built specification from `/raw`; `false`: UI loads the index file and resolves `$ref` itself. | +| `ui.provider` | `UIProvider::Elements` or `UIProvider::Swagger` (enum `Blumilk\OpenApiToolbox\DocumentationUI\UIProvider`). | +| `ui.routing.prefix` / `name` / `middlewares` | URL prefix, route name and middlewares of UI routes. | + +## Recipe: add or change an API endpoint + +1. **Specification first.** Describe the path, parameters, request body, every response status code and response schema in the specification. + - Single file: add the path under `paths` in the index file. + - Multiple files (`allow_multiple_files = true`): create a new file directly in `specification.path` (no subdirectories, extension matching `format`) holding the path item, and reference it from the index: + ```yaml + paths: + "/ping": + "$ref": ping.yml + ``` +2. **Validate the files:** + ``` + php artisan openapi:validate + ``` + Pass the documentation name as an argument when it is not the default one. A failure means the files cannot be parsed or merged; fix it before continuing. +3. **Write a feature test** using the compatibility trait: + ```php + use Blumilk\OpenApiToolbox\OpenApiCompatibility\OpenApiCompatibility; + + class PingTest extends TestCase + { + use OpenApiCompatibility; + + public function testPing(): void + { + $this->getJson("/api/ping")->assertOk(); + } + } + ``` + Every request and response in this test is validated against the specification. +4. **Implement** the route, controller, request and resource until the test passes. +5. If validation fails, decide which side is wrong. The specification is the contract: change it only when the intended API really differs. + +## Recipe: test invalid input or undocumented responses + +The trait validates requests too, so a deliberately invalid payload fails before reaching the application. Disable validation only for that test: + +```php +public function testValidationError(): void +{ + $this->withoutRequestValidation(); + + $this->postJson("/api/login", [])->assertUnprocessable(); +} +``` + +Use `$this->withoutResponseValidation()` when the response is intentionally not described in the specification. Prefer documenting error responses (e.g. `422`) over disabling response validation. + +## Recipe: test against a non-default documentation + +```php +public function getDocumentationName(): string +{ + return "admin"; +} +``` + +Override `getDocumentationConfig(): DocumentationConfig` instead when the test needs a configuration that is not in `config/openapi_toolbox.php`. + +## Recipe: add another documentation + +1. Copy the `openapi` entry under `documentations` in `config/openapi_toolbox.php` and give it a new key, e.g. `admin`. +2. Change `specification.path` to a separate directory (e.g. `resource_path("openapi/admin")`) and create the index file there. +3. Give it unique `ui.routing.prefix` and `ui.routing.name` (e.g. `documentation/admin` and `documentation.admin`) and a unique `cache.key`, otherwise routes and cache entries collide. +4. Run `php artisan openapi:validate admin`. + +## Recipe: expose the documentation UI + +1. Set `ui.enabled = true` and choose `ui.provider`. +2. Protect it if needed with `ui.routing.middlewares` (e.g. `["auth"]`). +3. Check `php artisan route:list --name=documentation`; you should see the UI route, `.raw` and `.file`. +4. With multiple files, set `ui.single_source = true` so the UI receives one merged specification. + +## Recipe: run validation in CI + +Add `php artisan openapi:validate` (one call per documentation) to the pull request pipeline next to the test suite. diff --git a/routes/routes.php b/routes/routes.php index 3c1947c..7cded89 100644 --- a/routes/routes.php +++ b/routes/routes.php @@ -12,32 +12,53 @@ /** @var Repository $config */ $config = app()->make(Repository::class); -$documentations = $config->get("openapi_toolbox.documentations", []); - -foreach ($documentations as $key => $documentation) { - $documentationConfig = new DocumentationConfig($documentation); - - if (!$documentationConfig->isUiEnabled()) { - continue; - } +$documentationsWithUi = array_filter( + array_map( + static fn(array $documentation): DocumentationConfig => new DocumentationConfig($documentation), + $config->get("openapi_toolbox.documentations", []), + ), + static fn(DocumentationConfig $documentationConfig): bool => $documentationConfig->isUiEnabled(), +); +$registerFixedPathRoutes = static function (string $key, DocumentationConfig $documentationConfig) use ($router): void { $prefix = $documentationConfig->getRoutePrefix(); $name = $documentationConfig->getRouteName(); - $middlewares = $documentationConfig->getRouteMddlewares(); + $middlewares = $documentationConfig->getRouteMiddlewares(); $router->get("/$prefix/raw", [DocumentationUIController::class, "raw"]) ->middleware($middlewares) ->name("$name.raw") ->defaults("documentation", $key); + $router->get("/$prefix", [DocumentationUIController::class, "index"]) + ->middleware($middlewares) + ->name("$name") + ->defaults("documentation", $key); +}; + +$registerCatchAllFileRoute = static function (string $key, DocumentationConfig $documentationConfig) use ($router): void { + $prefix = $documentationConfig->getRoutePrefix(); + $name = $documentationConfig->getRouteName(); + $middlewares = $documentationConfig->getRouteMiddlewares(); + $router->get("/$prefix/{filePath}", [DocumentationUIController::class, "file"]) ->middleware($middlewares) ->where("filePath", ".*") ->name("$name.file") ->defaults("documentation", $key); +}; - $router->get("/$prefix", [DocumentationUIController::class, "index"]) - ->middleware($middlewares) - ->name("$name") - ->defaults("documentation", $key); +$documentationsWithMostNestedPrefixFirst = $documentationsWithUi; + +uasort( + $documentationsWithMostNestedPrefixFirst, + static fn(DocumentationConfig $a, DocumentationConfig $b): int => strlen($b->getRoutePrefix()) <=> strlen($a->getRoutePrefix()), +); + +foreach ($documentationsWithUi as $key => $documentationConfig) { + $registerFixedPathRoutes($key, $documentationConfig); +} + +foreach ($documentationsWithMostNestedPrefixFirst as $key => $documentationConfig) { + $registerCatchAllFileRoute($key, $documentationConfig); } diff --git a/src/Config/DocumentationConfig.php b/src/Config/DocumentationConfig.php index b8e412c..f43b19f 100644 --- a/src/Config/DocumentationConfig.php +++ b/src/Config/DocumentationConfig.php @@ -60,7 +60,7 @@ public function getRouteName(): string return Arr::get($this->config, "ui.routing.name"); } - public function getRouteMddlewares(): array + public function getRouteMiddlewares(): array { return Arr::get($this->config, "ui.routing.middlewares", []); } diff --git a/src/DocumentationUI/Http/DocumentationUIController.php b/src/DocumentationUI/Http/DocumentationUIController.php index 6fb75e9..d2dbc24 100644 --- a/src/DocumentationUI/Http/DocumentationUIController.php +++ b/src/DocumentationUI/Http/DocumentationUIController.php @@ -16,6 +16,7 @@ use Illuminate\Http\JsonResponse; use Mthole\OpenApiMerge\Writer\Exception\InvalidFileTypeException; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Yaml\Yaml; class DocumentationUIController @@ -87,7 +88,13 @@ public function file(string $filePath, string $documentation, Repository $config $documentationConfig = new DocumentationConfig($data); - $filePath = $documentationConfig->getPath($filePath); + $basePath = realpath($documentationConfig->getPath()); + $filePath = realpath($documentationConfig->getPath($filePath)); + + if ($basePath === false || $filePath === false || !str_starts_with($filePath, $basePath . DIRECTORY_SEPARATOR) || !is_file($filePath)) { + throw new NotFoundHttpException(); + } + $content = file_get_contents($filePath); return $this->respondWithSpecification($content, $documentationConfig->getFormat()); diff --git a/src/OpenApiToolboxServiceProvider.php b/src/OpenApiToolboxServiceProvider.php index 2a3b457..3fa50c0 100644 --- a/src/OpenApiToolboxServiceProvider.php +++ b/src/OpenApiToolboxServiceProvider.php @@ -19,7 +19,7 @@ public function boot(): void $this->publishes([ __DIR__ . "/../config/openapi_toolbox.php" => config_path("openapi_toolbox.php"), - ]); + ], "openapi-toolbox-config"); $this->loadRoutesFrom(__DIR__ . "/../routes/routes.php"); $this->loadViewsFrom(__DIR__ . "/../resources/views", "openapi_toolbox"); diff --git a/src/OpenApiValidation/DocumentationFilesValidator.php b/src/OpenApiValidation/DocumentationFilesValidator.php index 1834f67..495c194 100644 --- a/src/OpenApiValidation/DocumentationFilesValidator.php +++ b/src/OpenApiValidation/DocumentationFilesValidator.php @@ -5,8 +5,8 @@ namespace Blumilk\OpenApiToolbox\OpenApiValidation; use Blumilk\OpenApiToolbox\OpenApiSpecification\SpecificationBuilder; -use cebe\openapi\exceptions\UnresolvableReferenceException; use Mthole\OpenApiMerge\Writer\Exception\InvalidFileTypeException; +use openapiphp\openapi\exceptions\UnresolvableReferenceException; use Symfony\Component\Yaml\Exception\ParseException; use TypeError; diff --git a/tests/CachedDocumentationBuilderTest.php b/tests/CachedDocumentationBuilderTest.php new file mode 100644 index 0000000..6831fc9 --- /dev/null +++ b/tests/CachedDocumentationBuilderTest.php @@ -0,0 +1,105 @@ +config(multipleFiles: false)))->build(); + + $this->assertStringContainsString("API Documentation", $result); + $this->assertSame($result, Cache::get("openapi")); + $this->assertNotEmpty(Cache::get("openapi.md5")); + } + + /** + * @throws InvalidFileTypeException + */ + public function testMultipleFilesDocumentationIsCached(): void + { + $result = (new SpecificationBuilder($this->config(multipleFiles: true)))->build(); + + $this->assertStringContainsString("Ping endpoint", $result); + $this->assertSame($result, Cache::get("openapi")); + $this->assertNotEmpty(Cache::get("openapi.md5")); + } + + /** + * @throws InvalidFileTypeException + */ + public function testCachedDocumentationIsReturnedWhenChecksumIsValid(): void + { + $builder = new SpecificationBuilder($this->config(multipleFiles: true)); + $builder->build(); + + Cache::put("openapi", "cached documentation"); + + $this->assertSame("cached documentation", $builder->build()); + } + + /** + * @throws InvalidFileTypeException + */ + public function testDocumentationIsRebuiltWhenChecksumIsInvalid(): void + { + $builder = new SpecificationBuilder($this->config(multipleFiles: true)); + $builder->build(); + + Cache::put("openapi", "stale documentation"); + Cache::put("openapi.md5", "outdated checksum"); + + $result = $builder->build(); + + $this->assertStringContainsString("Ping endpoint", $result); + $this->assertSame($result, Cache::get("openapi")); + } + + /** + * @throws InvalidFileTypeException + */ + public function testConfiguredCacheDriverIsUsed(): void + { + $result = (new SpecificationBuilder($this->config(multipleFiles: false, driver: "secondary")))->build(); + + $this->assertSame($result, Cache::driver("secondary")->get("openapi")); + $this->assertFalse(Cache::driver()->has("openapi")); + } + + protected function defineEnvironment($app): void + { + $app["config"]->set("cache.default", "array"); + $app["config"]->set("cache.stores.secondary", [ + "driver" => "array", + ]); + } + + protected function config(bool $multipleFiles, string $driver = "default"): DocumentationConfig + { + return new DocumentationConfig([ + "format" => Format::Yml, + "specification" => [ + "path" => realpath(__DIR__ . "/mocks/yml/multipleFilesDocumentation"), + "index" => "openapi.yml", + "allow_multiple_files" => $multipleFiles, + ], + "cache" => [ + "enabled" => true, + "driver" => $driver, + "key" => "openapi", + ], + ]); + } +} diff --git a/tests/ConfigPublishingTest.php b/tests/ConfigPublishingTest.php new file mode 100644 index 0000000..f742a69 --- /dev/null +++ b/tests/ConfigPublishingTest.php @@ -0,0 +1,35 @@ +assertCount(1, $paths); + $this->assertFileExists(array_key_first($paths)); + $this->assertSame(config_path("openapi_toolbox.php"), reset($paths)); + } + + public function testConfigIsPublishedWithProvider(): void + { + $paths = ServiceProvider::pathsToPublish(OpenApiToolboxServiceProvider::class); + + $this->assertContains(config_path("openapi_toolbox.php"), $paths); + } + + protected function getPackageProviders($app): array + { + return [ + OpenApiToolboxServiceProvider::class, + ]; + } +} diff --git a/tests/DocumentationUITest.php b/tests/DocumentationUITest.php new file mode 100644 index 0000000..76ca129 --- /dev/null +++ b/tests/DocumentationUITest.php @@ -0,0 +1,214 @@ +app->make(Router::class); + $routes = $router->getRoutes(); + + $this->assertTrue($routes->hasNamedRoute("documentation")); + $this->assertTrue($routes->hasNamedRoute("documentation.raw")); + $this->assertTrue($routes->hasNamedRoute("documentation.file")); + $this->assertTrue($routes->hasNamedRoute("documentation.swagger")); + $this->assertFalse($routes->hasNamedRoute("documentation.disabled")); + } + + public function testCatchAllFileRouteDoesNotShadowRoutesOfDocumentationWithNestedPrefix(): void + { + $this->assertSame("documentation.swagger", Route::getRoutes()->match(Request::create("documentation/swagger"))->getName()); + $this->assertSame("documentation.swagger.raw", Route::getRoutes()->match(Request::create("documentation/swagger/raw"))->getName()); + $this->assertSame("documentation.swagger.file", Route::getRoutes()->match(Request::create("documentation/swagger/ping.yml"))->getName()); + $this->assertSame("documentation.file", Route::getRoutes()->match(Request::create("documentation/openapi.yml"))->getName()); + } + + public function testElementsUiIsServedWithSingleSource(): void + { + /** @var Repository $config */ + $config = $this->app->make(Repository::class); + + $this->get("documentation") + ->assertOk() + ->assertSee("Elements documentation", escape: false) + ->assertSee("assertSee('apiDescriptionUrl="' . route("documentation.raw") . '"', escape: false) + ->assertSee($config->get("openapi_toolbox.providers.elements.script.src")) + ->assertSee($config->get("openapi_toolbox.providers.elements.script.sri")) + ->assertSee($config->get("openapi_toolbox.providers.elements.stylesheet.href")) + ->assertSee($config->get("openapi_toolbox.providers.elements.stylesheet.sri")); + } + + public function testSwaggerUiIsServedWithIndexFile(): void + { + /** @var Repository $config */ + $config = $this->app->make(Repository::class); + + $this->get("documentation/swagger") + ->assertOk() + ->assertSee("Swagger documentation", escape: false) + ->assertSee("SwaggerUIBundle") + ->assertSee('url: "' . route("documentation.swagger.file", "openapi.yml") . '"', escape: false) + ->assertSee($config->get("openapi_toolbox.providers.swagger.script.src")) + ->assertSee($config->get("openapi_toolbox.providers.swagger.script.sri")) + ->assertSee($config->get("openapi_toolbox.providers.swagger.stylesheet.href")) + ->assertSee($config->get("openapi_toolbox.providers.swagger.stylesheet.sri")); + } + + public function testRawSpecificationIsConvertedFromYmlToJson(): void + { + $this->get("documentation/raw") + ->assertOk() + ->assertHeader("Content-Type", "application/json") + ->assertJsonPath("info.title", "application") + ->assertJsonPath("info.description", "API Documentation"); + } + + public function testRawSpecificationIsBuiltFromMultipleFiles(): void + { + $response = $this->get("documentation/swagger/raw") + ->assertOk() + ->assertHeader("Content-Type", "application/x-yaml"); + + $this->assertStringContainsString("API Documentation", $response->getContent()); + $this->assertStringContainsString("Ping endpoint", $response->getContent()); + } + + public function testSpecificationFileIsServed(): void + { + $response = $this->get("documentation/swagger/ping.yml") + ->assertOk() + ->assertHeader("Content-Type", "application/x-yaml"); + + $this->assertStringContainsString("Ping endpoint", $response->getContent()); + $this->assertStringNotContainsString("API Documentation", $response->getContent()); + } + + public function testRouteMiddlewaresAreApplied(): void + { + $this->get("documentation/protected")->assertForbidden(); + $this->get("documentation/protected/raw")->assertForbidden(); + $this->get("documentation/protected/openapi.yml")->assertForbidden(); + } + + public function testFilesOutsideSpecificationPathAreNotServed(): void + { + $this->get("documentation/../../../../composer.json")->assertNotFound(); + $this->get("documentation/..%2F..%2F..%2F..%2Fcomposer.json")->assertNotFound(); + } + + public function testMissingSpecificationFileIsNotFound(): void + { + $this->get("documentation/missing.yml")->assertNotFound(); + } + + public function testDisabledUiIsNotServed(): void + { + $this->get("documentation/disabled")->assertNotFound(); + } + + protected function getPackageProviders($app): array + { + return [ + OpenApiToolboxServiceProvider::class, + ]; + } + + protected function defineEnvironment($app): void + { + $app["config"]->set("openapi_toolbox", require __DIR__ . "/../config/openapi_toolbox.php"); + $app["config"]->set("openapi_toolbox.documentations", [ + "openapi" => $this->documentation( + format: Format::YmlToJson, + path: __DIR__ . "/mocks/yml/singleFileDocumentation", + title: "Elements documentation", + prefix: "documentation", + name: "documentation", + provider: UIProvider::Elements, + singleSource: true, + ), + "swagger" => $this->documentation( + format: Format::Yml, + path: __DIR__ . "/mocks/yml/multipleFilesDocumentation", + title: "Swagger documentation", + prefix: "documentation/swagger", + name: "documentation.swagger", + provider: UIProvider::Swagger, + singleSource: false, + multipleFiles: true, + ), + "protected" => $this->documentation( + format: Format::Yml, + path: __DIR__ . "/mocks/yml/singleFileDocumentation", + title: "Protected documentation", + prefix: "documentation/protected", + name: "documentation.protected", + provider: UIProvider::Elements, + singleSource: true, + middlewares: [DenyAccess::class], + ), + "disabled" => $this->documentation( + format: Format::Yml, + path: __DIR__ . "/mocks/yml/singleFileDocumentation", + title: "Disabled documentation", + prefix: "documentation/disabled", + name: "documentation.disabled", + provider: UIProvider::Elements, + singleSource: true, + enabled: false, + ), + ]); + } + + protected function documentation( + Format $format, + string $path, + string $title, + string $prefix, + string $name, + UIProvider $provider, + bool $singleSource, + bool $multipleFiles = false, + array $middlewares = [], + bool $enabled = true, + ): array { + return [ + "format" => $format, + "specification" => [ + "path" => realpath($path), + "index" => "openapi.yml", + "allow_multiple_files" => $multipleFiles, + ], + "cache" => [ + "enabled" => false, + "driver" => "default", + "key" => $name, + ], + "ui" => [ + "enabled" => $enabled, + "single_source" => $singleSource, + "title" => $title, + "routing" => [ + "prefix" => $prefix, + "name" => $name, + "middlewares" => $middlewares, + ], + "provider" => $provider, + ], + ]; + } +} diff --git a/tests/OpenApiValidationTest.php b/tests/OpenApiValidationTest.php index 1b2c946..4208916 100644 --- a/tests/OpenApiValidationTest.php +++ b/tests/OpenApiValidationTest.php @@ -7,6 +7,7 @@ use Blumilk\OpenApiToolbox\Config\DocumentationConfig; use Blumilk\OpenApiToolbox\Config\Format; use Blumilk\OpenApiToolbox\OpenApiSpecification\SpecificationBuilder; +use Blumilk\OpenApiToolbox\OpenApiValidation\DocumentationFilesInvalidException; use Blumilk\OpenApiToolbox\OpenApiValidation\DocumentationFilesValidator; use PHPUnit\Framework\Assert; use PHPUnit\Framework\TestCase; @@ -62,6 +63,7 @@ public function testMultipleInvalidFilesYamlDocumentationValidation(): void } Assert::assertCount(1, $exceptions); + Assert::assertInstanceOf(DocumentationFilesInvalidException::class, $exceptions[0]); } public function testMultipleFilesJsonDocumentationValidation(): void @@ -115,5 +117,6 @@ public function testMultipleInvalidFilesJsonDocumentationValidation(): void } Assert::assertCount(1, $exceptions); + Assert::assertInstanceOf(DocumentationFilesInvalidException::class, $exceptions[0]); } } diff --git a/tests/Stubs/DenyAccess.php b/tests/Stubs/DenyAccess.php new file mode 100644 index 0000000..192e4b2 --- /dev/null +++ b/tests/Stubs/DenyAccess.php @@ -0,0 +1,17 @@ +artisan("openapi:validate") + ->expectsOutput("OpenAPI specification named openapi is formatted properly.") + ->assertSuccessful(); + } + + public function testNamedDocumentationIsValidated(): void + { + $this->artisan("openapi:validate", ["documentation" => "multiple"]) + ->expectsOutput("OpenAPI specification named multiple is formatted properly.") + ->assertSuccessful(); + } + + public function testInvalidDocumentationFails(): void + { + $this->artisan("openapi:validate", ["documentation" => "invalid"]) + ->assertFailed(); + } + + public function testUnknownDocumentationThrowsException(): void + { + $this->expectException(DocumentationNotFound::class); + $this->expectExceptionMessageIs("Documentation named unknown not found."); + + $this->artisan("openapi:validate", ["documentation" => "unknown"])->run(); + } + + protected function getPackageProviders($app): array + { + return [ + OpenApiToolboxServiceProvider::class, + ]; + } + + protected function defineEnvironment($app): void + { + $app["config"]->set("openapi_toolbox.default", "openapi"); + $app["config"]->set("openapi_toolbox.documentations", [ + "openapi" => $this->documentation(__DIR__ . "/mocks/yml/singleFileDocumentation", multipleFiles: false), + "multiple" => $this->documentation(__DIR__ . "/mocks/yml/multipleFilesDocumentation", multipleFiles: true), + "invalid" => $this->documentation(__DIR__ . "/mocks/yml/multipleInvalidFilesDocumentation", multipleFiles: true), + ]); + } + + protected function documentation(string $path, bool $multipleFiles): array + { + return [ + "format" => Format::Yml, + "specification" => [ + "path" => realpath($path), + "index" => "openapi.yml", + "allow_multiple_files" => $multipleFiles, + ], + ]; + } +}