api_recipes 3.0.0.beta5 → 3.0.0.beta6

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 57bcc9de8b80033015cc0a780f9d59a9d4eb4a31206d47d142302b81d039ff01
4
- data.tar.gz: b03292e718ae4ad4a967270aa6eda834ce67221bb972a7afa9936bfcfed57a0e
3
+ metadata.gz: cd978dd075770c8701ae9cb41204c649390016b2e697feb1a01e7b058c400673
4
+ data.tar.gz: a8513c2f62b2089031cfbe93831e36aa757a32165c7cd0cb1bd2efb8add89144
5
5
  SHA512:
6
- metadata.gz: 93456b96e48047dea08bf1703a80144a38323278a1ab27add7e0dd7d2d00500b1a25fcb5e09707e398d48295b8ed92e41ab42712ad78cf72cd9f120f50f95999
7
- data.tar.gz: 97c8c52a08d74b1edb22ca0314ef66ea746dfe7355275f3ca49d152278a2b23d0674247f39e6acd0055092c2990cf10ed65868528658b7bd813fe43b7ea54d7a
6
+ metadata.gz: ebffee15a5f424293845ebe0104c7127fc02c9e5b946fc6ece9b668e8b799c2606163c8f6b81cef185b43714586fb81b9a44c0a8075ed63d81452332383d78b9
7
+ data.tar.gz: 76cbe576de29f0e141776addeb315ea16ab08a691672a9f4fb72e1c80a3181b3cb32fb98bab8fbf2be062160c5d560c97d78d56efd459c26f4e7931d48c77e2c
data/README.md CHANGED
@@ -220,7 +220,8 @@ stay in the path is written `\:`.
220
220
 
