api_recipes 3.0.0.beta1 → 3.0.0.beta2
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 +152 -0
- 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/routes.rb +50 -0
- data/lib/api_recipes/cli.rb +96 -0
- data/lib/api_recipes/version.rb +1 -1
- metadata +8 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 50e74b1e4dce5dd7ade7b7c574ac1c936b046faadbd79802e8c2dfd2840176ca
|
|
4
|
+
data.tar.gz: 9b4e83c0f2507b5c6dd78c49a89c7e89077c96d9e322b317aee03f9e4065230c
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 3de9f3c2618a1b1e1fab1bcf769c570b0a9dff147d214103eab82f57d74b1ee02c45be04fcc9ffe2ccd5405ade03f10a5b91919584269669cf7dc9fd43875285
|
|
7
|
+
data.tar.gz: 4d8fec4b97c5b97e9dffafbed66a0052a8be63aa851f8eaffe8bbbc71a9d69a23bf5649df56f1afa31ae037756e6f516087ad908958a01f2d26f44791f5ac5b0
|
data/README.md
CHANGED
|
@@ -33,6 +33,7 @@ Coming from version 2? Read [UPGRADING.md](UPGRADING.md) first.
|
|
|
33
33
|
- [Describing an API](#describing-an-api)
|
|
34
34
|
- [Variables](#variables)
|
|
35
35
|
- [Loading the configuration](#loading-the-configuration)
|
|
36
|
+
- [Importing an OpenAPI description](#importing-an-openapi-description)
|
|
36
37
|
- [Where an API is available](#where-an-api-is-available)
|
|
37
38
|
- [Making requests](#making-requests)
|
|
38
39
|
- [Options for one chain: `with`](#options-for-one-chain-with)
|
|
@@ -388,6 +389,141 @@ Keys can be strings or symbols, but not both for the same option.
|
|
|
388
389
|
If the configuration has a problem, `configure` raises and the previous
|
|
389
390
|
configuration stays active.
|
|
390
391
|
|
|
392
|
+
## Importing an OpenAPI description
|
|
393
|
+
|
|
394
|
+
When an API publishes an OpenAPI description, the `api_recipes` command writes
|
|
395
|
+
the recipe for you:
|
|
396
|
+
|
|
397
|
+
$ api_recipes import openapi.yml --name github --output config/apis/github.yml
|
|
398
|
+
|
|
399
|
+
The description is read once, when you run the command. Your application never
|
|
400
|
+
reads it: it loads the recipe, which is a file like the ones above, and you can
|
|
401
|
+
read it, trim it and rename things in it. These operations
|
|
402
|
+
|
|
403
|
+
```
|
|
404
|
+
GET /users
|
|
405
|
+
GET /users/{username}
|
|
406
|
+
GET /users/{username}/repos
|
|
407
|
+
GET /repos/{owner}/{repo}/issues
|
|
408
|
+
POST /repos/{owner}/{repo}/issues
|
|
409
|
+
GET /repos/{owner}/{repo}/issues/{issue_number}
|
|
410
|
+
PATCH /repos/{owner}/{repo}/issues/{issue_number}
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
become this recipe:
|
|
414
|
+
|
|
415
|
+
```
|
|
416
|
+
# Generated by api_recipes import from GitHub 1.0
|
|
417
|
+
github:
|
|
418
|
+
host: api.github.com
|
|
419
|
+
endpoints:
|
|
420
|
+
users: # GET /users (users/list)
|
|
421
|
+
endpoints:
|
|
422
|
+
show: # GET /users/{username} (users/get-by-username)
|
|
423
|
+
path: "/:username"
|
|
424
|
+
repos: # GET /users/{username}/repos (repos/list-for-user)
|
|
425
|
+
path: "/:username/repos"
|
|
426
|
+
repos:
|
|
427
|
+
route: false
|
|
428
|
+
endpoints:
|
|
429
|
+
issues: # GET /repos/{owner}/{repo}/issues (issues/list-for-repo)
|
|
430
|
+
path: "/:owner/:repo/issues"
|
|
431
|
+
endpoints:
|
|
432
|
+
create: # POST /repos/{owner}/{repo}/issues (issues/create)
|
|
433
|
+
path: ''
|
|
434
|
+
verb: post
|
|
435
|
+
ok_code: 201
|
|
436
|
+
show: # GET /repos/{owner}/{repo}/issues/{issue_number} (issues/get)
|
|
437
|
+
path: "/:issue_number"
|
|
438
|
+
update: # PATCH /repos/{owner}/{repo}/issues/{issue_number} (issues/update)
|
|
439
|
+
path: "/:issue_number"
|
|
440
|
+
verb: patch
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
| Request | Call |
|
|
444
|
+
| --- | --- |
|
|
445
|
+
| `GET /users` | `github.users` |
|
|
446
|
+
| `GET /users/{username}` | `github.users.show('octocat')` |
|
|
447
|
+
| `GET /users/{username}/repos` | `github.users.repos('octocat')` |
|
|
448
|
+
| `GET /repos/{owner}/{repo}/issues` | `github.repos.issues('rails', 'rails')` |
|
|
449
|
+
| `POST /repos/{owner}/{repo}/issues` | `github.repos.issues('rails', 'rails').create(json: { title: 'Bug' })` |
|
|
450
|
+
| `GET /repos/{owner}/{repo}/issues/{issue_number}` | `github.repos.issues('rails', 'rails').show(1347)` |
|
|
451
|
+
| `PATCH /repos/{owner}/{repo}/issues/{issue_number}` | `github.repos.issues('rails', 'rails').update(1347, json: { state: 'closed' })` |
|
|
452
|
+
|
|
453
|
+
### Options
|
|
454
|
+
|
|
455
|
+
| Option | Meaning |
|
|
456
|
+
| --- | --- |
|
|
457
|
+
| `--name NAME` | the name of the API in the recipe. Default: the title of the description, in lower case with `_` |
|
|
458
|
+
| `--only GLOB` | only the paths that match; can be repeated. `*` also crosses `/`: `--only 'repos/*'` |
|
|
459
|
+
| `--except GLOB` | leaves out the paths that match; can be repeated |
|
|
460
|
+
| `--server N` | which entry of `servers` gives the address, counted from 0. Default: the first |
|
|
461
|
+
| `--output FILE` | writes the recipe in FILE, which must not exist, instead of on STDOUT |
|
|
462
|
+
|
|
463
|
+
The input is one local file, YAML or JSON, OpenAPI 3.0 or 3.1. Warnings and a
|
|
464
|
+
summary go to STDERR, so the recipe can be redirected. The command exits with 1
|
|
465
|
+
when the description cannot be imported and with 2 when the arguments are wrong.
|
|
466
|
+
|
|
467
|
+
### What is read
|
|
468
|
+
|
|
469
|
+
| From the description | In the recipe |
|
|
470
|
+
| --- | --- |
|
|
471
|
+
| the address of the server | `protocol`, `host`, `port`, `base_url` |
|
|
472
|
+
| the variables of the server | `variables`, with their defaults |
|
|
473
|
+
| the paths | the tree of endpoints |
|
|
474
|
+
| the path parameters | `:name` placeholders |
|
|
475
|
+
| the query parameters | a comment beside the endpoint, with a `*` on the required ones |
|
|
476
|
+
| the documented 2xx statuses | `ok_code`: one status, or a list. Left out when `200` is the only one or none is documented, since every 2xx is accepted by default |
|
|
477
|
+
| `security` and `securitySchemes` | `auth`: `bearer` for http bearer, OAuth 2 and OpenID Connect; `basic`; `header` or `query` for an API key |
|
|
478
|
+
| `operationId`, `deprecated` | a comment beside the endpoint |
|
|
479
|
+
|
|
480
|
+
Schemas, bodies, callbacks, webhooks, links and cookie parameters are not read:
|
|
481
|
+
the gem does not validate requests and responses against them.
|
|
482
|
+
|
|
483
|
+
### How the names are made
|
|
484
|
+
|
|
485
|
+
Each segment of a path that is not a parameter is a node, named after the
|
|
486
|
+
segment in lower case, with `camelCase` turned into `snake_case` and every other
|
|
487
|
+
character into `_`. The parameters that come before a segment travel with it;
|
|
488
|
+
those at the end of the path travel with the operation. An operation is named
|
|
489
|
+
after its verb and after how its path ends:
|
|
490
|
+
|
|
491
|
+
| Verb | The path ends with a name (`/issues`) | The path ends with a parameter (`/issues/{n}`) |
|
|
492
|
+
| --- | --- | --- |
|
|
493
|
+
| GET | the node itself | `show` |
|
|
494
|
+
| POST | `create` | `post` |
|
|
495
|
+
| PUT | `replace_all` | `replace` |
|
|
496
|
+
| PATCH | `update_all` | `update` |
|
|
497
|
+
| DELETE | `delete_all` | `delete` |
|
|
498
|
+
| others | the name of the verb | the name of the verb and `_one` |
|
|
499
|
+
|
|
500
|
+
- A node whose path has no GET only groups others: `route: false`.
|
|
501
|
+
- Two endpoints with the same name under the same node: one gets a number
|
|
502
|
+
(`show_2`), and a warning says so.
|
|
503
|
+
- A name that is an existing method, such as `with`, is written all the same,
|
|
504
|
+
with a warning: reach it with `[]`.
|
|
505
|
+
- A single resource comes out badly: `PATCH /user` becomes `user.update_all`.
|
|
506
|
+
Rename it in the file.
|
|
507
|
+
|
|
508
|
+
What the gem cannot write as a path is left out, with a warning for each path:
|
|
509
|
+
a parameter directly followed by a letter, a digit or `_` (`/files/{id}_meta`),
|
|
510
|
+
because the gem reads `:id_meta` as one name; a segment that starts with `*` and
|
|
511
|
+
a name, which the gem reads as a parameter that spans segments; and an empty
|
|
512
|
+
segment (`/a//b`), because the gem joins two slashes into one.
|
|
513
|
+
|
|
514
|
+
### What the command refuses
|
|
515
|
+
|
|
516
|
+
- Swagger 2.0: convert the description to OpenAPI 3 first.
|
|
517
|
+
- A `$ref` to another file or to an address: bundle the description into one
|
|
518
|
+
file first. References inside the file are followed.
|
|
519
|
+
- A description whose text would become code in the recipe: `<%` in a value is
|
|
520
|
+
an error that says where, and it is removed from the comments.
|
|
521
|
+
- A YAML description with binary values, with keys that are not plain text, or
|
|
522
|
+
with aliases that stand for more than ten million values.
|
|
523
|
+
|
|
524
|
+
The command reads that one file, never uses the network and runs nothing of the
|
|
525
|
+
description.
|
|
526
|
+
|
|
391
527
|
## Where an API is available
|
|
392
528
|
|
|
393
529
|
### On the `ApiRecipes` module
|
|
@@ -967,6 +1103,19 @@ route = ApiRecipes.github.definition.routes.find { |r| r.call.end_with?('.contri
|
|
|
967
1103
|
# => "github.repos(owner, repo).contributors get https://api.github.com/repos/:owner/:repo/contributors"
|
|
968
1104
|
```
|
|
969
1105
|
|
|
1106
|
+
The command line gives the same list for the recipes in one or more files,
|
|
1107
|
+
which is handy after an import:
|
|
1108
|
+
|
|
1109
|
+
```
|
|
1110
|
+
$ api_recipes routes config/apis/github.yml
|
|
1111
|
+
github.users GET https://api.github.com/users
|
|
1112
|
+
github.users.show(username) GET https://api.github.com/users/:username
|
|
1113
|
+
github.repos.issues(owner, repo).create POST https://api.github.com/repos/:owner/:repo/issues
|
|
1114
|
+
```
|
|
1115
|
+
|
|
1116
|
+
A file that contains ERB is read only with `--erb`, because that runs the code
|
|
1117
|
+
in it.
|
|
1118
|
+
|
|
970
1119
|
## Recipes
|
|
971
1120
|
|
|
972
1121
|
### Rails setup
|
|
@@ -1117,6 +1266,9 @@ What ApiRecipes does:
|
|
|
1117
1266
|
not sent again if the chain comes back.
|
|
1118
1267
|
- **Before sending**, the address that http.rb will contact is checked against
|
|
1119
1268
|
the origin that was validated.
|
|
1269
|
+
- **`api_recipes import`** reads one local file, follows only the references
|
|
1270
|
+
inside it, never uses the network and runs nothing of the description. Text of
|
|
1271
|
+
the description cannot add keys to the recipe and cannot become ERB in it.
|
|
1120
1272
|
- **Logs, errors and `inspect`.** A log line and an error message of the gem
|
|
1121
1273
|
never contain a credential, a header value, a body or a query string. Neither
|
|
1122
1274
|
does the `inspect` or the `pp` of an API, an endpoint, a response, a
|
|
@@ -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
|