api_recipes 3.0.0.beta1 → 3.0.0.beta3
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/README.md +667 -78
- data/UPGRADING.md +67 -22
- data/lib/api_recipes/api.rb +14 -10
- data/lib/api_recipes/cli/import/document.rb +234 -0
- data/lib/api_recipes/cli/import/security.rb +138 -0
- data/lib/api_recipes/cli/import/server.rb +166 -0
- data/lib/api_recipes/cli/import/tree.rb +288 -0
- data/lib/api_recipes/cli/import/writer.rb +127 -0
- data/lib/api_recipes/cli/import.rb +129 -0
- data/lib/api_recipes/cli/recipes/git.rb +197 -0
- data/lib/api_recipes/cli/recipes/lock_file.rb +34 -0
- data/lib/api_recipes/cli/recipes/summary.rb +226 -0
- data/lib/api_recipes/cli/recipes.rb +287 -0
- data/lib/api_recipes/cli/routes.rb +55 -0
- data/lib/api_recipes/cli/upgrade.rb +10 -2
- data/lib/api_recipes/cli.rb +163 -1
- data/lib/api_recipes/configuration.rb +50 -13
- data/lib/api_recipes/endpoint.rb +9 -3
- data/lib/api_recipes/errors.rb +2 -1
- data/lib/api_recipes/internals/compiler.rb +146 -33
- data/lib/api_recipes/internals/context.rb +52 -14
- data/lib/api_recipes/internals/declaration.rb +18 -18
- data/lib/api_recipes/internals/definition.rb +75 -22
- data/lib/api_recipes/internals/level.rb +54 -43
- data/lib/api_recipes/internals/path_template.rb +29 -4
- data/lib/api_recipes/internals/plain_yaml.rb +133 -0
- data/lib/api_recipes/internals/recipe.rb +297 -0
- data/lib/api_recipes/internals/recipe_lock.rb +115 -0
- data/lib/api_recipes/internals/registry.rb +61 -15
- data/lib/api_recipes/internals/request.rb +26 -9
- data/lib/api_recipes/internals/template.rb +17 -5
- data/lib/api_recipes/version.rb +1 -1
- data/lib/api_recipes.rb +7 -3
- metadata +15 -1
data/UPGRADING.md
CHANGED
|
@@ -5,7 +5,7 @@ Version 3.0 keeps the way you use the gem: the YAML files, `ApiRecipes.configure
|
|
|
5
5
|
`ApiRecipes.github.users.show('octocat').run` work as before. A YAML file that
|
|
6
6
|
is valid for 2.x needs no change, apart from what part 2 describes: options and
|
|
7
7
|
values that 2.x accepted without checking them, a placeholder in `base_url` and a
|
|
8
|
-
`{word}` in a header value. What changes is how the gem behaves around them: it
|
|
8
|
+
`{word}` in a header value or in a path. What changes is how the gem behaves around them: it
|
|
9
9
|
checks more, it refuses more, and a few results are different.
|
|
10
10
|
|
|
11
11
|
This guide has six parts:
|
|
@@ -92,10 +92,15 @@ configuration in place. Four things are worth knowing:
|
|
|
92
92
|
`variables: { template: { default: '{id}' } }` with the header value
|
|
93
93
|
`'{template}'`. Braces around anything else, such as a JSON value, are sent
|
|
94
94
|
as they are.
|
|
95
|
+
- A word in braces in the `path` of an endpoint, such as `/items/{id}`, is now a
|
|
96
|
+
variable too, and one that is not declared is an error. In 2.x the braces were
|
|
97
|
+
sent as text. If you meant a value that changes at every call, write a
|
|
98
|
+
placeholder, `/items/:id`. To keep the braces as text, write `\{id}`.
|
|
95
99
|
- A file that is missing, empty, not valid YAML or not valid UTF-8 raises
|
|
96
100
|
`ApiRecipes::RecipeFileError`, which names the file. Files are read with
|
|
97
101
|
`YAML.safe_load`: plain values, symbols and aliases are accepted, and nothing
|
|
98
|
-
else. A file called `something.recipe.yml` is refused
|
|
102
|
+
else. A file called `something.recipe.yml` is refused: it is a portable
|
|
103
|
+
recipe, and goes in `recipes_paths`.
|
|
99
104
|
|
|
100
105
|
### A class with its own destination needs its own credential
|
|
101
106
|
|
|
@@ -111,17 +116,42 @@ api 'github': the credential is bound to "https://api.github.com" but the reques
|
|
|
111
116
|
or set it to nil to send none
|
|
112
117
|
```
|
|
113
118
|
|
|
114
|
-
|
|
119
|
+
Give the credential where the class declares the API:
|
|
115
120
|
|
|
116
121
|
```ruby
|
|
117
122
|
class EnterpriseClient
|
|
118
123
|
include ApiRecipes
|
|
119
|
-
api :github, host: 'ent.example.test'
|
|
124
|
+
api :github, host: 'ent.example.test', authorization: "Bearer #{ENV.fetch('ENTERPRISE_TOKEN')}"
|
|
125
|
+
end
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Credentials are given when the application starts
|
|
129
|
+
|
|
130
|
+
In 2.x the usual line was `ApiRecipes.github.authorization = '...'`, and code
|
|
131
|
+
that served several users assigned it before each call. What `ApiRecipes.github`
|
|
132
|
+
and a class use is shared by every thread of the process, so a request could
|
|
133
|
+
leave with the token of another user. Now `authorization=`, `basic_auth=` and
|
|
134
|
+
`variables=` raise `ApiRecipes::Error` on `ApiRecipes.github` and on a class,
|
|
135
|
+
and the message says where the value goes:
|
|
136
|
+
|
|
137
|
+
```ruby
|
|
138
|
+
# the whole application: once, in configure
|
|
139
|
+
ApiRecipes.configure do |config|
|
|
140
|
+
config.values = { github: { authorization: "Bearer #{ENV.fetch('GITHUB_TOKEN')}" } }
|
|
120
141
|
end
|
|
121
142
|
|
|
122
|
-
|
|
143
|
+
# one class: where it declares the API
|
|
144
|
+
class AdminClient
|
|
145
|
+
include ApiRecipes
|
|
146
|
+
api :github, authorization: "Bearer #{ENV.fetch('ADMIN_TOKEN')}"
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# one user, one request: the chain, or an object of its own
|
|
150
|
+
ApiRecipes.github.with(authorization: "Bearer #{user.token}").users.run
|
|
123
151
|
```
|
|
124
152
|
|
|
153
|
+
The writers still work on an object, as in `client.github.authorization = ...`.
|
|
154
|
+
|
|
125
155
|
### `nil` or an empty path parameter
|
|
126
156
|
|
|
127
157
|
`show(nil)` and `show('')` built the URL of the parent. They now raise
|
|
@@ -236,13 +266,13 @@ The warnings name the endpoint and never the value. `config.upgrade_warnings = f
|
|
|
236
266
|
turns them off. Two more effects: a `:` in a value no longer breaks nested
|
|
237
267
|
endpoints, and a suffix after a placeholder, as in `/:name.json`, is kept.
|
|
238
268
|
|
|
239
|
-
### Credentials on
|
|
269
|
+
### Credentials on an instance take effect
|
|
240
270
|
|
|
241
|
-
In 2.x `
|
|
242
|
-
returned a new object. Now it is
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
271
|
+
In 2.x `client.github.authorization = '...'` was lost, because every call
|
|
272
|
+
returned a new object. Now it is kept for that object. If your code assigned
|
|
273
|
+
one and relied on it having no effect, it now sends a credential. The nearest
|
|
274
|
+
level wins: the chain (`with`), the object, the class that declares the API,
|
|
275
|
+
then the whole application. A credential given as `nil` means "send none".
|
|
246
276
|
|
|
247
277
|
### Logging
|
|
248
278
|
|
|
@@ -278,11 +308,15 @@ rescue ApiRecipes::ResponseCodeNotAsExpected => e
|
|
|
278
308
|
end
|
|
279
309
|
```
|
|
280
310
|
|
|
281
|
-
###
|
|
311
|
+
### An endpoint looks for its options up the tree
|
|
282
312
|
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
313
|
+
In 2.x an endpoint took `timeout`, `on_bad_code` and `mime_type` from the API,
|
|
314
|
+
whatever the endpoint that contained it said, and one written without options
|
|
315
|
+
did not take `verify_with` from its parent. Now an endpoint that does not set
|
|
316
|
+
one of these four options looks for it in the endpoints that contain it, from
|
|
317
|
+
the nearest, then in the API, and takes the first value it finds. Look at the
|
|
318
|
+
endpoints that set one of them and also contain other endpoints: those now
|
|
319
|
+
find it there. `ok_code` is read only on its endpoint.
|
|
286
320
|
|
|
287
321
|
### `apis_configs` after the files
|
|
288
322
|
|
|
@@ -385,19 +419,30 @@ You can adopt these when you are ready. The [README](README.md) describes each o
|
|
|
385
419
|
`ApiRecipes.github[:users][:show, 'octocat']`, whatever the name.
|
|
386
420
|
- **`with`**: options for one chain or one request, without changing anything
|
|
387
421
|
stored: `ApiRecipes.github.with(host: 'github.example.com')`.
|
|
388
|
-
- **Credentials along a chain**: the chain, the object, the class
|
|
389
|
-
|
|
390
|
-
- **`variables`**: `{name}` placeholders in `host`, `base_url
|
|
391
|
-
|
|
422
|
+
- **Credentials along a chain**: the chain, the object, the class that declares
|
|
423
|
+
the API, then the whole application. A credential is bound to its origin.
|
|
424
|
+
- **`variables`**: `{name}` placeholders in `host`, `base_url`, the `path` of an
|
|
425
|
+
endpoint and the values of `default_headers` and `default_params`, with
|
|
426
|
+
values given at any of those levels.
|
|
427
|
+
- **`default_params`**: query parameters sent with every request, as
|
|
428
|
+
`default_headers` does for headers. Both can be written on an endpoint, for
|
|
429
|
+
that endpoint and the ones below it.
|
|
430
|
+
- **`resource`**: `resource: true` on an endpoint adds `show`, `create`,
|
|
431
|
+
`update`, `replace` and `delete` under it.
|
|
392
432
|
- **`auth`**: says where the credential goes: the `Authorization` header, a header
|
|
393
433
|
of your choice or a query parameter.
|
|
394
434
|
- **`ok_code`** accepts a list of statuses, and `response.success?` tells whether a
|
|
395
435
|
response passed the rule of its endpoint.
|
|
396
436
|
- **`definition`**, `routes` and a safe `inspect` on APIs and endpoints.
|
|
397
437
|
- **Validated configuration**, with every problem reported at once.
|
|
398
|
-
- **`config.
|
|
399
|
-
|
|
400
|
-
|
|
438
|
+
- **`config.values`**, which gives each API its credential and the values of
|
|
439
|
+
its variables for the whole application, **`config.upgrade_warnings`** and
|
|
440
|
+
the logging options described above.
|
|
441
|
+
- **The `api_recipes` command**, with `upgrade`, `import`, `routes`, `install`,
|
|
442
|
+
`update` and `check`.
|
|
443
|
+
- **Portable recipes**: recipes written by others, installed with
|
|
444
|
+
`api_recipes install` and loaded with `config.recipes_paths`. See
|
|
445
|
+
[Portable recipes](README.md#portable-recipes) in the README.
|
|
401
446
|
|
|
402
447
|
## 6. Security
|
|
403
448
|
|
data/lib/api_recipes/api.rb
CHANGED
|
@@ -31,11 +31,15 @@ module ApiRecipes
|
|
|
31
31
|
credential && credential.kind == :authorization ? credential.value : nil
|
|
32
32
|
end
|
|
33
33
|
|
|
34
|
-
# Sets the credential of
|
|
35
|
-
# writers
|
|
34
|
+
# Sets the credential of an object; nil means "send none". Only an object
|
|
35
|
+
# has writers: what the whole application or a class uses is shared by
|
|
36
|
+
# every thread, so it is given where the application starts, to
|
|
37
|
+
# ApiRecipes.configure (config.values) or to `api` in the class. The
|
|
38
|
+
# writers also refuse an api returned by with: its options belong to its
|
|
39
|
+
# chain.
|
|
36
40
|
def authorization=(value)
|
|
37
|
-
|
|
38
|
-
raise Error,
|
|
41
|
+
if Module === @context.owner || !@context.overrides.empty?
|
|
42
|
+
raise Error, Internals::LevelSet.refusal(:authorization, @context.owner, @context.definition.name, @context.overrides.empty?)
|
|
39
43
|
end
|
|
40
44
|
|
|
41
45
|
credential = Internals::Credential.from(:authorization, value)
|
|
@@ -48,8 +52,8 @@ module ApiRecipes
|
|
|
48
52
|
end
|
|
49
53
|
|
|
50
54
|
def basic_auth=(value)
|
|
51
|
-
|
|
52
|
-
raise Error,
|
|
55
|
+
if Module === @context.owner || !@context.overrides.empty?
|
|
56
|
+
raise Error, Internals::LevelSet.refusal(:basic_auth, @context.owner, @context.definition.name, @context.overrides.empty?)
|
|
53
57
|
end
|
|
54
58
|
|
|
55
59
|
credential = Internals::Credential.from(:basic_auth, value)
|
|
@@ -58,14 +62,14 @@ module ApiRecipes
|
|
|
58
62
|
|
|
59
63
|
# The variable values of the caller's level.
|
|
60
64
|
def variables
|
|
61
|
-
level =
|
|
65
|
+
level = @context.own_level
|
|
62
66
|
(level && level.variables) || {}
|
|
63
67
|
end
|
|
64
68
|
|
|
65
|
-
# Sets the variable values of
|
|
69
|
+
# Sets the variable values of an object; nil removes them. See authorization=.
|
|
66
70
|
def variables=(values)
|
|
67
|
-
|
|
68
|
-
raise Error,
|
|
71
|
+
if Module === @context.owner || !@context.overrides.empty?
|
|
72
|
+
raise Error, Internals::LevelSet.refusal(:variables, @context.owner, @context.definition.name, @context.overrides.empty?)
|
|
69
73
|
end
|
|
70
74
|
|
|
71
75
|
values = Internals::Registry.variable_values(values)
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'date'
|
|
4
|
+
require 'json'
|
|
5
|
+
require 'set'
|
|
6
|
+
require 'yaml'
|
|
7
|
+
|
|
8
|
+
module ApiRecipes
|
|
9
|
+
module CLI
|
|
10
|
+
class Import
|
|
11
|
+
# An OpenAPI 3.0 or 3.1 description read from one local file, YAML or
|
|
12
|
+
# JSON. Only plain data is accepted. A `$ref` is followed when the
|
|
13
|
+
# importer asks for it and only inside the same file: the schemas, which
|
|
14
|
+
# often refer to themselves, are never walked.
|
|
15
|
+
class Document
|
|
16
|
+
SUPPORTED = /\A3\.[01](\.|\z)/
|
|
17
|
+
NOT_YAML = 'the description is not valid YAML'
|
|
18
|
+
MAX_REFS = 64
|
|
19
|
+
READ_PROBLEMS = { Errno::ENOENT => 'no such file', Errno::EISDIR => 'is a directory',
|
|
20
|
+
Errno::EACCES => 'permission denied' }.freeze
|
|
21
|
+
|
|
22
|
+
class << self
|
|
23
|
+
def load(path)
|
|
24
|
+
text = File.read(path, encoding: 'UTF-8')
|
|
25
|
+
raise Error, "#{path}: is not valid UTF-8" unless text.valid_encoding?
|
|
26
|
+
|
|
27
|
+
parse(text)
|
|
28
|
+
rescue SystemCallError => e
|
|
29
|
+
raise Error, "#{path}: #{READ_PROBLEMS.fetch(e.class) { "cannot be read (#{e.class.name.split('::').last})" }}"
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def parse(text)
|
|
33
|
+
data = text.lstrip.start_with?('{') ? parse_json(text) : parse_yaml(text)
|
|
34
|
+
raise Error, 'the description is empty' if data.nil?
|
|
35
|
+
raise Error, 'the description must be a mapping' unless data.is_a?(Hash)
|
|
36
|
+
|
|
37
|
+
check_version(data)
|
|
38
|
+
new(data)
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
private
|
|
42
|
+
|
|
43
|
+
# YAML written in flow style starts with a brace too: what is not
|
|
44
|
+
# JSON is read as YAML.
|
|
45
|
+
def parse_json(text)
|
|
46
|
+
JSON.parse(text)
|
|
47
|
+
rescue JSON::ParserError
|
|
48
|
+
begin
|
|
49
|
+
parse_yaml(text)
|
|
50
|
+
rescue Error => e
|
|
51
|
+
raise e unless e.message.start_with?(NOT_YAML)
|
|
52
|
+
|
|
53
|
+
raise Error, 'the description is not valid JSON'
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# Dates are the only values beyond plain YAML that a description
|
|
58
|
+
# written by hand contains. Aliases are accepted, since tools write
|
|
59
|
+
# them for repeated parts: an alias is the same object, not a copy,
|
|
60
|
+
# and the importer never expands or prints a mapping or a list. The
|
|
61
|
+
# shape is checked first, on the events of the parser, because Ruby
|
|
62
|
+
# computes the hash of every key: a key that is an alias of a large
|
|
63
|
+
# structure would keep it busy for ever.
|
|
64
|
+
def parse_yaml(text)
|
|
65
|
+
Psych::Parser.new(Shape.new).parse(text)
|
|
66
|
+
YAML.safe_load(text, permitted_classes: [Date, Time], aliases: true)
|
|
67
|
+
rescue Psych::BadAlias
|
|
68
|
+
raise Error, 'the description uses a YAML alias that is not defined'
|
|
69
|
+
rescue Psych::DisallowedClass
|
|
70
|
+
raise Error, 'the description contains something that is not plain data'
|
|
71
|
+
rescue Psych::SyntaxError => e
|
|
72
|
+
raise Error, "#{NOT_YAML} (line #{e.line})"
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def check_version(data)
|
|
76
|
+
if data.key?('swagger')
|
|
77
|
+
raise Error, "Swagger #{Import.text(data['swagger']).to_s[0, 10].gsub(/[^\d.]/, '')} is not supported: " \
|
|
78
|
+
'convert it to OpenAPI 3 first'
|
|
79
|
+
end
|
|
80
|
+
version = data['openapi']
|
|
81
|
+
return if (version.is_a?(String) || version.is_a?(Numeric)) && SUPPORTED.match?(version.to_s)
|
|
82
|
+
|
|
83
|
+
raise Error, 'only OpenAPI 3.0 or 3.1 is supported: the description must say which one in its openapi key'
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Refuses, while the text is parsed and before any object is built:
|
|
88
|
+
# a key that is not plain text, a nesting that is too deep, binary
|
|
89
|
+
# values, and aliases that together stand for more values than a
|
|
90
|
+
# description can have. Every anchor is given the number of values under
|
|
91
|
+
# it, aliases included, so the count is exact without expanding anything.
|
|
92
|
+
class Shape < Psych::Handler
|
|
93
|
+
MAX_DEPTH = 200
|
|
94
|
+
MAX_ALIASED = 10_000_000
|
|
95
|
+
BINARY = 'tag:yaml.org,2002:binary'
|
|
96
|
+
|
|
97
|
+
# One mapping or list that is being read.
|
|
98
|
+
Open = Struct.new(:kind, :children, :anchor, :size)
|
|
99
|
+
|
|
100
|
+
def initialize
|
|
101
|
+
super
|
|
102
|
+
@open = []
|
|
103
|
+
@sizes = {}
|
|
104
|
+
@aliased = 0
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def scalar(_value, anchor, tag, *)
|
|
108
|
+
if tag == BINARY
|
|
109
|
+
raise Error, 'the description contains binary data (!!binary): only text is read'
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
child(false, 1)
|
|
113
|
+
@sizes[anchor] = 1 if anchor
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
# An alias of something still open is a structure that contains itself: it counts as one value.
|
|
117
|
+
def alias(anchor)
|
|
118
|
+
size = @sizes.fetch(anchor, 1)
|
|
119
|
+
@aliased += size
|
|
120
|
+
if @aliased > MAX_ALIASED
|
|
121
|
+
raise Error, 'the aliases of the description stand for more than ten million values: ' \
|
|
122
|
+
'this is not a description of an api'
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
child(true, size)
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def start_mapping(anchor, *) = start(:mapping, anchor)
|
|
129
|
+
|
|
130
|
+
def start_sequence(anchor, *) = start(:sequence, anchor)
|
|
131
|
+
|
|
132
|
+
def end_mapping = finish
|
|
133
|
+
|
|
134
|
+
def end_sequence = finish
|
|
135
|
+
|
|
136
|
+
private
|
|
137
|
+
|
|
138
|
+
def start(kind, anchor)
|
|
139
|
+
child(true, 0)
|
|
140
|
+
@open << Open.new(kind, 0, anchor, 1)
|
|
141
|
+
raise Error, 'the description is nested too deeply' if @open.size > MAX_DEPTH
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
def finish
|
|
145
|
+
done = @open.pop
|
|
146
|
+
@sizes[done.anchor] = done.size if done.anchor
|
|
147
|
+
@open.last.size += done.size if @open.last
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
# In a mapping the children come as key, value, key, value.
|
|
151
|
+
def child(composite, size)
|
|
152
|
+
parent = @open.last
|
|
153
|
+
return unless parent
|
|
154
|
+
|
|
155
|
+
parent.size += size
|
|
156
|
+
return unless parent.kind == :mapping
|
|
157
|
+
|
|
158
|
+
parent.children += 1
|
|
159
|
+
return unless parent.children.odd? && composite
|
|
160
|
+
|
|
161
|
+
raise Error, 'a key of the description is an alias, a mapping or a list: keys must be plain text'
|
|
162
|
+
end
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
attr_reader :root
|
|
166
|
+
|
|
167
|
+
def initialize(root)
|
|
168
|
+
@root = root
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def title = text_of('title')
|
|
172
|
+
|
|
173
|
+
def version = text_of('version')
|
|
174
|
+
|
|
175
|
+
# node itself, or what its `$ref` points to, through as many `$ref` as
|
|
176
|
+
# it takes. where is the place of node in the description, for messages.
|
|
177
|
+
def resolve(node, where)
|
|
178
|
+
seen = nil
|
|
179
|
+
while node.is_a?(Hash) && node.key?('$ref')
|
|
180
|
+
ref = node['$ref']
|
|
181
|
+
raise Error, "#{where}: $ref must be a string" unless ref.is_a?(String)
|
|
182
|
+
unless ref == '#' || ref.start_with?('#/')
|
|
183
|
+
raise Error, "#{where}: $ref #{Import.shown(ref)} points to another file: " \
|
|
184
|
+
'bundle the description into one file first'
|
|
185
|
+
end
|
|
186
|
+
raise Error, "#{where}: circular $ref #{Import.shown(ref)}" if seen&.include?(ref)
|
|
187
|
+
raise Error, "#{where}: more than #{MAX_REFS} $ref in a chain" if seen && seen.size >= MAX_REFS
|
|
188
|
+
|
|
189
|
+
(seen ||= Set.new) << ref
|
|
190
|
+
node = fetch(ref, where)
|
|
191
|
+
end
|
|
192
|
+
node
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
def inspect = "#<#{self.class.name} #{Import.shown(title)}>"
|
|
196
|
+
|
|
197
|
+
private
|
|
198
|
+
|
|
199
|
+
def text_of(key)
|
|
200
|
+
info = @root['info']
|
|
201
|
+
Import.text(info.is_a?(Hash) ? info[key] : nil)
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
# The pieces of a JSON pointer: the %XX of the URL fragment first, then
|
|
205
|
+
# ~1 and ~0.
|
|
206
|
+
def fetch(ref, where)
|
|
207
|
+
pieces = ref.delete_prefix('#').delete_prefix('/').split('/', -1)
|
|
208
|
+
pieces.reduce(@root) do |node, piece|
|
|
209
|
+
piece = piece.gsub(/%\h\h/) { |escape| escape[1, 2].hex.chr }.force_encoding(Encoding::UTF_8)
|
|
210
|
+
child = child_of(node, piece.gsub('~1', '/').gsub('~0', '~'))
|
|
211
|
+
raise Error, "#{where}: $ref #{Import.shown(ref)} does not exist" if child.equal?(MISSING)
|
|
212
|
+
|
|
213
|
+
child
|
|
214
|
+
end
|
|
215
|
+
end
|
|
216
|
+
|
|
217
|
+
MISSING = Object.new.freeze
|
|
218
|
+
private_constant :MISSING
|
|
219
|
+
|
|
220
|
+
def child_of(node, piece)
|
|
221
|
+
case node
|
|
222
|
+
when Hash
|
|
223
|
+
key = node.key?(piece) ? piece : node.each_key.find { |candidate| candidate.to_s == piece }
|
|
224
|
+
key.nil? ? MISSING : node[key]
|
|
225
|
+
when Array
|
|
226
|
+
piece.match?(/\A\d+\z/) && piece.to_i < node.size ? node[piece.to_i] : MISSING
|
|
227
|
+
else
|
|
228
|
+
MISSING
|
|
229
|
+
end
|
|
230
|
+
end
|
|
231
|
+
end
|
|
232
|
+
end
|
|
233
|
+
end
|
|
234
|
+
end
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ApiRecipes
|
|
4
|
+
module CLI
|
|
5
|
+
class Import
|
|
6
|
+
# The `auth` option of an api, from the global `security` of the
|
|
7
|
+
# description and its `securitySchemes`.
|
|
8
|
+
class Security
|
|
9
|
+
Result = Data.define(:auth, :warnings)
|
|
10
|
+
|
|
11
|
+
def self.read(document)
|
|
12
|
+
new(document).read
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def initialize(document)
|
|
16
|
+
@document = document
|
|
17
|
+
@warnings = []
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def read
|
|
21
|
+
components = @document.root['components']
|
|
22
|
+
schemes = components.is_a?(Hash) && components['securitySchemes'].is_a?(Hash) ? components['securitySchemes'] : {}
|
|
23
|
+
global = @document.root['security']
|
|
24
|
+
# A global security that is an empty list says that none is needed.
|
|
25
|
+
auth = if global.is_a?(Array)
|
|
26
|
+
from_requirements(global, schemes)
|
|
27
|
+
elsif schemes.size == 1
|
|
28
|
+
auth_of(schemes.keys.first, schemes)
|
|
29
|
+
else
|
|
30
|
+
unless schemes.empty?
|
|
31
|
+
@warnings << "the description has #{schemes.size} security schemes and no global security: " \
|
|
32
|
+
'no auth was written'
|
|
33
|
+
end
|
|
34
|
+
nil
|
|
35
|
+
end
|
|
36
|
+
count_own_security(global)
|
|
37
|
+
Result.new(auth: auth, warnings: @warnings.uniq)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
private
|
|
41
|
+
|
|
42
|
+
# The first alternative whose scheme can be written.
|
|
43
|
+
def from_requirements(requirements, schemes)
|
|
44
|
+
requirements.each do |requirement|
|
|
45
|
+
next unless requirement.is_a?(Hash) && !requirement.empty?
|
|
46
|
+
|
|
47
|
+
name = requirement.keys.first
|
|
48
|
+
auth = auth_of(name, schemes)
|
|
49
|
+
next unless auth
|
|
50
|
+
|
|
51
|
+
if requirement.size > 1
|
|
52
|
+
@warnings << "the security requires several schemes together (#{requirement.keys.map { |key| Import.shown(key) }.join(', ')}): " \
|
|
53
|
+
"only #{Import.shown(name)} was written"
|
|
54
|
+
end
|
|
55
|
+
return auth
|
|
56
|
+
end
|
|
57
|
+
nil
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def auth_of(name, schemes)
|
|
61
|
+
unless schemes.key?(name)
|
|
62
|
+
@warnings << "the security scheme #{Import.shown(name)} is not defined: no auth was written for it"
|
|
63
|
+
return nil
|
|
64
|
+
end
|
|
65
|
+
scheme = @document.resolve(schemes[name], "components.securitySchemes.#{Import.shown(name)}")
|
|
66
|
+
unless scheme.is_a?(Hash)
|
|
67
|
+
@warnings << "the security scheme #{Import.shown(name)} is not a mapping: no auth was written for it"
|
|
68
|
+
return nil
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
case scheme['type']
|
|
72
|
+
when 'http' then http(scheme)
|
|
73
|
+
when 'oauth2', 'openIdConnect' then { 'type' => 'bearer' }
|
|
74
|
+
when 'apiKey' then api_key(scheme)
|
|
75
|
+
else unsupported("the security scheme type #{Import.shown(scheme['type'])}")
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def http(scheme)
|
|
80
|
+
case Import.text(scheme['scheme']).to_s.downcase
|
|
81
|
+
when 'bearer' then { 'type' => 'bearer' }
|
|
82
|
+
when 'basic' then { 'type' => 'basic' }
|
|
83
|
+
else unsupported("the http scheme #{Import.shown(scheme['scheme'])}")
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def api_key(scheme)
|
|
88
|
+
return unsupported('an apiKey in a cookie') if scheme['in'] == 'cookie'
|
|
89
|
+
return unsupported("an apiKey in #{Import.shown(scheme['in'])}") unless %w[header query].include?(scheme['in'])
|
|
90
|
+
return unsupported('an apiKey without a name') unless scheme['name'].is_a?(String) && !scheme['name'].empty?
|
|
91
|
+
|
|
92
|
+
{ 'type' => scheme['in'], 'name' => scheme['name'] }
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
# A path that cannot be read is not counted here: the tree reports it,
|
|
96
|
+
# unless the filters leave it out.
|
|
97
|
+
def path_item(path, item)
|
|
98
|
+
@document.resolve(item, "paths.#{Import.shown(path)}")
|
|
99
|
+
rescue Error
|
|
100
|
+
nil
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# The scheme names of a list of requirements: what two of them are
|
|
104
|
+
# compared by, without walking the whole structure.
|
|
105
|
+
def names_of(requirements)
|
|
106
|
+
return nil unless requirements.is_a?(Array)
|
|
107
|
+
|
|
108
|
+
requirements.map { |requirement| requirement.is_a?(Hash) ? requirement.keys.map { |key| Import.text(key) } : nil }
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def unsupported(what)
|
|
112
|
+
@warnings << "#{what} is not supported: no auth was written for it"
|
|
113
|
+
nil
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
def count_own_security(global)
|
|
117
|
+
paths = @document.root['paths']
|
|
118
|
+
return unless paths.is_a?(Hash)
|
|
119
|
+
|
|
120
|
+
chosen = names_of(global)
|
|
121
|
+
count = paths.sum do |path, item|
|
|
122
|
+
item = path_item(path, item)
|
|
123
|
+
next 0 unless item.is_a?(Hash)
|
|
124
|
+
|
|
125
|
+
Tree::METHODS.count do |method|
|
|
126
|
+
operation = item[method]
|
|
127
|
+
operation.is_a?(Hash) && operation.key?('security') && names_of(operation['security']) != chosen
|
|
128
|
+
end
|
|
129
|
+
end
|
|
130
|
+
return if count.zero?
|
|
131
|
+
|
|
132
|
+
@warnings << "#{count == 1 ? '1 operation declares its' : "#{count} operations declare their"} own security: " \
|
|
133
|
+
'the recipe has one auth for the whole api'
|
|
134
|
+
end
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
end
|
|
138
|
+
end
|