openapi_first 4.4.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.
Files changed (74) hide show
  1. checksums.yaml +4 -4
  2. data/.yardopts +7 -0
  3. data/CHANGELOG.md +6 -0
  4. data/README.md +79 -10
  5. data/lib/openapi_first/builder.rb +25 -24
  6. data/lib/openapi_first/child_configuration.rb +1 -0
  7. data/lib/openapi_first/configuration.rb +80 -2
  8. data/lib/openapi_first/definition.rb +3 -2
  9. data/lib/openapi_first/error_response.rb +18 -3
  10. data/lib/openapi_first/failure.rb +27 -7
  11. data/lib/openapi_first/file_loader.rb +1 -1
  12. data/lib/openapi_first/json.rb +1 -1
  13. data/lib/openapi_first/middlewares/request_validation.rb +2 -0
  14. data/lib/openapi_first/middlewares/response_validation.rb +2 -0
  15. data/lib/openapi_first/parameter/converter/array_converter.rb +1 -1
  16. data/lib/openapi_first/parameter/converter/object_converter.rb +1 -1
  17. data/lib/openapi_first/parameter/converter.rb +1 -1
  18. data/lib/openapi_first/parameter/unpackers.rb +1 -1
  19. data/lib/openapi_first/parameter.rb +3 -0
  20. data/lib/openapi_first/parameters_parser.rb +1 -1
  21. data/lib/openapi_first/parsed_request.rb +1 -0
  22. data/lib/openapi_first/path_template.rb +1 -1
  23. data/lib/openapi_first/plugins/x_public.rb +3 -0
  24. data/lib/openapi_first/query_string_parser.rb +1 -1
  25. data/lib/openapi_first/ref_resolver.rb +16 -11
  26. data/lib/openapi_first/registry.rb +2 -4
  27. data/lib/openapi_first/request_body_parsers.rb +1 -1
  28. data/lib/openapi_first/{request.rb → request_definition.rb} +27 -1
  29. data/lib/openapi_first/request_headers.rb +1 -1
  30. data/lib/openapi_first/request_validator.rb +1 -0
  31. data/lib/openapi_first/response_body_parsers.rb +1 -1
  32. data/lib/openapi_first/{response.rb → response_definition.rb} +19 -4
  33. data/lib/openapi_first/response_parser.rb +3 -1
  34. data/lib/openapi_first/response_validator.rb +1 -0
  35. data/lib/openapi_first/router/find_content.rb +1 -1
  36. data/lib/openapi_first/router/find_response.rb +1 -1
  37. data/lib/openapi_first/router/path_trie.rb +1 -1
  38. data/lib/openapi_first/router/segment_pattern.rb +1 -1
  39. data/lib/openapi_first/router.rb +1 -0
  40. data/lib/openapi_first/schema/hash.rb +15 -1
  41. data/lib/openapi_first/schema/validation_result.rb +1 -0
  42. data/lib/openapi_first/sinatra.rb +2 -2
  43. data/lib/openapi_first/test/app.rb +3 -0
  44. data/lib/openapi_first/test/callable.rb +1 -0
  45. data/lib/openapi_first/test/configuration.rb +6 -4
  46. data/lib/openapi_first/test/coverage/covered_request.rb +1 -0
  47. data/lib/openapi_first/test/coverage/covered_response.rb +1 -0
  48. data/lib/openapi_first/test/coverage/html_reporter/context.rb +1 -0
  49. data/lib/openapi_first/test/coverage/html_reporter.rb +2 -0
  50. data/lib/openapi_first/test/coverage/plan.rb +1 -0
  51. data/lib/openapi_first/test/coverage/request_task.rb +1 -1
  52. data/lib/openapi_first/test/coverage/response_task.rb +1 -1
  53. data/lib/openapi_first/test/coverage/route_task.rb +1 -0
  54. data/lib/openapi_first/test/coverage/skipped_summary.rb +1 -0
  55. data/lib/openapi_first/test/coverage/terminal_reporter.rb +2 -0
  56. data/lib/openapi_first/test/coverage/tracker.rb +1 -0
  57. data/lib/openapi_first/test/coverage.rb +11 -4
  58. data/lib/openapi_first/test/methods.rb +14 -1
  59. data/lib/openapi_first/test/minitest_helpers.rb +5 -2
  60. data/lib/openapi_first/test/observe.rb +2 -1
  61. data/lib/openapi_first/test/observer_middleware.rb +1 -0
  62. data/lib/openapi_first/test/plain_helpers.rb +7 -4
  63. data/lib/openapi_first/test.rb +30 -3
  64. data/lib/openapi_first/utils.rb +1 -1
  65. data/lib/openapi_first/validated_request.rb +4 -4
  66. data/lib/openapi_first/validated_response.rb +5 -3
  67. data/lib/openapi_first/validators/multipart_request_body.rb +1 -0
  68. data/lib/openapi_first/validators/request_body.rb +1 -0
  69. data/lib/openapi_first/validators/request_parameters.rb +1 -1
  70. data/lib/openapi_first/validators/response_body.rb +1 -0
  71. data/lib/openapi_first/validators/response_headers.rb +1 -0
  72. data/lib/openapi_first/version.rb +1 -1
  73. data/lib/openapi_first.rb +7 -2
  74. metadata +4 -3
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ef15e925e193150f3425c32bd94986f3c069f12af86a88ad043886de13c1ca8a
4
- data.tar.gz: d4f11e849a469be720cbd5973ffb04e039664101ed44484d4b4f4b2c5ef542f8
3
+ metadata.gz: 33b54b526cc7579d4c7bed16fef0c283d3752fa3ccb5e7371e5a39b87b1189ba
4
+ data.tar.gz: 369cb181d69488cef0edbcccf1f2a1a0d92430a1e00bd2d96bdd28b665300742
5
5
  SHA512:
