openapi_first 4.3.0 → 4.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.yardopts +7 -0
- data/CHANGELOG.md +12 -0
- data/README.md +92 -10
- data/lib/openapi_first/builder.rb +25 -24
- data/lib/openapi_first/child_configuration.rb +7 -2
- data/lib/openapi_first/configuration.rb +80 -2
- data/lib/openapi_first/definition.rb +13 -3
- data/lib/openapi_first/error_response.rb +18 -3
- data/lib/openapi_first/failure.rb +27 -7
- data/lib/openapi_first/file_loader.rb +1 -1
- data/lib/openapi_first/json.rb +1 -1
- data/lib/openapi_first/middlewares/request_validation.rb +9 -8
- data/lib/openapi_first/middlewares/response_validation.rb +2 -0
- data/lib/openapi_first/parameter/converter/array_converter.rb +1 -1
- data/lib/openapi_first/parameter/converter/object_converter.rb +1 -1
- data/lib/openapi_first/parameter/converter.rb +1 -1
- data/lib/openapi_first/parameter/unpackers.rb +1 -1
- data/lib/openapi_first/parameter.rb +3 -0
- data/lib/openapi_first/parameters_parser.rb +1 -1
- data/lib/openapi_first/parsed_request.rb +1 -0
- data/lib/openapi_first/path_template.rb +1 -1
- data/lib/openapi_first/plugins/x_public.rb +3 -0
- data/lib/openapi_first/query_string_parser.rb +1 -1
- data/lib/openapi_first/ref_resolver.rb +16 -11
- data/lib/openapi_first/registry.rb +2 -4
- data/lib/openapi_first/request_body_parsers.rb +1 -1
- data/lib/openapi_first/{request.rb → request_definition.rb} +27 -1
- data/lib/openapi_first/request_headers.rb +1 -1
- data/lib/openapi_first/request_validator.rb +1 -0
- data/lib/openapi_first/response_body_parsers.rb +1 -1
- data/lib/openapi_first/{response.rb → response_definition.rb} +19 -4
- data/lib/openapi_first/response_parser.rb +3 -1
- data/lib/openapi_first/response_validator.rb +1 -0
- data/lib/openapi_first/router/find_content.rb +1 -1
- data/lib/openapi_first/router/find_response.rb +1 -1
- data/lib/openapi_first/router/path_trie.rb +11 -2
- data/lib/openapi_first/router/segment_pattern.rb +1 -1
- data/lib/openapi_first/router.rb +1 -0
- data/lib/openapi_first/schema/hash.rb +15 -1
- data/lib/openapi_first/schema/validation_result.rb +1 -0
- data/lib/openapi_first/sinatra.rb +2 -2
- data/lib/openapi_first/test/app.rb +3 -0
- data/lib/openapi_first/test/callable.rb +1 -0
- data/lib/openapi_first/test/configuration.rb +6 -4
- data/lib/openapi_first/test/coverage/covered_request.rb +1 -0
- data/lib/openapi_first/test/coverage/covered_response.rb +1 -0
- data/lib/openapi_first/test/coverage/html_reporter/context.rb +1 -0
- data/lib/openapi_first/test/coverage/html_reporter.rb +2 -0
- data/lib/openapi_first/test/coverage/plan.rb +1 -0
- data/lib/openapi_first/test/coverage/request_task.rb +1 -1
- data/lib/openapi_first/test/coverage/response_task.rb +1 -1
- data/lib/openapi_first/test/coverage/route_task.rb +1 -0
- data/lib/openapi_first/test/coverage/skipped_summary.rb +1 -0
- data/lib/openapi_first/test/coverage/terminal_reporter.rb +2 -0
- data/lib/openapi_first/test/coverage/tracker.rb +1 -0
- data/lib/openapi_first/test/coverage.rb +11 -4
- data/lib/openapi_first/test/methods.rb +14 -1
- data/lib/openapi_first/test/minitest_helpers.rb +5 -2
- data/lib/openapi_first/test/observe.rb +2 -1
- data/lib/openapi_first/test/observer_middleware.rb +1 -0
- data/lib/openapi_first/test/plain_helpers.rb +7 -4
- data/lib/openapi_first/test.rb +30 -3
- data/lib/openapi_first/utils.rb +1 -1
- data/lib/openapi_first/validated_request.rb +4 -4
- data/lib/openapi_first/validated_response.rb +5 -3
- data/lib/openapi_first/validators/multipart_request_body.rb +1 -0
- data/lib/openapi_first/validators/request_body.rb +1 -0
- data/lib/openapi_first/validators/request_parameters.rb +1 -1
- data/lib/openapi_first/validators/response_body.rb +1 -0
- data/lib/openapi_first/validators/response_headers.rb +1 -0
- data/lib/openapi_first/version.rb +1 -1
- data/lib/openapi_first.rb +16 -6
- metadata +4 -3
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 33b54b526cc7579d4c7bed16fef0c283d3752fa3ccb5e7371e5a39b87b1189ba
|
|
4
|
+
data.tar.gz: 369cb181d69488cef0edbcccf1f2a1a0d92430a1e00bd2d96bdd28b665300742
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 798b8ceb7787be4ed6a530a9869b08976c2b8442da35f3dbc9f1f241cc3dfec105bf1474aaf095f2b8e4d561fbe49598bef54d19a7da64b792c31fc677708121
|
|
7
|
+
data.tar.gz: be67bcb40e82bbdeb1574868ead6b3ba3442ca7fe91961582ee7711a7ab7701454fae8f858e23d1c32e03cc208d7fdca1ae4f730798b24527f7f2326761c85cb
|
data/.yardopts
ADDED
data/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 4.5.0
|
|
6
|
+
|
|
7
|
+
- Changed: Renamed internal `OpenapiFirst::Request` to `OpenapiFirst::RequestDefinition` and `OpenapiFirst::Response` to `OpenapiFirst::ResponseDefinition`. These are the objects returned by `ValidatedRequest#request_definition` and `ValidatedResponse#response_definition`. The old constants still work, but are deprecated and will be removed in the next major version.
|
|
8
|
+
- Internal classes and methods are now marked with YARD `@api private`, and the API docs on rubydoc.info show only the public API.
|
|
9
|
+
- Fix: A parameter whose schema is a `$ref` gets the `default` of the referenced schema again, including through chains of `$ref`s and `$ref`s to other files. This was lost in 4.0.0. A `default` next to the `$ref` takes precedence in OpenAPI 3.1. OpenAPI 3.0 ignores keywords next to a `$ref`, so there a `default` next to the `$ref` is no longer applied.
|
|
10
|
+
|
|
11
|
+
## 4.4.0
|
|
12
|
+
|
|
13
|
+
- Changed: Percent-encoded path parameters are now decoded. For example `/files/my%20file` yields `my file` for `/files/{name}`. A `+` stays a `+`. Values with a malformed encoding or that do not decode to valid UTF-8 are kept as they are. If your application decodes path parameters itself, remove that, or values get decoded twice. Known limitation: An encoded delimiter inside an array or object path parameter is decoded before the value is split, so `/files/a%2Cb,c` yields `["a", "b", "c"]`.
|
|
14
|
+
- Added: You can pass a block to `OpenapiFirst::Middlewares::RequestValidation` to configure hooks and other options specifically for that middleware. With a registered name or a Definition it creates a copy of that OAD, so the registered OAD stays unchanged.
|
|
15
|
+
- Fix: `OpenapiFirst.load` now accepts and applies a configuration block.
|
|
16
|
+
|
|
5
17
|
## 4.3.0
|
|
6
18
|
|
|
7
19
|
- Fix: Passing a block to `config.register` not works when called inside `OpenapiFirst.configure` block. Before the block was ignored.
|
data/README.md
CHANGED
|
@@ -78,12 +78,45 @@ end
|
|
|
78
78
|
|
|
79
79
|
### Request validation
|
|
80
80
|
|
|
81
|
-
The request validation middleware returns a 4xx if the request is invalid or not defined in the API description. It adds
|
|
81
|
+
The request validation middleware returns a 4xx if the request is invalid or not defined in the API description. It adds an `OpenapiFirst::ValidatedRequest` to the current Rack environment at `env[OpenapiFirst::REQUEST]` (`'openapi.request'`) with the request parameters parsed exactly as described in your API description plus access to meta information from your API description. See _[Manual use](#manual-use)_ for more details about that object.
|
|
82
82
|
|
|
83
83
|
```ruby
|
|
84
84
|
use OpenapiFirst::Middlewares::RequestValidation
|
|
85
85
|
```
|
|
86
86
|
|
|
87
|
+
Read the validated request in your application:
|
|
88
|
+
|
|
89
|
+
```ruby
|
|
90
|
+
validated_request = env[OpenapiFirst::REQUEST]
|
|
91
|
+
validated_request.parsed_params # => { "petId" => 42, "limit" => 10 }
|
|
92
|
+
validated_request.operation_id # => "showPetById"
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Your application can reject a valid request by calling `OpenapiFirst::Failure.fail!`. The middleware discards the application's response, sets the failure as the `error` of `env[OpenapiFirst::REQUEST]` and renders the matching [error response](#error-responses).
|
|
96
|
+
|
|
97
|
+
```ruby
|
|
98
|
+
get '/pets/:id' do
|
|
99
|
+
OpenapiFirst::Failure.fail!(:not_found, message: 'Pet not found') unless Pet.exists?(params[:id])
|
|
100
|
+
# …
|
|
101
|
+
end
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
The first argument is the failure type, which determines the error class and the response status:
|
|
105
|
+
`:not_found`, `:method_not_allowed`, `:unsupported_media_type`, `:invalid_body`, `:invalid_query`, `:invalid_header`, `:invalid_path` or `:invalid_cookie`. You can pass `message:` to set the error message.
|
|
106
|
+
|
|
107
|
+
You can pass a block to configure [hooks](#hooks) and other options for this middleware only:
|
|
108
|
+
|
|
109
|
+
```ruby
|
|
110
|
+
use OpenapiFirst::Middlewares::RequestValidation, :v1 do |config|
|
|
111
|
+
config.request_validation_error_response = :jsonapi
|
|
112
|
+
config.after_request_validation do |validated_request|
|
|
113
|
+
warn validated_request.error.message if validated_request.invalid?
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
If you pass a registered name or a Definition together with a block, the middleware uses a copy of that OAD that keeps its configuration and adds yours. The registered OAD stays unchanged.
|
|
119
|
+
|
|
87
120
|
#### Error responses
|
|
88
121
|
|
|
89
122
|
openapi_first produces a useful machine readable error response that can be customized.
|
|
@@ -166,6 +199,26 @@ use OpenapiFirst::Middlewares::RequestValidation, error_response: :jsonapi
|
|
|
166
199
|
You can build your own custom error response with `error_response: MyCustomClass` that implements `OpenapiFirst::ErrorResponse`.
|
|
167
200
|
You can define custom error responses globally by including / implementing `OpenapiFirst::ErrorResponse` and register it via `OpenapiFirst.register_error_response(my_name, MyCustomErrorResponse)` and set `error_response: my_name`.
|
|
168
201
|
|
|
202
|
+
A custom error response implements `body` and `content_type`. It can read the `OpenapiFirst::Failure` via `failure` and can override `status`, which defaults to 404, 405, 415 or 400 depending on `failure.type`.
|
|
203
|
+
|
|
204
|
+
```ruby
|
|
205
|
+
class MyErrorResponse
|
|
206
|
+
include OpenapiFirst::ErrorResponse
|
|
207
|
+
|
|
208
|
+
def body
|
|
209
|
+
JSON.generate({ error: failure.message, details: failure.errors&.map(&:message) })
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
def content_type
|
|
213
|
+
'application/json'
|
|
214
|
+
end
|
|
215
|
+
end
|
|
216
|
+
|
|
217
|
+
OpenapiFirst.register_error_response(:my_errors, MyErrorResponse)
|
|
218
|
+
|
|
219
|
+
use OpenapiFirst::Middlewares::RequestValidation, error_response: :my_errors
|
|
220
|
+
```
|
|
221
|
+
|
|
169
222
|
#### Multipart file uploads
|
|
170
223
|
|
|
171
224
|
Uploaded files are not read during request validation. A `multipart/form-data` field that was sent as a file is passed through as Rack parsed it – the same shape that Sinatra and Hanami hand to your application:
|
|
@@ -183,7 +236,7 @@ This means the _content_ of these fields is not validated, so `minLength`, `maxL
|
|
|
183
236
|
|
|
184
237
|
### Response validation
|
|
185
238
|
|
|
186
|
-
> [!
|
|
239
|
+
> [!NOTE]
|
|
187
240
|
> You should use [Contract Testing](#contract-testing) instead of this middleware.
|
|
188
241
|
|
|
189
242
|
This middleware raises an error by default if the response is not valid.
|
|
@@ -244,7 +297,7 @@ OpenapiFirst::Test.setup do |test|
|
|
|
244
297
|
end
|
|
245
298
|
```
|
|
246
299
|
|
|
247
|
-
OpenapiFirst::Test raises an error when a response status is not defined except for 404 and 500. You can change this:
|
|
300
|
+
OpenapiFirst::Test raises an error when a response status is not defined except for 401, 404 and 500. You can change this:
|
|
248
301
|
|
|
249
302
|
```ruby
|
|
250
303
|
OpenapiFirst::Test.setup do |test|
|
|
@@ -288,6 +341,21 @@ OpenapiFirst::Test.setup do |test|
|
|
|
288
341
|
end
|
|
289
342
|
```
|
|
290
343
|
|
|
344
|
+
OpenapiFirst::Test raises `OpenapiFirst::Test::UnknownQueryParameterError` when a test sends a query parameter that the API description does not declare for that operation. This makes typos in tests visible. Requests for which an `ignore_request_error` block returns true are not checked.
|
|
345
|
+
|
|
346
|
+
After the test run, OpenapiFirst::Test reports API coverage and exits with status 2 if the coverage is below `minimum_coverage` (default: 100):
|
|
347
|
+
|
|
348
|
+
```ruby
|
|
349
|
+
OpenapiFirst::Test.setup do |test|
|
|
350
|
+
test.minimum_coverage = 95
|
|
351
|
+
|
|
352
|
+
# true (default): report and enforce minimum_coverage
|
|
353
|
+
# :warn: report, but never fail the test run
|
|
354
|
+
# false: neither report nor enforce
|
|
355
|
+
test.report_coverage = :warn
|
|
356
|
+
end
|
|
357
|
+
```
|
|
358
|
+
|
|
291
359
|
### Test assertions
|
|
292
360
|
|
|
293
361
|
> [!WARNING]
|
|
@@ -300,7 +368,7 @@ Here is how to use it with RSpec, but MiniTest works just as good:
|
|
|
300
368
|
```ruby
|
|
301
369
|
# spec_helper.rb
|
|
302
370
|
OpenapiFirst::Test.setup do |test|
|
|
303
|
-
test.register(File.join(__dir__, '../examples/openapi.yaml')
|
|
371
|
+
test.register(File.join(__dir__, '../examples/openapi.yaml'))
|
|
304
372
|
end
|
|
305
373
|
```
|
|
306
374
|
|
|
@@ -389,12 +457,16 @@ You can integrate your code at certain points during request/response validation
|
|
|
389
457
|
|
|
390
458
|
Available hooks:
|
|
391
459
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
460
|
+
| Hook | Block arguments |
|
|
461
|
+
| --- | --- |
|
|
462
|
+
| `before_request_validation` | `rack_request, request_definition, definition` |
|
|
463
|
+
| `after_request_validation` | `validated_request, definition` |
|
|
464
|
+
| `after_response_validation` | `validated_response, rack_request, definition` |
|
|
465
|
+
| `after_request_parameter_property_validation` | `data, property, property_schema, parent_schema` |
|
|
466
|
+
| `after_request_body_property_validation` | `data, property, property_schema, parent_schema` |
|
|
467
|
+
| `after_response_body_property_validation` | `data, property, property_schema, parent_schema` |
|
|
468
|
+
|
|
469
|
+
`before_request_validation` only runs for requests that match an operation in the API description. The `*_property_validation` hooks run for each property of an object schema after it was validated. `data` is the object that contains `property`, so you can change its value in place. `parent_schema` is the schema of that object, or `nil` for `after_request_parameter_property_validation`.
|
|
398
470
|
|
|
399
471
|
Setup per per instance:
|
|
400
472
|
|
|
@@ -421,6 +493,16 @@ OpenapiFirst.configure do |config|
|
|
|
421
493
|
end
|
|
422
494
|
```
|
|
423
495
|
|
|
496
|
+
You can mark a request as invalid by calling `OpenapiFirst::Failure.fail!` inside a `before_request_validation` or `after_request_validation` hook. If the [request validation middleware](#request-validation) is used, it will render an error response. See [Request validation](#request-validation) for the failure types.
|
|
497
|
+
|
|
498
|
+
```ruby
|
|
499
|
+
OpenapiFirst.configure do |config|
|
|
500
|
+
config.before_request_validation do |rack_request, request_definition|
|
|
501
|
+
OpenapiFirst::Failure.fail!(:not_found) unless request_definition.operation['x-public']
|
|
502
|
+
end
|
|
503
|
+
end
|
|
504
|
+
```
|
|
505
|
+
|
|
424
506
|
## Framework integration
|
|
425
507
|
|
|
426
508
|
Using rack middlewares is supported in probably all Ruby web frameworks.
|
|
@@ -8,14 +8,15 @@ require_relative 'response_header'
|
|
|
8
8
|
require_relative 'parameter'
|
|
9
9
|
require_relative 'parameters_parser'
|
|
10
10
|
require_relative 'query_string_parser'
|
|
11
|
-
require_relative '
|
|
12
|
-
require_relative '
|
|
11
|
+
require_relative 'request_definition'
|
|
12
|
+
require_relative 'response_definition'
|
|
13
13
|
require_relative 'schema/hash'
|
|
14
14
|
require_relative 'ref_resolver'
|
|
15
15
|
|
|
16
16
|
module OpenapiFirst
|
|
17
17
|
# Builds parts of a Definition
|
|
18
|
-
# This knows how to read a resolved OpenAPI document and build {
|
|
18
|
+
# This knows how to read a resolved OpenAPI document and build {RequestDefinition} and {ResponseDefinition} objects.
|
|
19
|
+
# @api private
|
|
19
20
|
class Builder
|
|
20
21
|
REQUEST_METHODS = %w[get head post put patch delete trace options query].freeze
|
|
21
22
|
|
|
@@ -179,24 +180,24 @@ module OpenapiFirst
|
|
|
179
180
|
after_property_validation: config.after_request_body_property_validation
|
|
180
181
|
)
|
|
181
182
|
encoding = content_object['encoding']&.resolved
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
183
|
+
RequestDefinition.new(path:, request_method:, parameters:,
|
|
184
|
+
operation_object: operation_object.resolved,
|
|
185
|
+
content_type:,
|
|
186
|
+
content_schema:,
|
|
187
|
+
encoding:,
|
|
188
|
+
required_body:,
|
|
189
|
+
key: [path, request_method, content_type].join(':'))
|
|
189
190
|
end
|
|
190
191
|
end
|
|
191
192
|
|
|
192
193
|
def request_without_body(path:, request_method:, parameters:, operation_object:)
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
194
|
+
RequestDefinition.new(path:, request_method:, parameters:,
|
|
195
|
+
operation_object: operation_object.resolved,
|
|
196
|
+
content_type: nil,
|
|
197
|
+
content_schema: nil,
|
|
198
|
+
encoding: nil,
|
|
199
|
+
required_body: false,
|
|
200
|
+
key: [path, request_method, nil].join(':'))
|
|
200
201
|
end
|
|
201
202
|
|
|
202
203
|
def build_responses(responses:, request:)
|
|
@@ -209,13 +210,13 @@ module OpenapiFirst
|
|
|
209
210
|
configuration: schemer_configuration,
|
|
210
211
|
after_property_validation: config.after_response_body_property_validation
|
|
211
212
|
)
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
end ||
|
|
218
|
-
|
|
213
|
+
ResponseDefinition.new(status:,
|
|
214
|
+
headers:,
|
|
215
|
+
content_type:,
|
|
216
|
+
content_schema:,
|
|
217
|
+
key: [request.key, status, content_type].join(':'))
|
|
218
|
+
end || ResponseDefinition.new(status:, headers:, content_type: nil,
|
|
219
|
+
content_schema: nil, key: [request.key, status, nil].join(':'))
|
|
219
220
|
end
|
|
220
221
|
end
|
|
221
222
|
|
|
@@ -2,20 +2,25 @@
|
|
|
2
2
|
|
|
3
3
|
module OpenapiFirst
|
|
4
4
|
# A subclass to configuration that points to its parent
|
|
5
|
+
# @api private
|
|
5
6
|
class ChildConfiguration < Configuration
|
|
6
7
|
def initialize(parent:)
|
|
7
8
|
super()
|
|
8
9
|
@parent = parent
|
|
9
|
-
@request_validation_error_response =
|
|
10
|
+
@request_validation_error_response = nil
|
|
10
11
|
@path = parent.path
|
|
11
12
|
@regexp_resolver = parent.regexp_resolver
|
|
12
13
|
end
|
|
13
14
|
|
|
14
15
|
private attr_reader :parent
|
|
15
16
|
|
|
17
|
+
def request_validation_error_response
|
|
18
|
+
@request_validation_error_response || parent.request_validation_error_response
|
|
19
|
+
end
|
|
20
|
+
|
|
16
21
|
HOOKS.each do |hook|
|
|
17
22
|
define_method(hook) do |&block|
|
|
18
|
-
return hooks[hook].chain(parent.
|
|
23
|
+
return hooks[hook].chain(parent.public_send(hook)) if block.nil?
|
|
19
24
|
|
|
20
25
|
hooks[hook] << block
|
|
21
26
|
block
|
|
@@ -1,8 +1,57 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module OpenapiFirst
|
|
4
|
-
#
|
|
4
|
+
# Configuration of hooks, plugins and options. {OpenapiFirst.configure} yields the global configuration.
|
|
5
|
+
# A block passed to {OpenapiFirst.load} yields a child of it, which also runs the global hooks.
|
|
6
|
+
#
|
|
7
|
+
# @!method before_request_validation(&block)
|
|
8
|
+
# Adds a hook that runs before a request is validated. It runs only for requests that match an
|
|
9
|
+
# operation. Call {Failure.fail!} inside the block to mark the request as invalid.
|
|
10
|
+
# @yieldparam rack_request [Rack::Request]
|
|
11
|
+
# @yieldparam request_definition [RequestDefinition]
|
|
12
|
+
# @yieldparam definition [Definition]
|
|
13
|
+
# @return [Proc, Enumerable<Proc>] The block, or all hooks of this kind if no block is given
|
|
14
|
+
#
|
|
15
|
+
# @!method after_request_validation(&block)
|
|
16
|
+
# Adds a hook that runs after a request was validated, including unknown requests.
|
|
17
|
+
# Call {Failure.fail!} inside the block to mark the request as invalid.
|
|
18
|
+
# @yieldparam validated_request [ValidatedRequest]
|
|
19
|
+
# @yieldparam definition [Definition]
|
|
20
|
+
# @return [Proc, Enumerable<Proc>] The block, or all hooks of this kind if no block is given
|
|
21
|
+
#
|
|
22
|
+
# @!method after_response_validation(&block)
|
|
23
|
+
# Adds a hook that runs after a response was validated.
|
|
24
|
+
# It does not run for responses to requests that match no operation.
|
|
25
|
+
# @yieldparam validated_response [ValidatedResponse]
|
|
26
|
+
# @yieldparam rack_request [Rack::Request]
|
|
27
|
+
# @yieldparam definition [Definition]
|
|
28
|
+
# @return [Proc, Enumerable<Proc>] The block, or all hooks of this kind if no block is given
|
|
29
|
+
#
|
|
30
|
+
# @!method after_request_parameter_property_validation(&block)
|
|
31
|
+
# Adds a hook that runs for each request parameter after it was validated.
|
|
32
|
+
# @yieldparam data [Hash] The parsed parameters. Change a value in place to replace it.
|
|
33
|
+
# @yieldparam property [String] The parameter name
|
|
34
|
+
# @yieldparam property_schema [Hash] The JSON Schema of the parameter
|
|
35
|
+
# @yieldparam parent [nil]
|
|
36
|
+
# @return [Proc, Enumerable<Proc>] The block, or all hooks of this kind if no block is given
|
|
37
|
+
#
|
|
38
|
+
# @!method after_request_body_property_validation(&block)
|
|
39
|
+
# Adds a hook that runs for each property of an object in the request body after it was validated.
|
|
40
|
+
# @yieldparam data [Hash] The object that contains property. Change a value in place to replace it.
|
|
41
|
+
# @yieldparam property [String]
|
|
42
|
+
# @yieldparam property_schema [Hash] The JSON Schema of the property
|
|
43
|
+
# @yieldparam parent [Hash, nil]
|
|
44
|
+
# @return [Proc, Enumerable<Proc>] The block, or all hooks of this kind if no block is given
|
|
45
|
+
#
|
|
46
|
+
# @!method after_response_body_property_validation(&block)
|
|
47
|
+
# Adds a hook that runs for each property of an object in the response body after it was validated.
|
|
48
|
+
# @yieldparam data [Hash] The object that contains property. Change a value in place to replace it.
|
|
49
|
+
# @yieldparam property [String]
|
|
50
|
+
# @yieldparam property_schema [Hash] The JSON Schema of the property
|
|
51
|
+
# @yieldparam parent [Hash, nil]
|
|
52
|
+
# @return [Proc, Enumerable<Proc>] The block, or all hooks of this kind if no block is given
|
|
5
53
|
class Configuration
|
|
54
|
+
# The names of all hooks
|
|
6
55
|
HOOKS = %i[
|
|
7
56
|
before_request_validation
|
|
8
57
|
after_request_validation
|
|
@@ -19,11 +68,28 @@ module OpenapiFirst
|
|
|
19
68
|
@regexp_resolver = nil
|
|
20
69
|
end
|
|
21
70
|
|
|
71
|
+
# Loads and registers an API description globally. See {OpenapiFirst.register}.
|
|
72
|
+
# @param path_or_definition [String, Definition]
|
|
73
|
+
# @param as [Symbol] The name to register it under
|
|
74
|
+
# @return [Definition]
|
|
22
75
|
def register(path_or_definition, as: :default, &)
|
|
23
76
|
OpenapiFirst.register(path_or_definition, as:, &)
|
|
24
77
|
end
|
|
25
78
|
|
|
79
|
+
# @!attribute [r] hooks
|
|
80
|
+
# @return [Hash<Symbol, Set<Proc>>] The hooks added to this configuration, by hook name
|
|
81
|
+
# @!attribute [r] request_validation_error_response
|
|
82
|
+
# @return [Class] The error response class the request validation middleware renders
|
|
83
|
+
# @!attribute [r] regexp_resolver
|
|
84
|
+
# @return [String, Proc, nil] How JSON Schema `pattern` is evaluated. See {#regexp_resolver=}.
|
|
26
85
|
attr_reader :hooks, :request_validation_error_response, :regexp_resolver
|
|
86
|
+
|
|
87
|
+
# @!attribute [rw] path
|
|
88
|
+
# A Proc that receives the Rack::Request and returns the path to look up in the API description.
|
|
89
|
+
# Use this if your app is mounted under a path that the API description does not contain.
|
|
90
|
+
# @example
|
|
91
|
+
# config.path = ->(rack_request) { rack_request.path.delete_prefix('/api') }
|
|
92
|
+
# @return [Proc, nil]
|
|
27
93
|
attr_accessor :path
|
|
28
94
|
|
|
29
95
|
# Return a child configuration that still receives updates of global hooks.
|
|
@@ -31,7 +97,7 @@ module OpenapiFirst
|
|
|
31
97
|
ChildConfiguration.new(parent: self)
|
|
32
98
|
end
|
|
33
99
|
|
|
34
|
-
# @
|
|
100
|
+
# @api private
|
|
35
101
|
def clone
|
|
36
102
|
raise NoMethodError, 'OpenapiFirst::Configuration#clone was removed. You want to call #child instead'
|
|
37
103
|
end
|
|
@@ -45,15 +111,27 @@ module OpenapiFirst
|
|
|
45
111
|
end
|
|
46
112
|
end
|
|
47
113
|
|
|
114
|
+
# Loads a plugin and lets it configure this configuration.
|
|
115
|
+
# @example
|
|
116
|
+
# config.plugin :x_public, field: 'x-visible'
|
|
117
|
+
# @param name [Symbol] The plugin name, e.g. :x_public for {Plugins::XPublic}
|
|
118
|
+
# @return [void]
|
|
119
|
+
# @see Plugins
|
|
48
120
|
def plugin(name, **)
|
|
49
121
|
require_relative 'plugins'
|
|
50
122
|
Plugins.load(name).configure(self, **)
|
|
51
123
|
end
|
|
52
124
|
|
|
125
|
+
# Sets how JSON Schema `pattern` is evaluated. It is passed to json_schemer as `regexp_resolver`.
|
|
126
|
+
# OpenAPI requires ECMA-262 regular expressions, so 'ecma' is recommended.
|
|
127
|
+
# @param resolver [String, Symbol, Proc] 'ruby' (default), 'ecma' or a Proc
|
|
53
128
|
def regexp_resolver=(resolver)
|
|
54
129
|
@regexp_resolver = resolver.is_a?(Symbol) ? resolver.to_s : resolver
|
|
55
130
|
end
|
|
56
131
|
|
|
132
|
+
# Sets the error response that the request validation middleware renders.
|
|
133
|
+
# @param mod [Symbol, Class] A name registered via {OpenapiFirst.register_error_response}
|
|
134
|
+
# (:default, :jsonapi) or a class that includes {ErrorResponse}
|
|
57
135
|
def request_validation_error_response=(mod)
|
|
58
136
|
@request_validation_error_response = if mod.is_a?(Symbol)
|
|
59
137
|
OpenapiFirst.find_error_response(mod)
|
|
@@ -24,10 +24,11 @@ module OpenapiFirst
|
|
|
24
24
|
# @param contents [Hash] The OpenAPI document.
|
|
25
25
|
# @param filepath [String] The file path of the OpenAPI document.
|
|
26
26
|
# @param path_prefix [String,nil] An optional path prefix, that is not documented, that all requests begin with.
|
|
27
|
-
|
|
27
|
+
# @param config [Configuration] The configuration to use. Gets yielded and frozen.
|
|
28
|
+
def initialize(contents, filepath = nil, path_prefix = nil, config: OpenapiFirst.configuration.child)
|
|
28
29
|
@filepath = filepath
|
|
29
30
|
@path_prefix = path_prefix
|
|
30
|
-
@config =
|
|
31
|
+
@config = config
|
|
31
32
|
yield @config if block_given?
|
|
32
33
|
@config.freeze
|
|
33
34
|
@router = Builder.build_router(contents, filepath:, config:)
|
|
@@ -35,6 +36,14 @@ module OpenapiFirst
|
|
|
35
36
|
@paths = @router.routes.map(&:path).to_a.uniq # TODO: Refactor
|
|
36
37
|
end
|
|
37
38
|
|
|
39
|
+
# Returns a new Definition of the same document whose configuration is a child of this one's.
|
|
40
|
+
# @api private
|
|
41
|
+
# @yield [Configuration]
|
|
42
|
+
# @return [Definition]
|
|
43
|
+
def configure(&)
|
|
44
|
+
Definition.new(@resolved, filepath, path_prefix, config: @config.child, &)
|
|
45
|
+
end
|
|
46
|
+
|
|
38
47
|
# Gives access to the raw resolved Hash. Like `mydefinition['components'].dig('schemas', 'Stations')`
|
|
39
48
|
# @!method [](key)
|
|
40
49
|
# @return [Hash]
|
|
@@ -122,7 +131,8 @@ module OpenapiFirst
|
|
|
122
131
|
# @param request [Rack::Request] The Rack request object.
|
|
123
132
|
# @param response [Rack::Response] The Rack response object.
|
|
124
133
|
# @param raise_error [Boolean] Whether to raise an error if validation fails.
|
|
125
|
-
# @return [ValidatedResponse] The validated response object
|
|
134
|
+
# @return [ValidatedResponse, nil] The validated response object, or nil if the request does not match
|
|
135
|
+
# any operation in the API description. Responses to unknown requests are not validated.
|
|
126
136
|
def validate_response(request, response, raise_error: false)
|
|
127
137
|
route = @router.match(request.request_method, resolve_path(request), content_type: request.content_type)
|
|
128
138
|
return if route.error # Skip response validation for unknown requests
|
|
@@ -1,21 +1,33 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module OpenapiFirst
|
|
4
|
-
#
|
|
4
|
+
# Include this module to build an error response for the request validation middleware.
|
|
5
|
+
# Implement {#body} and {#content_type}; override {#status} or {#render} if needed.
|
|
6
|
+
# Register it via {OpenapiFirst.register_error_response} to refer to it by name.
|
|
7
|
+
# @example
|
|
8
|
+
# class MyErrorResponse
|
|
9
|
+
# include OpenapiFirst::ErrorResponse
|
|
10
|
+
#
|
|
11
|
+
# def body = JSON.generate({ error: failure.message })
|
|
12
|
+
# def content_type = 'application/json'
|
|
13
|
+
# end
|
|
5
14
|
module ErrorResponse
|
|
6
|
-
|
|
15
|
+
# @param failure [OpenapiFirst::Failure]
|
|
7
16
|
def initialize(failure: nil)
|
|
8
17
|
@failure = failure
|
|
9
18
|
end
|
|
10
19
|
|
|
20
|
+
# @return [OpenapiFirst::Failure] The reason why the request is invalid
|
|
11
21
|
attr_reader :failure
|
|
12
22
|
|
|
13
23
|
# The response body
|
|
24
|
+
# @return [String]
|
|
14
25
|
def body
|
|
15
26
|
raise "#{self.class} must implement the method #{__method__}"
|
|
16
27
|
end
|
|
17
28
|
|
|
18
29
|
# The response content-type
|
|
30
|
+
# @return [String]
|
|
19
31
|
def content_type
|
|
20
32
|
raise "#{self.class} must implement the method #{__method__}"
|
|
21
33
|
end
|
|
@@ -27,12 +39,15 @@ module OpenapiFirst
|
|
|
27
39
|
}.freeze
|
|
28
40
|
private_constant :STATUS
|
|
29
41
|
|
|
30
|
-
# The response status
|
|
42
|
+
# The response status: 404 for :not_found, 405 for :method_not_allowed, 415 for
|
|
43
|
+
# :unsupported_media_type, otherwise 400
|
|
44
|
+
# @return [Integer]
|
|
31
45
|
def status
|
|
32
46
|
STATUS[failure.type] || 400
|
|
33
47
|
end
|
|
34
48
|
|
|
35
49
|
# Render this error response
|
|
50
|
+
# @return [Array] A Rack response triplet
|
|
36
51
|
def render
|
|
37
52
|
Rack::Response.new(body, status, Rack::CONTENT_TYPE => content_type).finish
|
|
38
53
|
end
|
|
@@ -20,8 +20,18 @@ module OpenapiFirst
|
|
|
20
20
|
}.freeze
|
|
21
21
|
private_constant :TYPES
|
|
22
22
|
|
|
23
|
-
#
|
|
24
|
-
#
|
|
23
|
+
# Marks the current request as invalid with a new Failure and stops validation.
|
|
24
|
+
# Call this only inside a `before_request_validation` or `after_request_validation` hook or in
|
|
25
|
+
# the block passed to {Definition#validate_request}. It uses `throw`, which nothing else catches.
|
|
26
|
+
# @example
|
|
27
|
+
# config.before_request_validation do |rack_request, request_definition|
|
|
28
|
+
# OpenapiFirst::Failure.fail!(:not_found) unless request_definition.operation['x-public']
|
|
29
|
+
# end
|
|
30
|
+
# @param type [Symbol] One of :not_found, :method_not_allowed, :unsupported_media_type,
|
|
31
|
+
# :invalid_body, :invalid_query, :invalid_header, :invalid_path, :invalid_cookie
|
|
32
|
+
# @param message [String, nil] The error message
|
|
33
|
+
# @param errors [Array<OpenapiFirst::Schema::ValidationError>, nil]
|
|
34
|
+
# @return [void]
|
|
25
35
|
def self.fail!(type, message: nil, errors: nil)
|
|
26
36
|
throw FAILURE, new(
|
|
27
37
|
type,
|
|
@@ -30,8 +40,12 @@ module OpenapiFirst
|
|
|
30
40
|
)
|
|
31
41
|
end
|
|
32
42
|
|
|
33
|
-
# @param type [Symbol]
|
|
43
|
+
# @param type [Symbol] One of :not_found, :method_not_allowed, :unsupported_media_type,
|
|
44
|
+
# :invalid_body, :invalid_query, :invalid_header, :invalid_path, :invalid_cookie,
|
|
45
|
+
# :response_content_type_not_found, :response_status_not_found, :invalid_response_body,
|
|
46
|
+
# :invalid_response_header
|
|
34
47
|
# @param message [String] A generic error message
|
|
48
|
+
# @raise [ArgumentError] if type is unknown
|
|
35
49
|
# @param errors [Array<OpenapiFirst::Schema::ValidationError>]
|
|
36
50
|
def self.new(type, message: nil, errors: nil)
|
|
37
51
|
unless TYPES.key?(type)
|
|
@@ -41,10 +55,11 @@ module OpenapiFirst
|
|
|
41
55
|
super(type:, message:, errors:)
|
|
42
56
|
end
|
|
43
57
|
|
|
44
|
-
#
|
|
45
|
-
#
|
|
58
|
+
# @!attribute [r] type
|
|
59
|
+
# @return [Symbol] The type of the failure, e.g. :invalid_body. See {.new} for all types.
|
|
46
60
|
|
|
47
|
-
#
|
|
61
|
+
# @!attribute [r] errors
|
|
62
|
+
# @return [Array<OpenapiFirst::Schema::ValidationError>, nil] Schema validation errors
|
|
48
63
|
|
|
49
64
|
alias original_message message
|
|
50
65
|
private :original_message
|
|
@@ -53,15 +68,20 @@ module OpenapiFirst
|
|
|
53
68
|
"#<OpenapiFirst::Failure:#{object_id} type: #{type}, message: #{message}>"
|
|
54
69
|
end
|
|
55
70
|
|
|
56
|
-
#
|
|
71
|
+
# The message passed to {.new}, or {#exception_message} if none was passed
|
|
72
|
+
# @return [String]
|
|
57
73
|
def message
|
|
58
74
|
original_message || exception_message
|
|
59
75
|
end
|
|
60
76
|
|
|
77
|
+
# @param context [ValidatedRequest, ValidatedResponse, nil] The object that failed validation
|
|
78
|
+
# @return [RequestInvalidError, NotFoundError, ResponseInvalidError, ResponseNotFoundError]
|
|
79
|
+
# The exception to raise for this failure type
|
|
61
80
|
def exception(context = nil)
|
|
62
81
|
TYPES.fetch(type).first.new(exception_message, context)
|
|
63
82
|
end
|
|
64
83
|
|
|
84
|
+
# @return [String] The message of {#exception}, prefixed by the failure type, e.g. "Request body invalid: ..."
|
|
65
85
|
def exception_message
|
|
66
86
|
_, message_prefix = TYPES.fetch(type)
|
|
67
87
|
|
data/lib/openapi_first/json.rb
CHANGED
|
@@ -29,25 +29,26 @@ module OpenapiFirst
|
|
|
29
29
|
# :error_response The Class to use for error responses.
|
|
30
30
|
# This can be a Symbol-name of an registered error response (:default, :jsonapi)
|
|
31
31
|
# or it can be set to false to disable returning a response.
|
|
32
|
-
# default:
|
|
33
|
-
|
|
32
|
+
# default: the configured request_validation_error_response
|
|
33
|
+
# @yield [Configuration] Optional block to configure hooks and other options for this middleware.
|
|
34
|
+
# If spec is a registered name or a Definition, this uses a new Definition that inherits its configuration,
|
|
35
|
+
# so the registered Definition is not changed.
|
|
36
|
+
def initialize(app, spec = nil, options = {}, &)
|
|
34
37
|
@app = app
|
|
35
38
|
if spec.is_a?(Hash)
|
|
36
39
|
options = spec
|
|
37
40
|
spec = options[:spec]
|
|
38
41
|
end
|
|
39
42
|
@raise = options.fetch(:raise_error, false)
|
|
43
|
+
@definition = OpenapiFirst.load(spec || :default, &)
|
|
40
44
|
@error_response_class = error_response_option(options[:error_response])
|
|
41
|
-
|
|
42
|
-
spec ||= :default
|
|
43
|
-
spec = OpenapiFirst[spec] if spec.is_a?(Symbol)
|
|
44
|
-
|
|
45
|
-
@definition = spec.is_a?(Definition) ? spec : OpenapiFirst.load(spec)
|
|
46
45
|
end
|
|
47
46
|
|
|
48
47
|
# @attr_reader [Proc] app The upstream Rack application
|
|
49
48
|
attr_reader :app
|
|
50
49
|
|
|
50
|
+
# @param env [Hash] The Rack env
|
|
51
|
+
# @return [Array] A Rack response
|
|
51
52
|
def call(env)
|
|
52
53
|
rack_response = nil
|
|
53
54
|
app_called = false
|
|
@@ -70,7 +71,7 @@ module OpenapiFirst
|
|
|
70
71
|
return if value == false
|
|
71
72
|
return OpenapiFirst.find_error_response(value) if value.is_a?(Symbol)
|
|
72
73
|
|
|
73
|
-
value ||
|
|
74
|
+
value || @definition.config.request_validation_error_response
|
|
74
75
|
end
|
|
75
76
|
end
|
|
76
77
|
end
|