221
221
  A `{name}` in a path is a [variable](#variables): a value given once, to a
222
222
  chain, an object, a class or the whole application, where a `:name` is an
223
- argument of each call.
223
+ argument of each call. A `{*name}` is the variable form of `*name`: its value
224
+ can be several segments.
224
225
 
225
226
  ### Endpoints that only group others
226
227
 
@@ -294,7 +295,8 @@ ApiRecipes.billing.invoices.show(42).url.to_s
294
295
 
295
296
  `host` is a plain host name: no scheme, port, path or spaces. Use `protocol` and
296
297
  `port` for those. A `base_url` cannot contain a `:name` or `*name` placeholder;
297
- for a value that changes, use a [variable](#variables).
298
+ for a value that changes, use a [variable](#variables), and `{*name}` for a
299
+ value of several segments, such as a prefix.
298
300
 
299
301
  All options are listed in the [options reference](#options-reference).
300
302
 
@@ -451,7 +453,8 @@ Sandbox.sandbox.with(variables: { tenant: 'acme' }).ping.url.to_s
451
453
  ```
452
454
 
453
455
  `config.values` holds, for each API, its `variables` and its credential
454
- (`authorization` or `basic_auth`, see [Authorization](#authorization)). A later
456
+ (`authorization` or `basic_auth`, see [Authorization](#authorization)), and with
457
+ the credential the other origins it may go to (`credential_origins`). A later
455
458
  `configure` that assigns `config.values` replaces them all; one that does not
456
459
  keeps them.
457
460
 
@@ -522,11 +525,43 @@ an option as it is written. What decides the shape of the tree is read when
522
525
  the configuration is loaded and takes no variable: `endpoints`, `resource`,
523
526
  `route`, the names, `verify_with` and `auth`.
524
527
 
528
+ A variable written with a star, `{*name}`, in a `base_url` or in a `path`
529
+ takes a value of several segments, as a `*name` placeholder does: the value is
530
+ split on `/`, each segment is encoded and the slashes stay. It lets an
531
+ application move an API under a prefix:
532
+
533
+ ```yaml
534
+ rabbitmq:
535
+ variables:
536
+ api_path:
537
+ default: api
538
+ protocol: http
539
+ host: localhost
540
+ port: 15672
541
+ base_url: '{*api_path}'
542
+ endpoints:
543
+ overview:
544
+ ```
545
+
546
+ ```ruby
547
+ ApiRecipes.rabbitmq.overview.url.to_s
548
+ # => "http://localhost:15672/api/overview"
549
+
550
+ ApiRecipes.rabbitmq.with(variables: { api_path: 'rabbitmq/api' }).overview.url.to_s
551
+ # => "http://localhost:15672/rabbitmq/api/overview"
552
+ ```
553
+
554
+ No segment of the value can be empty, `.` or `..`, so the value never climbs
555
+ out of the path: `'a/../b'`, `'/a'` and `'a//b'` raise
556
+ `ApiRecipes::InvalidVariable`. In a header or a parameter `{*name}` is text,
557
+ a `host` refuses it, and `\{*name}` is text in a `path` and in a `base_url`.
558
+ A portable recipe that uses `{*name}` declares `recipe.format: 2`.
559
+
525
560
  The value of a variable is a String, a Symbol or a number, and is kept as
526
561
  text. A value is checked for the place where it ends up. In a `host` it can contain
527
562
  only letters, digits, dots, hyphens and underscores. In a `base_url` and in a
528
563
  `path` it is encoded like a path parameter, and it cannot be empty, `.` or
529
- `..`. In a header it cannot contain a line break or another control character.
564
+ `..`; in a `{*name}` it is encoded like the value of a `*name` placeholder. In a header it cannot contain a line break or another control character.
530
565
  In a parameter it is encoded like every value of a query string. Anything else
531
566
  raises `ApiRecipes::InvalidVariable`.
532
567
  A word in braces that is not a variable is written `\{word}` in a path and in
@@ -957,7 +992,10 @@ The rules, beyond those of every description:
957
992
  (`billing.recipe.yml`) are the same: lowercase letters, digits, `-` and `_`.
958
993
  - `recipe.name` and `recipe.version` are required. The version is text made of
959
994
  digits, letters and dots: write `'1.2'` between quotes. `format` is the
960
- version of the format, today 1; `summary` and `homepage` are optional.
995
+ version of the format: 1, or none, for most recipes; 2 for a recipe that
996
+ uses a `{*name}` variable in its `base_url` or in the `path` of an endpoint,
997
+ so that a version of the gem that does not know `{*name}` refuses it.
998
+ `summary` and `homepage` are optional.
961
999
  - `host` is required. A variable can be the whole host, or stand before fixed
962
1000
  text that starts with a dot: `{account}.billing.example.com` and
963
1001
  `s3.{region}.example.com` are accepted, `api.example.{tld}` is not.
@@ -1043,11 +1081,19 @@ What the command does:
1043
1081
  number (`ENV.fetch('NAME', 'text')`, `ENV['NAME'] || 443`) becomes the
1044
1082
  default of the variable. A default that a tag gave to a variable the file
1045
1083
  declares is given by the application from now on. Only a variable with a
1046
- default is declared in the recipe.
1084
+ default is declared in the recipe. In the `base_url` and in a `path` the
1085
+ variable is a `{*name}`, since 2.x put the value of the tag there with its
1086
+ slashes, and the recipe then declares `recipe.format: 2`. A value of one or
1087
+ more segments goes where 2.x sent it; one that starts or ends with a slash,
1088
+ has two in a row or is empty, which 2.x joined, raises
1089
+ `ApiRecipes::InvalidVariable` at the request: give it without those slashes.
1090
+ The command says so when the default written in the tag is such a value.
1047
1091
  - **A word in braces stays text**, as 2.x sent it, unless the file declares a
1048
1092
  variable with that name: it is written `\{word}` in a `path` and in the
1049
1093
  `base_url`, and a header or a parameter that holds one is given by a
1050
- variable whose default is its text.
1094
+ variable whose default is its text. With a star, `{*word}` is written
1095
+ `\{*word}` in a `path` and in the `base_url` even when the file declares
1096
+ `word`; in a header or a parameter it stays as it is.
1051
1097
  - **`--calls` writes beside each endpoint how it is called in Ruby**, as
1052
1098
  `show: # .invoices.show(id)`, after the name of the API. The recipe is the
1053
1099
  same with or without them.
@@ -1162,7 +1208,7 @@ ApiRecipes[:github].users.run
1162
1208
 
1163
1209
  ```ruby
1164
1210
  ApiRecipes.apis.inspect
1165
- # => "[:github, :billing, :shopify]"
1211
+ # => "[:github, :billing, :shopify, :rabbitmq]"
1166
1212
  ```
1167
1213
 
1168
1214
  ### In your classes
@@ -1367,8 +1413,9 @@ in a variable, and for an endpoint whose name is already a method (see
1367
1413
 
1368
1414
  ## Reading the response
1369
1415
 
1370
- `run` returns an `ApiRecipes::Response`. It adds `data` and forwards everything
1371
- else to the [http.rb response](https://github.com/httprb/http/wiki/Response-Handling):
1416
+ `run` returns an `ApiRecipes::Response`. It adds `data`, and has the status,
1417
+ the headers and the body of the
1418
+ [http.rb response](https://github.com/httprb/http/wiki/Response-Handling):
1372
1419
 
1373
1420
  ```ruby
1374
1421
  response = ApiRecipes.github.users.show('octocat').run
@@ -1380,10 +1427,38 @@ response.headers['Content-Type'] # => "application/json; charset=utf-8"
1380
1427
  response.body.to_s # => "{\"login\":\"octocat\", ...}"
1381
1428
  ```
1382
1429
 
1383
- `data` parses the body according to the `Content-Type` of the response. For
1384
- anything that is not JSON, or for an empty body, it raises `HTTP::Error`: read
1385
- `response.body.to_s` instead. If a server sends JSON with the wrong
1386
- `Content-Type`, set `mime_type: application/json` on the endpoint or on the API.
1430
+ `data` parses the body according to the `Content-Type` of the response, with
1431
+ the parser of http.rb, which reads JSON. A type that ends in `+json`, like
1432
+ `application/problem+json`, is read as JSON too, unless your application gave
1433
+ http.rb a parser for it. An empty body gives `nil`, whatever
1434
+ the status and the type: a `204 No Content` needs nothing special. A body of
1435
+ spaces and line breaks counts as empty. A JSON `null` gives `nil` too: read
1436
+ `response.body.to_s` to tell them apart.
1437
+
1438
+ When there is a body that `data` cannot read (no `Content-Type`, a type that is
1439
+ not JSON, JSON that is not valid) it raises `ApiRecipes::UnreadableResponse`.
1440
+ The error has `path` and `response`, and its message gives the status and the
1441
+ type, when there is one, never the body: read `error.response.body.to_s`.
1442
+ `fill`, and a `verify_with` method that reads `data`, raise it as well. If a
1443
+ server sends JSON with the wrong `Content-Type`, set
1444
+ `mime_type: application/json` on the endpoint or on the API.
1445
+
1446
+ `data` raises the same error when the body is no longer there, because it was
1447
+ read with `readpartial` or because reading it failed: then `body.to_s` raises
1448
+ `HTTP::StateError` too.
1449
+
1450
+ `response.parse` reads the body as `data` does: `nil` for an empty body, the
1451
+ same error for one it cannot read. It takes a type, a String or a Symbol, for
1452
+ one response that is to be read with another one, and it reads the body again
1453
+ at every call:
1454
+
1455
+ ```ruby
1456
+ response.parse # as data, read again
1457
+ response.parse('application/json') # whatever the Content-Type and mime_type say
1458
+ ```
1459
+
1460
+ It is not the `parse` of http.rb, whose error quotes the body: that one is
1461
+ still `response.original_response.parse`.
1387
1462
 
1388
1463
  `response.success?` tells whether the response passed the rule of the endpoint
1389
1464
  (see the next section). It is the way to check a response when `on_bad_code` is
@@ -1486,6 +1561,8 @@ end
1486
1561
  The method can be private. It is looked up on the caller, so `verify_with` is
1487
1562
  meant for APIs used from a class or an instance. An endpoint that has no
1488
1563
  `verify_with` of its own looks for one up the tree, as for the other options.
1564
+ `response.data` is `nil` when the body is empty: a rule that reads a key from
1565
+ it checks that first, where an answer without a body is possible.
1489
1566
 
1490
1567
  ## Handling errors
1491
1568
 
@@ -1512,6 +1589,7 @@ body, a credential or a query string: the body is on `error.response`.
1512
1589
  | Error | Raised when |
1513
1590
  | --- | --- |
1514
1591
  | `ApiRecipes::ResponseCodeNotAsExpected` | the response is not a success; has `response`, `path` and `expected_code` |
1592
+ | `ApiRecipes::UnreadableResponse` | `response.data` or `response.parse` cannot read the body; has `response` and `path` |
1515
1593
  | `ApiRecipes::PathParamsMismatch` | an endpoint gets the wrong number of path parameters |
1516
1594
  | `ApiRecipes::InvalidPathParameter` | a path parameter is `nil`, empty, `.` or `..` |
1517
1595
  | `ApiRecipes::NoRouteExists` | `run` is called on an endpoint with `route: no` |
@@ -1642,6 +1720,37 @@ through it raises the same error instead of sending a credential of the levels
1642
1720
  to the old origin: ask `ApiRecipes` (or the class, or the object) for the API
1643
1721
  again. A `configure` that does not move the origin changes nothing for it.
1644
1722
 
1723
+ When one credential is meant for several origins, like the nodes of a cluster
1724
+ that a variable selects, say so where the application gives the credential,
1725
+ with `credential_origins` in `config.values`:
1726
+
1727
+ ```ruby
1728
+ ApiRecipes.configure do |config|
1729
+ config.values = {
1730
+ broker: {
1731
+ basic_auth: { user: 'me', pass: 'secret' },
1732
+ credential_origins: ['https://node2.example.com:15672', 'https://node3.example.com:15672']
1733
+ }
1734
+ }
1735
+ end
1736
+ ```
1737
+
1738
+ Each entry is a whole origin, `https://host` or `https://host:port`, and
1739
+ nothing else: no path, no user, no variable, no wildcard. An entry can also
1740
+ begin with `http://`: the credential then goes there in clear. The origin the
1741
+ credential was given for needs no entry. `credential_origins: :any` sends the
1742
+ credential wherever the request goes, plain `http` included. Use it only when
1743
+ the host, the port and the protocol that reach `with` and the variables never
1744
+ come from the data of a request: whoever chooses the destination receives the
1745
+ credential.
1746
+
1747
+ `credential_origins` is taken only there, next to `authorization` or
1748
+ `basic_auth`. `api` in a class, `with`, a recipe and `apis_configs` refuse it,
1749
+ and it says nothing of a credential that a class or an object sets for itself.
1750
+ A redirect to another origin still drops the credential. An API kept in a
1751
+ variable across a `configure` that moves it sends the credential to its old
1752
+ origin when that origin is named, or with `:any`.
1753
+
1645
1754
  The readers `authorization` and `basic_auth` return the nearest credential that
1646
1755
  was assigned. They do not apply that check: only a request does.
1647
1756
 
@@ -1706,8 +1815,11 @@ become a method, when the configuration is loaded (see
1706
1815
 
1707
1816
  It also warns, once for each endpoint, when the value of a path parameter
1708
1817
  contains a `/` (it is sent as `%2F`) or looks already percent-encoded (it is
1709
- encoded again). The warning names the endpoint and never the value.
1710
- `config.upgrade_warnings = false` turns these two warnings off.
1818
+ encoded again). The warning names the endpoint and never the value. A value
1819
+ that your code encoded is given decoded; a value that the API gave already
1820
+ encoded, such as an id it returned in that form, is given as it is, and then
1821
+ the warning is expected. `config.upgrade_warnings = false` turns these two
1822
+ warnings off.
1711
1823
 
1712
1824
  ## Inspecting an API
1713
1825
 
@@ -1943,11 +2055,14 @@ end
1943
2055
 
1944
2056
  What ApiRecipes does:
1945
2057
 
1946
- - **Path parameters** are encoded one by one. A value cannot add a segment, a
1947
- query string or a fragment. `nil`, an empty value, `.` and `..` are refused.
2058
+ - **Path parameters** are encoded one by one. A value cannot add a query
2059
+ string or a fragment, nor a segment unless the placeholder is a `*name`.
2060
+ `nil`, an empty value, `.` and `..` are refused, and so is an empty, `.` or
2061
+ `..` segment of a `*name`.
1948
2062
  - **Variables** are checked for the place where they end up: a host, a path, a
1949
2063
  header or a query parameter. In a path a value is one encoded segment, like a
1950
- path parameter.
2064
+ path parameter, or, written `{*name}`, several encoded segments, none of them
2065
+ empty, `.` or `..`.
1951
2066
  - **Parameters sent with every request** cannot take the place of the
1952
2067
  credential: with `auth.type: query`, `default_params` that name its parameter
1953
2068
  are refused, and the credential is always the only parameter with its name.
@@ -1959,8 +2074,10 @@ What ApiRecipes does:
1959
2074
  another finds it. A `configure` changes the descriptions and those values in
1960
2075
  one step.
1961
2076
  - **Credentials** are sent only to the origin they were set for, and a request
1962
- that would send one elsewhere raises. A value with a control character is
1963
- refused, so a credential cannot add a header.
2077
+ that would send one elsewhere raises. Only the application names other
2078
+ origins for the credential it gives, with `credential_origins` in
2079
+ `config.values`. A value with a control character is refused, so a credential
2080
+ cannot add a header.
1964
2081
  - **Redirects.** With `follow`, a redirect to another origin drops the
1965
2082
  credentials, the `Cookie` header and the credential query parameter. They are
1966
2083
  not sent again if the chain comes back.
@@ -2054,12 +2171,12 @@ Every protection has an example in [`spec/security`](spec/security); its
2054
2171
  | `protocol` | `https` | `http` or `https`; can be a `{variable}` |
2055
2172
  | `host` | `localhost` | host name, which can contain `{variables}` |
2056
2173
  | `port` | port of the protocol | port number; can be a `{variable}` |
2057
- | `base_url` | none | prefix of every path, for example `api/v1`; can contain `{variables}` |
2174
+ | `base_url` | none | prefix of every path, for example `api/v1`; can contain `{variables}`, and `{*name}` for a value of several segments |
2058
2175
  | `timeout` | `3` | seconds allowed for the whole request; can be a `{variable}`, as `on_bad_code` and `mime_type` |
2059
2176
  | `default_headers` | none | headers sent with every request; a value can contain `{variables}` |
2060
2177
  | `default_params` | none | query parameters sent with every request; a value is text, a number or a boolean, and can contain `{variables}` |
2061
2178
  | `on_bad_code` | `raise` | `raise` or `ignore` when the response is not a success |
2062
- | `mime_type` | from the response | content type used by `response.data` |
2179
+ | `mime_type` | from the response | content type used by `response.data` and `response.parse` |
2063
2180
  | `verify_with` | none | method that decides whether a response is a success |
2064
2181
  | `auth` | none | where the credential goes: `type` (`none`, `bearer`, `basic`, `header`, `query`) and `name` (for `header` and `query`) |
2065
2182
  | `variables` | none | the variables of the API, each with an optional `default` and `description` |
@@ -2069,13 +2186,13 @@ Every protection has an example in [`spec/security`](spec/security); its
2069
2186
 
2070
2187
  | Option | Default | Meaning |
2071
2188
  | --- | --- | --- |
2072
- | `path` | the endpoint name | segment added to the parent path; `''` adds nothing; can contain `:name` and `*name` placeholders and `{variables}` |
2189
+ | `path` | the endpoint name | segment added to the parent path; `''` adds nothing; can contain `:name` and `*name` placeholders, `{variables}` and `{*name}` |
2073
2190
  | `verb` | `get` | HTTP verb; can be a `{variable}`, as `ok_code` (one status), `timeout`, `on_bad_code` and `mime_type` |
2074
2191
  | `route` | `yes` | `no` makes the endpoint a group that cannot be called |
2075
2192
  | `ok_code` | any 2xx | the status, or the list of statuses, accepted as a success |
2076
2193
  | `timeout` | looked for up the tree | seconds allowed for the whole request |
2077
2194
  | `on_bad_code` | looked for up the tree | `raise` or `ignore` |
2078
- | `mime_type` | looked for up the tree | content type used by `response.data` |
2195
+ | `mime_type` | looked for up the tree | content type used by `response.data` and `response.parse` |
2079
2196
  | `verify_with` | looked for up the tree | method that decides whether a response is a success |
2080
2197
  | `default_headers` | none | headers of this endpoint; a request finds them here when it looks up the tree, before those of the API |
2081
2198
  | `default_params` | none | query parameters of this endpoint; a request finds them here when it looks up the tree, before those of the API |
@@ -2128,7 +2245,8 @@ operation, as its verb does.
2128
2245
  `ApiNameClashError`, `ConfigurationError`, `CredentialOriginMismatch`,
2129
2246
  `InvalidCredential`, `InvalidPathParameter`, `InvalidUrl`, `InvalidVariable`,
2130
2247
  `MissingVariable`, `NoRouteExists`, `PathParamsMismatch`, `RecipeFileError`,
2131
- `ResponseCodeNotAsExpected` and `UnknownEndpoint`). If your application has a
2248
+ `ResponseCodeNotAsExpected`, `UnknownEndpoint` and `UnreadableResponse`). If
2249
+ your application has a
2132
2250
  class with one of these names, write it with a leading `::` inside the classes
2133
2251
  that include `ApiRecipes`, for example `::Response`. The internal classes of
2134
2252
  the gem are all under `ApiRecipes::Internals`, so they hide nothing else.
data/UPGRADING.md CHANGED
@@ -95,7 +95,10 @@ configuration in place. Four things are worth knowing:
95
95
  `variables: { template: { default: '{id}' } }` with the header value
96
96
  `'{template}'`. Braces around anything else, such as a JSON value, are sent
97
97
  as they are. In a path, if you meant a value that changes at every call,
98
- write a placeholder, `/items/:id`.
98
+ write a placeholder, `/items/:id`. In the `base_url` and in a `path`, a
99
+ word in braces with a star, `{*id}`, is a variable too, whose value spans
100
+ several segments: `api_recipes convert` writes `\{*id}`, whether the file
101
+ declares `id` or not.
99
102
  - A recipe that is missing, not valid YAML, not valid UTF-8 or not a recipe
100
103
  raises `ApiRecipes::RecipeFileError`, which names the file. A recipe is
101
104
  plain YAML: anchors, aliases, tags and the merge key are refused.
@@ -114,7 +117,10 @@ describes to a recipe in `config/api_recipes`, one after the other:
114
117
 
115
118
  - what an `<%= ... %>` tag gave becomes a variable of the recipe, and the code
116
119
  of the tag moves, as it is written, to `config.values` in the file that
117
- calls `ApiRecipes.configure`;
120
+ calls `ApiRecipes.configure`; in the `base_url` and in a `path` it is a
121
+ `{*name}`, which keeps the slashes inside the value as 2.x did, while a
122
+ value that starts or ends with a slash, has two in a row or is empty raises
123
+ `ApiRecipes::InvalidVariable`: set `API_PREFIX=api/v1`, not `/api/v1`;
118
124
  - `config.recipes_paths` is added, and `config.apis_files_paths` goes with the
119
125
  last description;
120
126
  - the old file is deleted, and every change is listed.
@@ -138,7 +144,8 @@ own raises:
138
144
  ```
139
145
  api 'github': the credential is bound to "https://api.github.com" but the request goes to
140
146
  "https://ent.example.test". Set the credential at the level that changes the destination,
141
- or set it to nil to send none
147
+ or set it to nil to send none, or name that origin in credential_origins, next to the
148
+ credential in config.values
142
149
  ```
143
150
 
144
151
  Give the credential where the class declares the API:
@@ -150,6 +157,10 @@ class EnterpriseClient
150
157
  end
151
158
  ```
152
159
 
160
+ When the credential of the application is meant for that origin too, name the
161
+ origin with `credential_origins` in `config.values` instead (see
162
+ "Authorization" in the README).
163
+
153
164
  ### Credentials are given when the application starts
154
165
 
155
166
  In 2.x the usual line was `ApiRecipes.github.authorization = '...'`, and code
@@ -277,7 +288,8 @@ ApiRecipes.github.users.show('a/b').url.to_s
277
288
 
278
289
  - **Values you encoded yourself.** Remove the encoding (`ERB::Util.url_encode`,
279
290
  `CGI.escape`): `%2F` would be sent as `%252F`. The gem logs a warning, once for
280
- each endpoint, when a value looks already encoded.
291
+ each endpoint, when a value looks already encoded. A value that the API gave
292
+ already encoded, such as an id it returned in that form, is given as it is.
281
293
  - **A `/` in a value** that was used to cover several segments is now `%2F`. Write
282
294
  the placeholder with a `*` instead: each segment is encoded and the slashes stay.
283
295
  The gem logs a warning, once for each endpoint, when a value contains a `/`.
@@ -364,6 +376,33 @@ to the other host. Cookies that a server sets during a chain of redirects are no
364
376
  carried to the next hop any more (they were with http.rb 5). A page that sets a
365
377
  cookie and redirects to itself now ends in the redirect-loop error of http.rb.
366
378
 
379
+ ### `response.data` on an empty body, and on one it cannot read
380
+
381
+ In 2.x `data` passed on whatever http.rb or the JSON parser raised, also for a
382
+ response with no body. Now an empty body gives `nil`, and a body that cannot be
383
+ read (no `Content-Type`, a type that is not JSON, JSON that is not valid) raises
384
+ `ApiRecipes::UnreadableResponse`, whose message never contains the body. The
385
+ body is still on the response:
386
+
387
+ ```ruby
388
+ begin
389
+ response.data
390
+ rescue ApiRecipes::UnreadableResponse => e
391
+ e.response.body.to_s
392
+ end
393
+ ```
394
+
395
+ A `rescue HTTP::Error` or a `rescue JSON::ParserError` written around `data`
396
+ no longer catches it. The same holds around `fill`, and around a `run` whose
397
+ `verify_with` method reads `data`. Timeouts and connection errors are still
398
+ errors of http.rb. Code that reads a key of `data` after a call that can answer
399
+ without a body gets `nil`: check `response.data.nil?` first.
400
+
401
+ `response.parse` is no longer the method of http.rb. It reads the body as
402
+ `data` does, with the type it is given: `nil` for an empty body,
403
+ `ApiRecipes::UnreadableResponse` for one it cannot read. The method of http.rb
404
+ is `response.original_response.parse`.
405
+
367
406
  ### `fill`
368
407
 
369
408
  `fill` calls only public writers. It used to call private ones, and it swallowed
@@ -379,7 +418,8 @@ classes. In 3.0 `Route` and `Settings` are gone, so a top-level `Route` or
379
418
  `Settings` of yours is found again. `Error`, `Internals`, `VERSION` and the new
380
419
  error classes (`ConfigurationError`, `CredentialOriginMismatch`,
381
420
  `InvalidCredential`, `InvalidPathParameter`, `InvalidUrl`, `InvalidVariable`,
382
- `MissingVariable`, `RecipeFileError`, `UnknownEndpoint`) are new, and hide a
421
+ `MissingVariable`, `RecipeFileError`, `UnknownEndpoint`, `UnreadableResponse`)
422
+ are new, and hide a
383
423
  top-level constant of yours with the same name. Inside the classes that include
384
424
  `ApiRecipes`, write it with a leading `::`, for example `::Error`. The
385
425
  [README](README.md#good-to-know) lists all the names.
@@ -396,7 +436,8 @@ top-level constant of yours with the same name. Inside the classes that include
396
436
  `auth: { type: 'query' }`.
397
437
  - `response.request` was removed, because the request holds the credentials that
398
438
  were sent. `response.uri` and the other readers stay, and the http.rb response
399
- is still `response.original_response`.
439
+ is still `response.original_response`. `response.flush` returns the response of
440
+ the gem, not the one of http.rb.
400
441
  - `response.to_s` returns the body, as the http.rb response does. In 2.x it was
401
442
  the default text of the object.
402
443
  - A redirect to a host with non-ASCII characters needs the `addressable` gem;
@@ -470,7 +511,8 @@ You can adopt these when you are ready. The [README](README.md) describes each o
470
511
 
471
512
  - Path parameters are encoded, and `nil`, empty, `.` and `..` are refused.
472
513
  - Variables are checked where they end up: host, path or header.
473
- - A credential is sent only to the origin it was set for, and a value with a
514
+ - A credential is sent only to the origin it was set for, or to one that the
515
+ application names for it with `credential_origins`, and a value with a
474
516
  control character is refused.
475
517
  - Redirects to another origin drop the credentials and cookies.
476
518
  - Logs, error messages of the gem and `inspect` never show a credential, a
@@ -77,6 +77,7 @@ module ApiRecipes
77
77
  @secret = []
78
78
  @given = {}
79
79
  @refs = {}
80
+ @segments = false
80
81
  name, options = api(parsed(plain(source)))
81
82
  @name = name
82
83
  declared = options['variables']
@@ -86,7 +87,7 @@ module ApiRecipes
86
87
  refuse('already has the key recipe: rename the file to NAME.recipe.yml and check it') if options.key?('recipe')
87
88
 
88
89
  body = api_options(options)
89
- body = { 'recipe' => { 'name' => name, 'version' => @version, 'format' => Internals::Recipe::FORMAT } }.merge(body)
90
+ body = { 'recipe' => { 'name' => name, 'version' => @version, 'format' => @segments ? Internals::Recipe::SEGMENTS_FORMAT : Internals::Recipe::FORMATS.first } }.merge(body)
90
91
  # A variable that has no default needs no declaration: the recipe
91
92
  # uses it, and that makes it a variable that a value must be given to.
92
93
  written = @variables.reject { |_, spec| spec.empty? }
@@ -267,7 +268,7 @@ module ApiRecipes
267
268
  when 'verify_with' then left_out(key, value)
268
269
  when 'variables' then out[key] = declared_variables(value)
269
270
  when 'host' then out[key] = with_variables(value, key, key)
270
- when 'base_url' then out[key] = with_variables(as_text(value, key), key, key)
271
+ when 'base_url' then out[key] = with_variables(as_text(value, key), key, key, star: true)
271
272
  when *OPTION_KEYS then out[key] = option(value, key, key)
272
273
  when *SENT then out[key] = sent(value, key)
273
274
  when 'endpoints' then out[key] = endpoints(value, key)
@@ -308,7 +309,7 @@ module ApiRecipes
308
309
  here = "#{where}.#{key}"
309
310
  case key
310
311
  when 'verify_with' then left_out(here, value)
311
- when 'path' then out[key] = with_variables(as_text(value, here), here, "#{name}_path")
312
+ when 'path' then out[key] = with_variables(as_text(value, here), here, "#{name}_path", star: true)
312
313
  when *OPTION_KEYS then out[key] = option(value, here, "#{name}_#{key}")
313
314
  when *SENT then out[key] = sent(value, here)
314
315
  when 'endpoints' then out[key] = endpoints(value, here)
@@ -351,12 +352,16 @@ module ApiRecipes
351
352
  # A word in braces that the file does not declare as a variable: 2.x
352
353
  # sent it as text, and 3.0 would read it as a variable. In a path and
353
354
  # in the base_url a backslash before the brace already keeps it text;
354
- # a header and a parameter have no such escape.
355
- TEXT_IN_BRACES = /(?<!\\)\{([A-Za-z_]\w*)\}/
355
+ # a header and a parameter have no such escape. With a star, {*word},
356
+ # it was text in every version before, declared or not: in a path and
357
+ # in the base_url 3.0 reads it as a variable of several segments.
358
+ TEXT_IN_BRACES = /(?<!\\)\{(\*?)([A-Za-z_]\w*)\}/
356
359
 
357
360
  def text_in_braces?(value, escaped: true)
358
- pattern = escaped ? TEXT_IN_BRACES : Internals::Template::VARIABLE
359
- value.is_a?(String) && value.scan(pattern).flatten.any? { |name| @origins[name] != :declared }
361
+ return false unless value.is_a?(String)
362
+ return value.scan(Internals::Template::VARIABLE).flatten.any? { |name| @origins[name] != :declared } unless escaped
363
+
364
+ value.scan(TEXT_IN_BRACES).any? { |star, name| !star.empty? || @origins[name] != :declared }
360
365
  end
361
366
 
362
367
  # In a path and in the base_url a brace is kept as text with a backslash.
@@ -364,11 +369,12 @@ module ApiRecipes
364
369
  return value unless text_in_braces?(value)
365
370
 
366
371
  value.gsub(TEXT_IN_BRACES) do
367
- name = Regexp.last_match(1)
368
- next Regexp.last_match(0) if @origins[name] == :declared
372
+ star, name = Regexp.last_match.captures
373
+ next Regexp.last_match(0) if star.empty? && @origins[name] == :declared
369
374
 
370
- @changes << "#{shown(where)}: {#{shown(name)}} was text in 2.x and would be a variable: it is written \\{#{shown(name)}}"
371
- "\\{#{name}}"
375
+ word = "{#{star}#{shown(name)}}"
376
+ @changes << "#{shown(where)}: #{word} was text in 2.x and would be a variable: it is written \\#{word}"
377
+ "\\{#{star}#{name}}"
372
378
  end
373
379
  end
374
380
 
@@ -412,18 +418,38 @@ module ApiRecipes
412
418
  end
413
419
 
414
420
  # A value where a recipe can have a variable.
415
- def with_variables(value, where, fallback)
421
+ # star: in the base_url and in a path, where 2.x put the value of the
422
+ # tag as it was, slashes included: the variable spans several segments,
423
+ # and the recipe asks for the format that knows {*name}.
424
+ def with_variables(value, where, fallback, star: false)
416
425
  return fixed(value, where) unless value.is_a?(String) && @token.match?(value)
417
426
 
418
427
  value.gsub(@token) do
419
428
  tag = @tags[Regexp.last_match(1).to_i]
420
429
  variable = variable_for(tag, fallback, where, default: true)
421
430
  kept = @variables[variable].key?('default') ? ', with the default written in the tag' : ''
422
- @changes << "#{shown(where)}: the ERB tag is now the variable {#{variable}}#{kept}"
423
- "{#{variable}}"
431
+ @segments ||= star
432
+ as_variable = "{#{'*' if star}#{variable}}"
433
+ @changes << "#{shown(where)}: the ERB tag is now the variable #{as_variable}#{kept}"
434
+ refused_default(where, variable) if star
435
+ as_variable
424
436
  end
425
437
  end
426
438
 
439
+ # 2.x joined the slashes of a value; a {*name} refuses a value that
440
+ # starts or ends with one, has two in a row or is empty. Said with the
441
+ # place and the name, never with the value.
442
+ def refused_default(where, variable)
443
+ spec = @variables[variable]
444
+ return unless spec.key?('default')
445
+
446
+ Internals::Template.segments(spec['default'], variable, @name)
447
+ rescue InvalidVariable
448
+ @changes << "#{shown(where)}: the default written in the tag is not a value that {*#{variable}} takes: one or more " \
449
+ 'segments, with no slash at the start or at the end and no two in a row. Correct it in the recipe ' \
450
+ 'and in the code of the tag, which config.values gives'
451
+ end
452
+
427
453
  def variable_for(tag, fallback, where, default:)
428
454
  # What is named like a credential in the environment has no default either.
429
455
  default &&= !CREDENTIAL.match?(tag.env.to_s)
@@ -36,7 +36,7 @@ module ApiRecipes
36
36
  tree = Tree.build(document, only: @only, except: @except)
37
37
  raise Error, '--version: must be made of digits, letters and dots, such as 1.2.0' unless Internals::Recipe::VERSION.match?(@version.to_s)
38
38
 
39
- options = { recipe: { 'name' => name, 'version' => @version, 'format' => Internals::Recipe::FORMAT } }.merge(server.options)
39
+ options = { recipe: { 'name' => name, 'version' => @version, 'format' => Internals::Recipe::FORMATS.first } }.merge(server.options)
40
40
  options[:auth] = security.auth if security.auth
41
41
  header = "Generated by api_recipes import from #{document.title} #{document.version}"
42
42
  text = Writer.new(name: name, options: options, nodes: tree.nodes, header: header).to_yaml
@@ -72,7 +72,7 @@ module ApiRecipes
72
72
  def address(fill = false)
73
73
  host = fill ? filled(@api.host) : @api.host
74
74
  base = @api.base_url.to_s
75
- base = filled(base) if fill
75
+ base = filled(base, Internals::Template::PATH_VARIABLE) if fill
76
76
  path = "/#{base}".gsub(%r{/+}, '/').chomp('/')
77
77
  protocol = fill ? filled(@api.protocol.to_s) : @api.protocol
78
78
  port = fill && @api.port ? filled(@api.port.to_s) : @api.port
@@ -216,9 +216,11 @@ module ApiRecipes
216
216
  found
217
217
  end
218
218
 
219
- def filled(text)
219
+ # The base_url reads {name} and {*name}, with PATH_VARIABLE; the rest
220
+ # reads {name} only. The name is the last group of both.
221
+ def filled(text, pattern = Internals::Template::VARIABLE)
220
222
  defaults = @api.variables.transform_values { |spec| spec[:default] }.compact
221
- text.gsub(Internals::Template::VARIABLE) { defaults.fetch(Regexp.last_match(1).to_sym, Regexp.last_match(0)) }
223
+ text.gsub(pattern) { defaults.fetch(Regexp.last_match[-1].to_sym, Regexp.last_match(0)) }
222
224
  end
223
225
 
224
226
  # One line for each variable: its default, or that it must be set.
@@ -101,6 +101,8 @@ module ApiRecipes
101
101
  'a bare rescue in a file that does not name the gem, around code that calls it somewhere else: it now catches the errors of the gem too',
102
102
  'the response body read from the message of a verify_with error: read it from error.response',
103
103
  'fill with private setters, or code that relies on swallowed errors: make the setters public, handle the errors',
104
+ 'a rescue of HTTP::Error or of JSON::ParserError around response.data, around response.parse, around fill, or ' \
105
+ 'around a run whose verify_with reads data: an empty body now gives nil, and a body that cannot be read raises ApiRecipes::UnreadableResponse',
104
106
  'cookies set by a server during a redirect chain: they are no longer carried to the next hop',
105
107
  'Endpoint#name, #params, #children, #api and Api#name, #configs, #object were removed: use definition (a search cannot tell them from other methods called like that)',
106
108
  'an object restored from a serialized form (Marshal, YAML) has no credential: assign it again',
@@ -67,16 +67,19 @@ module ApiRecipes
67
67
  end
68
68
 
69
69
  class CredentialOriginMismatch < Error
70
- def initialize(api, credential_origin, request_origin)
70
+ # application: the credential is the one of config.values, the only one
71
+ # that credential_origins can send to other origins.
72
+ def initialize(api, credential_origin, request_origin, application: false)
73
+ remedy = application ? ', or name that origin in credential_origins, next to the credential in config.values' : ''
71
74
  if credential_origin
72
75
  super("api '#{api}': the credential is bound to #{credential_origin.inspect} but the request goes to " \
73
76
  "#{request_origin.inspect}. Set the credential at the level that changes the destination, " \
74
- 'or set it to nil to send none')
77
+ "or set it to nil to send none#{remedy}")
75
78
  else
76
79
  super("api '#{api}': the origin of the credential cannot be determined at the level that holds it " \
77
80
  '(for example, a variable of the host has no value there), so it is not sent to ' \
78
81
  "#{request_origin.inspect}. Set the credential at the level that sets the destination, " \
79
- 'or give the level that holds it the values its host needs')
82
+ "or give the level that holds it the values its host needs#{remedy}")
80
83
  end
81
84
  end
82
85
  end
@@ -122,6 +125,20 @@ module ApiRecipes
122
125
  end
123
126
  end
124
127
 
128
+ # Raised by Response#data for a body it cannot read. The message has the
129
+ # route, the status and the content type: never the body, which is on
130
+ # response.body.
131
+ class UnreadableResponse < Error
132
+ attr_reader :path, :response
133
+
134
+ def initialize(path, response, reason, advice)
135
+ @path = path
136
+ @response = response
137
+ route = path ? " on route '#{path}'" : ''
138
+ super("cannot read the data of the response#{route} (#{response.code}): #{reason}. #{advice}")
139
+ end
140
+ end
141
+
125
142
  class ApiConfigIsNotAnHash < Error
126
143
  def initialize(endpoint)
127
144
  message = "provided config for endpoint '#{endpoint}' must be an Hash"
@@ -264,12 +264,17 @@ module ApiRecipes
264
264
  # The global level uses the global definition, the others the owner's one:
265
265
  # every other level of the chain was written through the declaration in
266
266
  # use, whose tree that is.
267
+ # The level of the application can name other origins for the
268
+ # credential it holds, with credential_origins: no other level is asked.
267
269
  def check_origin(chain, index, destination)
270
+ kind, level = chain[index]
271
+ return if kind == :global && Origins.name?(level.origins, destination)
272
+
268
273
  registry = chain.respond_to?(:registry) ? chain.registry : Registry.current
269
- bound = origin_from(definition_in_force(chain[index].first, registry), chain, index, with: false)
274
+ bound = origin_from(definition_in_force(kind, registry), chain, index, with: false)
270
275
  return if bound && destination && bound.casecmp?(destination)
271
276
 
272
- raise CredentialOriginMismatch.new(@definition.name, bound, destination)
277
+ raise CredentialOriginMismatch.new(@definition.name, bound, destination, application: kind == :global)
273
278
  end
274
279
 
275
280
  # The tree a level reads now. An api or an endpoint kept across a
@@ -4,7 +4,12 @@ module ApiRecipes
4
4
  module Internals
5
5
  # What was assigned to one api at one level: a credential (nil when never
6
6
  # assigned, Credential::NONE when removed on purpose) and variable values.
7
- Level = Data.define(:credential, :variables) do
7
+ # origins is what credential_origins gave with the credential, see
8
+ # Origins: only the level of the application has it, and a level that is
9
+ # written, sealed or read back from a serialized form never does.
10
+ Level = Data.define(:credential, :variables, :origins) do
11
+ def initialize(credential:, variables:, origins: nil) = super
12
+
8
13
  def inspect = "#<ApiRecipes::Internals::Level credential=#{credential.inspect} variables=[FILTERED]>"
9
14
 
10
15
  def to_s = inspect
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module Internals
5
+ # The other origins a credential of the application may go to, as
6
+ # credential_origins says in config.values: :any, or a list of whole
7
+ # origins. The origin the credential was given for needs no entry.
8
+ module Origins
9
+ ANY = :any
10
+ KEY = :credential_origins
11
+ # A scheme, a host as the gem takes one and a port: nothing before,
12
+ # nothing after, so no user, no path and no line break. It is matched
13
+ # against ASCII text only: without its case, a letter of another
14
+ # alphabet is taken for one of these.
15
+ ENTRY = %r{\A(https?)://([A-Za-z0-9._-]+)(?::([0-9]{1,5}))?\z}i
16
+ PORTS = (1..65_535)
17
+ WHOLE = "'scheme://host' or 'scheme://host:port', with https or http as the scheme"
18
+
19
+ class << self
20
+ # nil, ANY, or a frozen list of origins written as a request writes
21
+ # its own. An entry that is refused is named by its position, never
22
+ # shown: it can hold a user and a password.
23
+ def from(value, where)
24
+ return nil if value.nil?
25
+ return ANY if ANY.equal?(value)
26
+ unless Array === value && !value.empty?
27
+ raise ConfigurationError.new(["#{where}.#{KEY}: must be :any or a list of origins, each written as #{WHOLE}"])
28
+ end
29
+
30
+ value.each_with_index.map do |entry, index|
31
+ written(entry) || raise(ConfigurationError.new(
32
+ ["#{where}.#{KEY}: entry #{index + 1} is not an origin: write it as #{WHOLE}, and nothing else"]
33
+ ))
34
+ end.uniq.freeze
35
+ end
36
+
37
+ # Whether origins, as from returned them, name destination.
38
+ def name?(origins, destination)
39
+ return true if origins == ANY
40
+ return false if origins.nil? || destination.nil?
41
+
42
+ origins.any? { |origin| origin.casecmp?(destination) }
43
+ end
44
+
45
+ private
46
+
47
+ # entry as Context#address writes an origin: without the default
48
+ # port. nil when it is not a whole origin. What is checked is a copy
49
+ # that is a String and nothing more: an object of a subclass is not
50
+ # asked what it holds.
51
+ def written(entry)
52
+ return nil unless String === entry
53
+
54
+ text = String.new(entry)
55
+ return nil unless text.ascii_only?
56
+
57
+ match = ENTRY.match(text)
58
+ return nil unless match
59
+
60
+ scheme = match[1].downcase
61
+ port = match[3]&.to_i
62
+ return nil unless port.nil? || PORTS.cover?(port)
63
+
64
+ port = nil if port == Context::DEFAULT_PORTS[scheme]
65
+ "#{scheme}://#{match[2]}#{":#{port}" if port}".freeze
66
+ end
67
+ end
68
+ end
69
+ end
70
+ end
@@ -10,6 +10,7 @@ module ApiRecipes
10
10
  FIXED_KEPT = /\A(?:[A-Za-z0-9\-._~!$&'()*+,;=:@\/]|%\h\h)/
11
11
  UNRESERVED = /[A-Za-z0-9\-._~]/
12
12
  ENCODED_SEQUENCE = /%25\h\h/
13
+ VARIABLE_KINDS = %i[variable segments].freeze
13
14
 
14
15
  # Percent-encodes every byte outside letters, digits and -._~
15
16
  def self.escape(string)
@@ -29,13 +30,27 @@ module ApiRecipes
29
30
  repeated = names.find { |name| names.count(name) > 1 }
30
31
  raise ArgumentError, "placeholder '#{repeated}' is repeated in '#{string}'" if repeated
31
32
  @param_names = names.freeze
32
- @variable_names = @parts.select { |kind, _| kind == :variable }.map(&:last).uniq.freeze
33
+ @variable_names = @parts.select { |kind, _| VARIABLE_KINDS.include?(kind) }.map(&:last).uniq.freeze
34
+ @segments = @parts.any? { |kind, _| kind == :segments }
35
+ end
36
+
37
+ # True when string, read as a path, has a {*name}. A string that is not
38
+ # a valid path answers false: whoever compiles it reports why.
39
+ def self.segments_variable?(string)
40
+ parse(string.to_s).segments?
41
+ rescue ArgumentError
42
+ false
33
43
  end
34
44
 
35
45
  # param_names: the placeholders, which take an argument each, in order.
36
- # variable_names: the {variables} of the api, each once.
46
+ # variable_names: the {variables} and {*variables} of the api, each once.
37
47
  attr_reader :param_names, :variable_names
38
48
 
49
+ # Whether the path has a {*name}, whose value spans several segments.
50
+ def segments?
51
+ @segments
52
+ end
53
+
39
54
  # The block, if given, is called with the name of a parameter, :slash when
40
55
  # its value (not a splat) contains '/' or :encoded when it contains a
41
56
  # sequence %XX, and the endpoint. It never receives the value.
@@ -68,14 +83,15 @@ module ApiRecipes
68
83
  encoded = encode_splat(remaining.shift, content, endpoint)
69
84
  out << encoded
70
85
  yield content, :encoded, endpoint if block_given? && encoded.include?('%25') && encoded.match?(ENCODED_SEQUENCE)
71
- when :variable
86
+ when :variable, :segments
72
87
  raise ArgumentError, 'a path with variables needs a context' if context.nil?
73
88
 
74
89
  variables ||= context.variables
75
90
  api = context.definition.name
76
91
  raise MissingVariable.new(api, content) unless variables.key?(content)
77
92
 
78
- out << Template.segment(variables[content], content, api)
93
+ value = variables[content]
94
+ out << (kind == :segments ? Template.segments(value, content, api) : Template.segment(value, content, api))
79
95
  end
80
96
  end
81
97
  out
@@ -88,6 +104,7 @@ module ApiRecipes
88
104
  when :param then ":#{content}"
89
105
  when :splat then "*#{content}"
90
106
  when :variable then "{#{content}}"
107
+ when :segments then "{*#{content}}"
91
108
  end
92
109
  end.join
93
110
  end
@@ -107,9 +124,9 @@ module ApiRecipes
107
124
  elsif rest.start_with?('\\{')
108
125
  text << '%7B'
109
126
  index += 2
110
- elsif (match = rest.match(/\A\{(#{NAME})\}/o))
127
+ elsif (match = rest.match(/\A\{(\*?)(#{NAME})\}/o))
111
128
  flush(parts, text)
112
- parts << [:variable, match[1].to_sym]
129
+ parts << [match[1].empty? ? :variable : :segments, match[2].to_sym]
113
130
  index += match[0].length
114
131
  elsif (match = rest.match(/\A:(#{NAME})/o))
115
132
  flush(parts, text)
@@ -10,7 +10,9 @@ module ApiRecipes
10
10
  class Recipe
11
11
  MAX_BYTES = 1_048_576
12
12
  SUFFIX = '.recipe.yml'
13
- FORMAT = 1
13
+ FORMATS = [1, 2].freeze
14
+ # The format that knows {*name}.
15
+ SEGMENTS_FORMAT = 2
14
16
  NAME = /\A[a-z0-9_][a-z0-9_-]{0,63}\z/
15
17
  VERSION = /\A[0-9A-Za-z]+(?:\.[0-9A-Za-z]+)*\z/
16
18
  MAX_VERSION = 32
@@ -118,7 +120,8 @@ module ApiRecipes
118
120
  refuse(refused) if refused
119
121
  name, options = one_api(data)
120
122
  problems = name_problems(name, file_name) + recipe_problems(name, options['recipe']) +
121
- verify_with_problems(name, options) + host_problems(options['host']) + size_problems(options)
123
+ verify_with_problems(name, options) + host_problems(options['host']) + size_problems(options) +
124
+ segments_problems(options)
122
125
  refuse(problems) unless problems.empty?
123
126
 
124
127
  @name = name
@@ -241,9 +244,9 @@ module ApiRecipes
241
244
  end
242
245
  problems << "recipe.name must be '#{name}', the name of the api" unless recipe['name'] == name
243
246
  problems.concat(version_problems(recipe['version']))
244
- unless recipe['format'].nil? || recipe['format'] == FORMAT
247
+ unless recipe['format'].nil? || FORMATS.include?(recipe['format'])
245
248
  problems << "recipe.format #{PlainYaml.label(recipe['format'])} is not known to this version of api_recipes " \
246
- "(it knows #{FORMAT}): update the gem"
249
+ "(it knows #{FORMATS.join(' and ')}): update the gem"
247
250
  end
248
251
  summary = recipe['summary']
249
252
  unless summary.nil? || (summary.is_a?(String) && summary.length <= MAX_TEXT)
@@ -282,6 +285,29 @@ module ApiRecipes
282
285
  problems
283
286
  end
284
287
 
288
+ # A {*name} spans several segments, and a version of the gem that knows
289
+ # only format 1 would send it as text: such a recipe declares format 2,
290
+ # so that an older version refuses it. A \{*name} is text and asks
291
+ # for nothing.
292
+ def segments_problems(options)
293
+ recipe = options['recipe']
294
+ return [] unless recipe.is_a?(Hash) && [nil, 1].include?(recipe['format'])
295
+ return [] unless segments_variable?(options['base_url']) || segments_in_paths?(options['endpoints'])
296
+
297
+ ["uses {*name} in its base_url or in the path of an endpoint: write recipe.format: #{SEGMENTS_FORMAT}, " \
298
+ 'so that an older api_recipes refuses it']
299
+ end
300
+
301
+ def segments_in_paths?(endpoints)
302
+ return false unless endpoints.is_a?(Hash)
303
+
304
+ endpoints.each_value.any? do |options|
305
+ options.is_a?(Hash) && (segments_variable?(options['path']) || segments_in_paths?(options['endpoints']))
306
+ end
307
+ end
308
+
309
+ def segments_variable?(value) = value.is_a?(String) && PathTemplate.segments_variable?(value)
310
+
285
311
  # A variable can be the whole host, or stand before fixed text that
286
312
  # starts with a dot: its value never decides where the host ends.
287
313
  def host_problems(host)
@@ -62,8 +62,8 @@ module ApiRecipes
62
62
  "#{endpoint}: the value of '#{param}' contains '/' and is now sent as %2F. " \
63
63
  "To span several segments use *#{param} in the path."
64
64
  else
65
- "#{endpoint}: the value of '#{param}' looks already percent-encoded. " \
66
- 'ApiRecipes now encodes path parameters itself.'
65
+ "#{endpoint}: the value of '#{param}' looks already percent-encoded, and is encoded again. " \
66
+ 'If your code encoded it, give it decoded; if the API gave it in this form, give it as it is.'
67
67
  end
68
68
  warn_once([endpoint, param, kind], message)
69
69
  end
@@ -98,20 +98,25 @@ module ApiRecipes
98
98
  raise ConfigurationError.new(["values.#{shown}: is not the name of an api"]) unless shown == name.to_s && !shown.empty?
99
99
  raise ConfigurationError.new(["values.#{key}: is given twice"]) if levels.key?(key)
100
100
 
101
- levels[key] = level_from(given, "values.#{key}")
101
+ levels[key] = level_from(given, "values.#{key}", origins: true)
102
102
  end.freeze
103
103
  end
104
104
 
105
105
  # The level that given describes: variables, and authorization or
106
- # basic_auth. A credential given as nil means "send none".
107
- def level_from(given, where)
106
+ # basic_auth. A credential given as nil means "send none". origins:
107
+ # true for the level of the application, the only one that takes
108
+ # credential_origins: the key is taken out here and is no option for
109
+ # the compiler, which refuses it wherever else it is written.
110
+ def level_from(given, where, origins: false)
108
111
  raise ConfigurationError.new(["#{where}: must be a Hash"]) unless given.is_a?(Hash)
109
112
 
110
113
  texts = given.keys.map(&:to_s)
111
- # What is not one of the three names is not shown: a credential
114
+ names = VALUE_KEYS.map(&:to_s)
115
+ names += [Origins::KEY.to_s] if origins
116
+ # What is not one of these names is not shown: a credential
112
117
  # written in the wrong place would be.
113
- unless (texts - VALUE_KEYS.map(&:to_s)).empty?
114
- raise ConfigurationError.new(["#{where}: takes variables, authorization and basic_auth, and nothing else"])
118
+ unless (texts - names).empty?
119
+ raise ConfigurationError.new(["#{where}: takes #{names[0..-2].join(', ')} and #{names.last}, and nothing else"])
115
120
  end
116
121
  twice = texts.find { |text| texts.count(text) > 1 }
117
122
  raise ConfigurationError.new(["#{where}: #{twice} is given twice"]) if twice
@@ -121,9 +126,15 @@ module ApiRecipes
121
126
  raise ConfigurationError.new(["#{where}: takes authorization or basic_auth, not both"])
122
127
  end
123
128
 
124
- resolved = Compiler.resolve_options(given, :with_api)
125
129
  kind = (names & %i[authorization basic_auth]).first
126
- Level.new(credential: kind && Credential.from(kind, resolved[kind]), variables: resolved[:variables])
130
+ about_origins, given = given.partition { |key, _value| key.to_s == Origins::KEY.to_s }.map(&:to_h)
131
+ unless about_origins.values.first.nil? || kind
132
+ raise ConfigurationError.new(["#{where}: #{Origins::KEY} is given with authorization or basic_auth"])
133
+ end
134
+
135
+ resolved = Compiler.resolve_options(given, :with_api)
136
+ Level.new(credential: kind && Credential.from(kind, resolved[kind]), variables: resolved[:variables],
137
+ origins: Origins.from(about_origins.values.first, where))
127
138
  rescue ConfigurationError => e
128
139
  raise e if e.errors.all? { |problem| problem.start_with?(where) }
129
140
 
@@ -285,7 +285,7 @@ module ApiRecipes
285
285
  mime_type = setting(:mime_type)
286
286
  hidden = auth[:type] == :query ? auth[:name] : nil
287
287
  success, expected, message = outcome(http_response, mime_type, hidden)
288
- response = Response.new(http_response, mime_type: mime_type, success: success, hidden_param: hidden)
288
+ response = Response.new(http_response, mime_type: mime_type, success: success, hidden_param: hidden, path: @path)
289
289
  if !success && setting(:on_bad_code).to_s == 'raise'
290
290
  raise ResponseCodeNotAsExpected.new(@path, expected, response, message: message)
291
291
  end
@@ -298,7 +298,7 @@ module ApiRecipes
298
298
  verify_with = setting(:verify_with)
299
299
  owner = @context.owner
300
300
  if verify_with && owner.respond_to?(verify_with, true)
301
- checked = Response.new(http_response, mime_type: mime_type, hidden_param: hidden)
301
+ checked = Response.new(http_response, mime_type: mime_type, hidden_param: hidden, path: @path)
302
302
  valid = owner.send(verify_with, checked) ? true : false
303
303
  return [valid, nil, "response for request on route '#{@path}' was not valid. Verified with #{verify_with}."]
304
304
  end
@@ -7,9 +7,16 @@ module ApiRecipes
7
7
  # How a value is checked depends on the position.
8
8
  class Template
9
9
  VARIABLE = /\{([A-Za-z_]\w*)\}/
10
+ # A variable whose value spans several segments: read in a base_url and
11
+ # in the path of an endpoint only. Elsewhere it is text.
12
+ SEGMENTS_VARIABLE = /\{\*([A-Za-z_]\w*)\}/
13
+ # What a base_url reads: {name} and {*name}.
14
+ PATH_VARIABLE = /\{(\*?)([A-Za-z_]\w*)\}/
10
15
  HOST_VALUE = /\A[A-Za-z0-9._-]+\z/
11
16
  CONTROL = /[\x00-\x1F\x7F]/
12
17
  POSITIONS = %i[host base_url header param].freeze
18
+ SEGMENTS_RULE = 'must be one or more segments, none of them empty, "." or "..": ' \
19
+ 'no slash at the start or at the end, and no two in a row'
13
20
 
14
21
  # value as one segment of a path: what base_url and the path of an
15
22
  # endpoint do with the value of a variable.
@@ -22,12 +29,24 @@ module ApiRecipes
22
29
  PathTemplate.escape(text)
23
30
  end
24
31
 
32
+ # value as several segments of a path, for a {*name}: split on '/', each
33
+ # piece encoded as one segment, the slashes kept. A piece that is empty,
34
+ # "." or ".." raises, so the value never climbs or leaves the path.
35
+ def self.segments(value, name, api)
36
+ pieces = value.nil? ? [''] : value.to_s.split('/', -1)
37
+ pieces = [''] if pieces.empty?
38
+ raise InvalidVariable.new(api, name, SEGMENTS_RULE) if pieces.any? { |piece| ['', '.', '..'].include?(piece) }
39
+
40
+ pieces.map { |piece| PathTemplate.escape(piece) }.join('/')
41
+ end
42
+
25
43
  def initialize(string, position)
26
44
  raise ArgumentError, "unknown template position '#{position}'" unless POSITIONS.include?(position)
27
45
 
28
46
  @string = string.to_s.dup.freeze
29
47
  @position = position
30
- @names = @string.scan(VARIABLE).flatten.map(&:to_sym).uniq.freeze
48
+ @names = (position == :base_url ? @string.scan(PATH_VARIABLE).map(&:last) : @string.scan(VARIABLE).flatten)
49
+ .map(&:to_sym).uniq.freeze
31
50
  freeze
32
51
  end
33
52
 
@@ -51,6 +70,8 @@ module ApiRecipes
51
70
  end
52
71
 
53
72
  def expand(values, api:)
73
+ return expand_path(values, api) if @position == :base_url
74
+
54
75
  @string.gsub(VARIABLE) do
55
76
  name = Regexp.last_match(1).to_sym
56
77
  raise MissingVariable.new(api, name) unless values.key?(name)
@@ -61,6 +82,16 @@ module ApiRecipes
61
82
 
62
83
  private
63
84
 
85
+ def expand_path(values, api)
86
+ @string.gsub(PATH_VARIABLE) do
87
+ star = !Regexp.last_match(1).empty?
88
+ name = Regexp.last_match(2).to_sym
89
+ raise MissingVariable.new(api, name) unless values.key?(name)
90
+
91
+ star ? self.class.segments(values[name], name, api) : self.class.segment(values[name], name, api)
92
+ end
93
+ end
94
+
64
95
  def encode(value, name, api)
65
96
  text = value.to_s
66
97
  bytes = text.b
@@ -68,7 +99,6 @@ module ApiRecipes
68
99
  when :host
69
100
  reject(api, name, 'must contain only letters, digits, dots, hyphens and underscores') unless HOST_VALUE.match?(bytes)
70
101
  text
71
- when :base_url then self.class.segment(value, name, api)
72
102
  # http.rb encodes the name and the value of a query parameter.
73
103
  when :param then text
74
104
  else
@@ -8,19 +8,31 @@ module ApiRecipes
8
8
  extend Forwardable
9
9
 
10
10
  KEY_PATTERN = /\A[a-z_][A-Za-z0-9_]*\z/
11
+ BLANK = /\A[ \t\r\n]*\z/
12
+ BLANK_BYTES = " \t\r\n".bytes.freeze
13
+ PLAIN_TYPE = %r{\A[A-Za-z0-9._+/-]+\z}
14
+ TYPE_LIMIT = 100
15
+ TYPE_ADVICE = 'Set mime_type on the endpoint or on the api, or read response.body.to_s'
16
+ JSON_TYPE = 'application/json'
17
+ JSON_SUFFIX = '+json'
18
+ # A type and a subtype in lower case, with the characters of RFC 6838.
19
+ TYPE_NAME = %r{\A[a-z0-9!\#$&^_.+-]+/[a-z0-9!\#$&^_.+-]+\z}
11
20
 
12
21
  attr_reader :original_response
13
22
 
14
23
  # Public instance methods of HTTP::Response (http.rb 6) except request and
15
- # deconstruct_keys, which would show the request, and uri and inspect,
16
- # which are defined here.
24
+ # deconstruct_keys, which would show the request, and uri, inspect, parse
25
+ # and flush, which are defined here.
17
26
  def_delegators :@original_response,
18
27
  :body, :charset, :chunked?, :code, :connection, :content_length, :content_type,
19
- :cookies, :deconstruct, :flush, :headers, :mime_type, :parse, :proxy_headers,
28
+ :cookies, :deconstruct, :headers, :mime_type, :proxy_headers,
20
29
  :readpartial, :reason, :status, :to_a, :to_s, :to_str, :version
21
30
 
22
- def initialize(http_response, mime_type: nil, success: nil, hidden_param: nil)
31
+ # path: the path of the request, for the error of data. Never the address,
32
+ # which can hold a credential in its query string.
33
+ def initialize(http_response, mime_type: nil, success: nil, hidden_param: nil, path: nil)
23
34
  @original_response = http_response
35
+ @path = path
24
36
  @mime_type = mime_type
25
37
  @success = success
26
38
  @hidden_param = hidden_param&.to_s
@@ -30,11 +42,29 @@ module ApiRecipes
30
42
  def data
31
43
  return @data if @parsed
32
44
 
33
- @data = @original_response.parse(@mime_type)
45
+ @data = read(@mime_type)
34
46
  @parsed = true
35
47
  @data
36
48
  end
37
49
 
50
+ # Reads the body as data does, with the given type when there is one, and
51
+ # keeps nothing. The parse of http.rb is not forwarded: its error quotes
52
+ # the body.
53
+ def parse(type = nil)
54
+ case type
55
+ when NilClass then read(@mime_type)
56
+ when String, Symbol then read(type.empty? ? @mime_type : type)
57
+ else raise ArgumentError, 'the type given to parse must be a String or a Symbol'
58
+ end
59
+ end
60
+
61
+ # Reads the whole body, as the flush of http.rb does, and returns this
62
+ # response: the one of http.rb holds the request.
63
+ def flush
64
+ @original_response.flush
65
+ self
66
+ end
67
+
38
68
  def success?
39
69
  return @success unless @success.nil?
40
70
 
@@ -63,8 +93,10 @@ module ApiRecipes
63
93
  filled
64
94
  end
65
95
 
96
+ # The type is text of the server, shown as in the error of data.
66
97
  def inspect
67
- "#<#{self.class.name} #{status} #{mime_type}>"
98
+ type = server_type
99
+ "#<#{[self.class.name, status, type && shown_type(type, quote: '')].compact.join(' ')}>"
68
100
  end
69
101
 
70
102
  # The http.rb response holds the request, with its credential: a Response
@@ -79,6 +111,93 @@ module ApiRecipes
79
111
 
80
112
  private
81
113
 
114
+ # nil for an empty body, whatever its type. given is the type to read it
115
+ # with, nil for the one of the response. An error of http.rb about the
116
+ # body is not raised as it is, and is not kept as the cause: its message
117
+ # quotes the body.
118
+ def read(given)
119
+ return nil if blank?(body_text)
120
+
121
+ type = given || server_type
122
+ @original_response.parse(parser_type(type) || '')
123
+ rescue HTTP::ParseError => e
124
+ raise unreadable(*parse_problem(e, type)), cause: nil
125
+ end
126
+
127
+ # JSON has one parser in http.rb, under one name: a JSON type that
128
+ # http.rb has no parser for is read with that one. A parser that the
129
+ # application registered for the type, as it is written or in lower
130
+ # case, is left to read it.
131
+ def parser_type(type)
132
+ name = json_name(type)
133
+ return type unless name
134
+
135
+ [type, name].find { |known| parser?(known) } || JSON_TYPE
136
+ end
137
+
138
+ def parser?(type)
139
+ HTTP::MimeType[type]
140
+ true
141
+ rescue HTTP::UnsupportedMimeTypeError
142
+ false
143
+ end
144
+
145
+ # type in lower case when it is application/json or has the +json suffix
146
+ # (application/problem+json), nil otherwise: also for the text http.rb
147
+ # makes of a repeated header, which is not the name of a type.
148
+ def json_name(type)
149
+ return nil unless type.is_a?(String) || type.is_a?(Symbol)
150
+
151
+ name = type.to_s.b.downcase
152
+ name if TYPE_NAME.match?(name) && (name == JSON_TYPE || name.end_with?(JSON_SUFFIX))
153
+ end
154
+
155
+ # The Content-Type of the response as the gem reads it and shows it: each
156
+ # value of the header without its parameters, in lower case, as bytes.
157
+ # nil when there is none. http.rb gives a repeated header, and one with
158
+ # a slash in a parameter, as one text with the parameters in it.
159
+ def server_type
160
+ values = Array(@original_response.headers['Content-Type'])
161
+ .map { |value| value.to_s.b.split(';', 2).first.to_s.strip.downcase }.reject(&:empty?)
162
+ values.empty? ? nil : values.join(', ')
163
+ end
164
+
165
+ # An error of the network while the body arrives is let through. After
166
+ # one, as after readpartial, http.rb no longer gives the body.
167
+ def body_text
168
+ @original_response.body.to_s
169
+ rescue HTTP::StateError
170
+ raise unreadable('the body is no longer available: it was read in parts, or reading it failed',
171
+ 'Read data before readpartial'), cause: nil
172
+ end
173
+
174
+ # The first byte is looked at before the bytes are copied: a body that has
175
+ # something to read is not copied.
176
+ def blank?(text)
177
+ text.empty? || (BLANK_BYTES.include?(text.getbyte(0)) && BLANK.match?(text.b))
178
+ end
179
+
180
+ # type is nil when the response names none.
181
+ def parse_problem(error, type)
182
+ return ["the body is not valid #{shown_type(type)}", 'Read response.body.to_s'] unless
183
+ error.cause.is_a?(HTTP::UnsupportedMimeTypeError)
184
+ return ['it has a body and no content type', TYPE_ADVICE] if type.to_s.empty?
185
+
186
+ ["the content type #{shown_type(type)} has no parser", TYPE_ADVICE]
187
+ end
188
+
189
+ # The type is text of the server: only its first bytes are shown, as they
190
+ # are when they are the characters of a type, escaped otherwise.
191
+ def shown_type(type, quote: "'")
192
+ bytes = type.to_s.b
193
+ bytes = "#{bytes[0, TYPE_LIMIT]}..." if bytes.bytesize > TYPE_LIMIT
194
+ PLAIN_TYPE.match?(bytes) ? "#{quote}#{bytes}#{quote}" : bytes.inspect
195
+ end
196
+
197
+ def unreadable(reason, advice)
198
+ UnreadableResponse.new(@path, self, reason, advice)
199
+ end
200
+
82
201
  def hidden_pair?(pair)
83
202
  name = pair.split('=', 2).first.to_s
84
203
  name == @hidden_param || URI.decode_www_form_component(name) == @hidden_param
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ApiRecipes
4
- VERSION = '3.0.0.beta5'
4
+ VERSION = '3.0.0.beta6'
5
5
  end
data/lib/api_recipes.rb CHANGED
@@ -6,6 +6,7 @@ require 'api_recipes/version'
6
6
  require 'api_recipes/errors'
7
7
  require 'api_recipes/internals/credential'
8
8
  require 'api_recipes/internals/level'
9
+ require 'api_recipes/internals/origins'
9
10
  require 'api_recipes/internals/path_template'
10
11
  require 'api_recipes/internals/template'
11
12
  require 'api_recipes/internals/option_value'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: api_recipes
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.0.0.beta5
4
+ version: 3.0.0.beta6
5
5
  platform: ruby
6
6
  authors:
7
7
  - Alessandro Verlato
@@ -91,6 +91,7 @@ files:
91
91
  - lib/api_recipes/internals/handles.rb
92
92
  - lib/api_recipes/internals/level.rb
93
93
  - lib/api_recipes/internals/option_value.rb
94
+ - lib/api_recipes/internals/origins.rb
94
95
  - lib/api_recipes/internals/path_template.rb
95
96
  - lib/api_recipes/internals/plain_yaml.rb
96
97
  - lib/api_recipes/internals/recipe.rb