6
- metadata.gz: 8aa700d2587944d67f5e2372fe7793c1cd71a76e6c772bf56938564e4f4c4221cb29e54e0ec37bec66c1da370415aabbebb7f722f4cd4fbeba478919308df6cb
7
- data.tar.gz: 6ef3870f3b011ac35065775da7265d6bc6dff0b121ec0ee42a7e5b47a9fd69d17dbc25ea85723615206d9704afcaee4f65ff3f04e6c85f430ea4781316260ff8
6
+ metadata.gz: 798b8ceb7787be4ed6a530a9869b08976c2b8442da35f3dbc9f1f241cc3dfec105bf1474aaf095f2b8e4d561fbe49598bef54d19a7da64b792c31fc677708121
7
+ data.tar.gz: be67bcb40e82bbdeb1574868ead6b3ba3442ca7fe91961582ee7711a7ab7701454fae8f858e23d1c32e03cc208d7fdca1ae4f730798b24527f7f2326761c85cb
data/.yardopts ADDED
@@ -0,0 +1,7 @@
1
+ --markup markdown
2
+ --hide-api private
3
+ lib/**/*.rb
4
+ -
5
+ README.md
6
+ CHANGELOG.md
7
+ LICENSE.txt
data/CHANGELOG.md CHANGED
@@ -2,6 +2,12 @@
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
+
5
11
  ## 4.4.0
6
12
 
7
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"]`.
data/README.md CHANGED
@@ -78,12 +78,32 @@ 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 a request object to the current Rack environment at `env[OpenapiFirst::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.
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
+
87
107
  You can pass a block to configure [hooks](#hooks) and other options for this middleware only:
88
108
 
89
109
  ```ruby
@@ -179,6 +199,26 @@ use OpenapiFirst::Middlewares::RequestValidation, error_response: :jsonapi
179
199
  You can build your own custom error response with `error_response: MyCustomClass` that implements `OpenapiFirst::ErrorResponse`.
180
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`.
181
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
+
182
222
  #### Multipart file uploads
183
223
 
184
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:
@@ -196,7 +236,7 @@ This means the _content_ of these fields is not validated, so `minLength`, `maxL
196
236
 
197
237
  ### Response validation
198
238
 
199
- > [!WARNING]
239
+ > [!NOTE]
200
240
  > You should use [Contract Testing](#contract-testing) instead of this middleware.
201
241
 
202
242
  This middleware raises an error by default if the response is not valid.
@@ -257,7 +297,7 @@ OpenapiFirst::Test.setup do |test|
257
297
  end
258
298
  ```
259
299
 
260
- 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:
261
301
 
262
302
  ```ruby
263
303
  OpenapiFirst::Test.setup do |test|
@@ -301,6 +341,21 @@ OpenapiFirst::Test.setup do |test|
301
341
  end
302
342
  ```
303
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
+
304
359
  ### Test assertions
305
360
 
306
361
  > [!WARNING]
@@ -313,7 +368,7 @@ Here is how to use it with RSpec, but MiniTest works just as good:
313
368
  ```ruby
314
369
  # spec_helper.rb
315
370
  OpenapiFirst::Test.setup do |test|
316
- test.register(File.join(__dir__, '../examples/openapi.yaml'), as: :example_app)
371
+ test.register(File.join(__dir__, '../examples/openapi.yaml'))
317
372
  end
318
373
  ```
319
374
 
@@ -402,12 +457,16 @@ You can integrate your code at certain points during request/response validation
402
457
 
403
458
  Available hooks:
404
459
 
405
- - `before_request_validation`
406
- - `after_request_validation`
407
- - `after_response_validation`
408
- - `after_request_parameter_property_validation`
409
- - `after_request_body_property_validation`
410
- - `after_response_body_property_validation`
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`.
411
470
 
412
471
  Setup per per instance:
413
472
 
@@ -434,6 +493,16 @@ OpenapiFirst.configure do |config|
434
493
  end
435
494
  ```
436
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
+
437
506
  ## Framework integration
438
507
 
439
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 'request'
12
- require_relative 'response'
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 {Request} and {Response} objects.
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
- Request.new(path:, request_method:, parameters:,
183
- operation_object: operation_object.resolved,
184
- content_type:,
185
- content_schema:,
186
- encoding:,
187
- required_body:,
188
- key: [path, request_method, content_type].join(':'))
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
- Request.new(path:, request_method:, parameters:,
194
- operation_object: operation_object.resolved,
195
- content_type: nil,
196
- content_schema: nil,
197
- encoding: nil,
198
- required_body: false,
199
- key: [path, request_method, nil].join(':'))
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
- Response.new(status:,
213
- headers:,
214
- content_type:,
215
- content_schema:,
216
- key: [request.key, status, content_type].join(':'))
217
- end || Response.new(status:, headers:, content_type: nil,
218
- content_schema: nil, key: [request.key, status, nil].join(':'))
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,6 +2,7 @@
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()
@@ -1,8 +1,57 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module OpenapiFirst
4
- # Global configuration. Currently only used for the request validation middleware.
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
- # @visibility private
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)
@@ -37,7 +37,7 @@ module OpenapiFirst
37
37
  end
38
38
 
39
39
  # Returns a new Definition of the same document whose configuration is a child of this one's.
40
- # @visibility private
40
+ # @api private
41
41
  # @yield [Configuration]
42
42
  # @return [Definition]
43
43
  def configure(&)
@@ -131,7 +131,8 @@ module OpenapiFirst
131
131
  # @param request [Rack::Request] The Rack request object.
132
132
  # @param response [Rack::Response] The Rack response object.
133
133
  # @param raise_error [Boolean] Whether to raise an error if validation fails.
134
- # @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.
135
136
  def validate_response(request, response, raise_error: false)
136
137
  route = @router.match(request.request_method, resolve_path(request), content_type: request.content_type)
137
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
- # This is the base module for error responses
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
- ## @param failure [OpenapiFirst::Failure]
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
- # @param type [Symbol] See Failure::TYPES.keys
24
- # @param errors [Array<OpenapiFirst::Schema::ValidationError>]
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] See TYPES.keys
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
- # @method type [Symbol] type The type of the failure. See TYPES.keys.
45
- # Example: :invalid_body
58
+ # @!attribute [r] type
59
+ # @return [Symbol] The type of the failure, e.g. :invalid_body. See {.new} for all types.
46
60
 
47
- # @method errors [Array<OpenapiFirst::Schema::ValidationError>, nil] errors Schema validation errors
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
- # A generic error message
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
 
@@ -4,7 +4,7 @@ require 'json'
4
4
  require 'yaml'
5
5
 
6
6
  module OpenapiFirst
7
- # @!visibility private
7
+ # @api private
8
8
  class FileLoader
9
9
  def self.load(file_path)
10
10
  new.load(file_path)
@@ -8,7 +8,7 @@ begin
8
8
 
9
9
  module OpenapiFirst
10
10
  # Compatibility with MultiJson
11
- # @visibility private
11
+ # @api private
12
12
  module JSON
13
13
  if defined?(::MultiJSON)
14
14
  # multi_json >= 1.21.0
@@ -47,6 +47,8 @@ module OpenapiFirst
47
47
  # @attr_reader [Proc] app The upstream Rack application
48
48
  attr_reader :app
49
49
 
50
+ # @param env [Hash] The Rack env
51
+ # @return [Array] A Rack response
50
52
  def call(env)
51
53
  rack_response = nil
52
54
  app_called = false
@@ -31,6 +31,8 @@ module OpenapiFirst
31
31
  # @attr_reader [Proc] app The upstream Rack application
32
32
  attr_reader :app
33
33
 
34
+ # @param env [Hash] The Rack env
35
+ # @return [Array] A Rack response
34
36
  def call(env)
35
37
  status, headers, body = @app.call(env)
36
38
  @definition.validate_response(Rack::Request.new(env), Rack::Response[status, headers, body],
@@ -4,7 +4,7 @@ module OpenapiFirst
4
4
  class Parameter
5
5
  module Converter
6
6
  # Converts the items of an array parameter value
7
- # @visibility private
7
+ # @api private
8
8
  ArrayConverter = Data.define(:schema) do
9
9
  def call(value)
10
10
  return [] if value.nil? || value.empty?
@@ -4,7 +4,7 @@ module OpenapiFirst
4
4
  class Parameter
5
5
  module Converter
6
6
  # Converts the properties of an object parameter value
7
- # @visibility private
7
+ # @api private
8
8
  ObjectConverter = Data.define(:schema) do
9
9
  def self.get_properties(schema) # rubocop:disable Metrics
10
10
  return nil if schema.nil? || schema.empty?
@@ -6,7 +6,7 @@ require_relative 'converter/object_converter'
6
6
  module OpenapiFirst
7
7
  class Parameter
8
8
  # Converts a parameter value (string) to the type specified in the JSON Schema.
9
- # @visibility private
9
+ # @api private
10
10
  module Converter
11
11
  PASS_THROUGH = ->(value) { value }
12
12
 
@@ -9,7 +9,7 @@ module OpenapiFirst
9
9
  # Each unpacker is a callable that takes a raw string (or already-parsed
10
10
  # value) and returns the unpacked Ruby value, throwing :skip on unrecoverable
11
11
  # parse errors.
12
- # @visibility private
12
+ # @api private
13
13
  module Unpackers
14
14
  ARRAY_DELIMITER = {
15
15
  'label' => '.',
@@ -32,12 +32,14 @@ module OpenapiFirst
32
32
 
33
33
  attr_reader :name, :schema, :location, :media_type, :style
34
34
 
35
+ # @api private
35
36
  def unpack(value)
36
37
  return value if value.nil?
37
38
 
38
39
  @unpacker.call(value)
39
40
  end
40
41
 
42
+ # @api private
41
43
  def convert(value) = @converter.call(value)
42
44
 
43
45
  # Unpacks and converts a raw value.
@@ -57,6 +59,7 @@ module OpenapiFirst
57
59
 
58
60
  def deep_object? = @deep_object
59
61
 
62
+ # @return [String, nil] The JSON Schema type of the parameter
60
63
  def type = schema && schema['type']
61
64
 
62
65
  def array? = type == 'array'
@@ -2,7 +2,7 @@
2
2
 
3
3
  module OpenapiFirst
4
4
  # Unpacks parameters from a Hash of raw values, like path parameters, headers or cookies.
5
- # @visibility private
5
+ # @api private
6
6
  class ParametersParser
7
7
  # @param parameters [Array<Parameter>]
8
8
  # @param check_encoding [Boolean] Raise Rack::Utils::InvalidParameterError if a value has an invalid encoding.