restep 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f1dd6df74be0e17804e1aac5596ac33ea98762adf71305a8c659fd9400eab877
4
- data.tar.gz: e487df908fc5b0b8b18b53450561d8951e56c450ede07f1807f35fd851d7a704
3
+ metadata.gz: 9e7b06b1cd991828aa4ddb9d0236ac1ee4a5b64287efe083e56a3551e07d153b
4
+ data.tar.gz: 88833bf7d9f2146dfef7402b82e79f159cd817726a2249944cb4256f844b0c83
5
5
  SHA512:
6
- metadata.gz: cd0164a4557516e8309c49b5d6714fce04544228474f10632fc1c94322f81f55da874f7d7231e065bb87c5dda52e3de09ff6d0fce1b639bc3856b6ab94e6507f
7
- data.tar.gz: 596a57114b830cd5b2ce6b1323171ed130a3e54d53832d7c0256b19bbf2a378312015c2cdf19c02125aaebdfa230921986dd7f915150bbf9407551b95fd2607f
6
+ metadata.gz: 60a09fa5352c465a8e95495e7b924fe2ef0c461b42ba684ef560b7c4082a7dc3f858f724f98b9ccc4b1da40456287bd89b3f703678af3186ef5894b20f08f7f9
7
+ data.tar.gz: 7a7f02fb8994b5643c731c270271ad6a6e9f97458836e323a849bb129edbfe4b4661c9e24b7f5e404fcd2b25649a792da4f85e05df2316783b4ded29a2b30ed0
data/README.md CHANGED
@@ -167,7 +167,8 @@ require "restep/rails" # the concern, restep_action routes and the railtie
167
167
 
168
168
  config.middleware.delete Rack::ETag # Restep sets its own validators
169
169
  config.middleware.delete Rack::ConditionalGet
170
- config.middleware.insert_before 0, Restep::Envelope, cors: false, credentials: true # a same-origin, cookie API
170
+ config.middleware.insert_before 0, Restep::Envelope, cors: false, credentials: true, # a same-origin, cookie API
171
+ path: "/v1" # only the API: the app's HTML pages keep their params
171
172
  config.exceptions_app = Restep::Rails::Controller.exceptions_app
172
173
 
173
174
  # app/controllers/drafts_controller.rb: any route shape, nested or not
@@ -228,8 +229,9 @@ served as written, and every request is answered by what it declares.
228
229
  | Principal (§2) | `c.principal = ->(request) { ... }` returns who the request acts for, a string, or `nil` for the anonymous principal. Idempotency keys and cursors belong to it, and reads become `Cache-Control: private` (§5.1). `c.idempotency_anonymous = false` refuses `Idempotency-Key` without one (§7.1) |
229
230
  | Cursor secret (§6.4) | `c.cursor_secret` (or `RESTEP_CURSOR_SECRET`; in Rails, derived from `secret_key_base`). Never generated: one per process would break cursors across replicas, so `Restep.check!` fails without it |
230
231
  | Body limit | `c.max_body_bytes`, or `max_body_bytes:` on one collection |
231
- | CORS (§5.8) | `use Restep::Envelope` (`cors: "*"`, the default), `cors: false` for a same-origin API, or `cors: ["https://editor.example"]` to name origins, with `Vary: Origin`. With `credentials: true` (cookies), unsafe requests a browser sends from any other origin get 403, as §5.8 requires; allowed origins also get `Access-Control-Allow-Credentials` |
232
- | Idempotency store (§7.1) | `c.idempotency_model = "IdempotencyKey"` (PostgreSQL table, see `Restep::Idempotency::ActiveRecordStore`), or `c.idempotency_store = Restep::Idempotency::MemoryStore.new` for one process |
232
+ | CORS (§5.8) | `use Restep::Envelope` (`cors: "*"`, the default), `cors: false` for a same-origin API, or `cors: ["https://editor.example"]` to name origins, with `Vary: Origin`. With `credentials: true` (cookies), unsafe requests a browser sends from any other origin get 403, as §5.8 requires; allowed origins also get `Access-Control-Allow-Credentials`. `exempt: ->(env) { ... }` names the requests the application authenticates only with a token a browser never attaches on its own, which §5.8 does not cover: `exempt: Restep::Envelope.method(:token_authorization?)` takes any `Authorization` scheme but Basic, Digest, Negotiate and NTLM |
233
+ | Where the API is | `path: "/v1"` (or a list) on `Restep::Envelope`: only requests under it get the envelope (501, profile link, CORS, the origin check, and Rails' parameter parsing turned off); the rest of the application is left untouched |
234
+ | Idempotency store (§7.1) | `c.idempotency_model = "IdempotencyKey"` (PostgreSQL table, see `Restep::Idempotency::ActiveRecordStore`), or `c.idempotency_store = Restep::Idempotency::MemoryStore.new` for one process. `Restep::Idempotency::ActiveRecordStore.new("IdempotencyKey", unique_by: ..., purge_every: 3600)`: the unique index on `(principal, http_method, path, key)` is found by its columns (or pass its name), and every expired key is deleted once per `purge_every` seconds (`nil`: never; call `store.purge` from a job) |
233
235
 
234
236
  ## Relations and language maps
235
237
 
@@ -257,6 +259,30 @@ well-formed and lowercase, `type`, `unknown` for a language the field does not t
257
259
  in a `PATCH` (`null` deletes a translation, `{"title": null}` empties it), declared in
258
260
  `language_maps`, and filtered or sorted by translation (`"title.es-es" => { "type" => "string", ... }`).
259
261
 
262
+ ## Documents: object and array fields
263
+
264
+ A field may hold any JSON object or array that the item carries (§3, §4.3): its shape goes in the
265
+ `schemas` of discovery, never in the types of §4.2, which are for filters.
266
+
267
+ ```ruby
268
+ Restep::Fields.f(name: "layout", type: "object", nullable: true,
269
+ schema: { "properties" => { "columns" => { "type" => "integer" } } }, # merged into {"type": "object"}
270
+ validate: ->(value, pointer) { value["columns"].is_a?(Integer) ? nil : [{ "pointer" => "#{pointer}/columns", "code" => "type", "detail" => "An integer." }] })
271
+ Restep::Fields.f(name: "tags", type: "array", default: [], schema: { "items" => { "type" => "string" } })
272
+ ```
273
+
274
+ - A body's value is checked as an I-JSON message: a string (or a member name) with U+0000 or a
275
+ noncharacter gives `422` with a `format` entry at that string (at `""` for a member name), and a
276
+ number a double cannot hold without losing digits gives `range`; it is never rounded. Numbers
277
+ with a fraction are stored as `Float`, integers stay exact.
278
+ - In a `PATCH`, an object merges member by member (RFC 7396: `null` deletes a member) and is then
279
+ validated whole; an array is replaced. A value equal as JSON to the current one changes nothing.
280
+ - `validate:` runs on the value after its type (and, in a `PATCH`, after merging) and returns the
281
+ `422` entries, or `nil`. It works on any field.
282
+ - The update schema gives an object field only its type, since a merge patch may leave any member
283
+ out or set it to `null`. A filter or sort key never names the whole field: declare a dotted path to
284
+ a member (`layout.columns`) with its own `sql:` or `value:` (§6.1).
285
+
260
286
  ## API
261
287
 
262
288
  ### `Restep::Collection.new`
@@ -266,7 +292,7 @@ in a `PATCH` (`null` deletes a translation, `{"title": null}` empties it), decla
266
292
  | `name`, `path`, `description` | Name in discovery, path relative to the API root (a URI template for a subcollection), description |
267
293
  | `parent` | For a subcollection, or a singleton under an item: the collection (or singleton) it hangs from |
268
294
  | `model` or `source` | An Active Record model (or its name), or any `Restep::Source` |
269
- | `fields` | `Restep::Fields.f(name:, type:, ...)`: `column`, `values`, `nullable`, `required`, `default`, `read_only` (a field only the server sets, other than `id`: a POST ignores it whatever its value, a PATCH accepts only its current value, §5.1), `max_length`, `pattern`, `range`, `scale`, `relation`, `include`, `languages`, `description`. Types: `id`, `string`, `enum`, `integer`, `decimal` (with `scale`), `boolean`, `date`, `datetime`, `relation`, `language_map` |
295
+ | `fields` | `Restep::Fields.f(name:, type:, ...)`: `column`, `values`, `nullable`, `required`, `default`, `read_only` (a field only the server sets, other than `id`: a POST ignores it whatever its value, a PATCH accepts only its current value, §5.1), `max_length`, `pattern`, `range`, `scale`, `relation`, `include`, `languages`, `schema` (object and array fields), `validate`, `description`. Types: `id`, `string`, `enum`, `integer`, `decimal` (with `scale`), `boolean`, `date`, `datetime`, `relation`, `language_map`, `object`, `array` |
270
296
  | `filters` | `{ "field" => { "type", "ops" } }` plus how to run it: `sql:` (Active Record), `value:` (computed); `"required" => true` for a filter every list request must carry (§6.1). Operators: `eq`, `ne`, `lt`, `le`, `gt`, `ge`, `in`, `nin`, `null`, and `prefix` and `contains` on strings (by code points) |
271
297
  | `named_filters` | `{ "name" => { "description", sql: ->(value) { ["SQL ?", value] } } }`, or `match: ->(record, value) { ... }` on a computed source (§6.1); a switch (no `"type"`) may declare `"default" => true`, and any named filter `"required" => true` |
272
298
  | `sort` | `{ "field" => { sql: "column", type: "string" } }` (`{}` takes the field's column and type) |
@@ -284,12 +310,31 @@ in a `PATCH` (`null` deletes a translation, `{"title": null}` empties it), decla
284
310
  `GET`, a safe one is also idempotent, `new` is reserved for the safe `GET` collection action that
285
311
  gives the starting values of a new item, `changes` is reserved, and `effects` takes `destroys`,
286
312
  `external` and `charges` (a safe action, only `charges`). `output` is the schema of a safe action's
287
- result. At run time:
313
+ result. At run time, what each kind answers is what §11.1 allows, and anything else is a 500, as a
314
+ programming error:
315
+
316
+ - an unsafe item action's `run` changes the item, and the gem answers 200 with the item, its new
317
+ `ETag` and `Content-Location`, or, with `Prefer: return=minimal`, 204 without `ETag`. If `run`
318
+ returns `Restep::Created.new(location)` (or `Restep::Created.new(location, body)`), the answer is
319
+ 201 with that `Location`, such as a new version; if it returns `Restep::NO_CONTENT`, 204;
320
+ - an unsafe collection action's `run` returns `Restep::Created.new(location)` (201 with `Location`)
321
+ or `[204, nil]`: a collection has no representation of its own, so never 200, and a 201 always
322
+ carries the `Location` of what it created;
323
+ - a safe action's `run` returns `[status, result]`: 200 with the result (on a collection, only with a
324
+ declared `output`), or `[204, nil]`; never 201. With `GET` it is a read, with `ETag` and 304. A safe
325
+ action may use `POST` to take an `input` in its body: that is the way to compute something from
326
+ data the client sends (a diff, a quote), whose 200 is `no-store`, after `If-Match` against the item
327
+ (412) and before the input's 422;
328
+
329
+ ```ruby
330
+ Restep::Fields.action("diff", on: "item", safe: true, idempotent: true, # POST /drafts/7:diff
331
+ input: [Restep::Fields.f(name: "with", type: "object", required: true)],
332
+ output: { "type" => "object" },
333
+ run: ->(draft, input) { [200, draft.diff(input["with"])] })
334
+ Restep::Fields.action("publish", on: "item", effects: [], # POST /drafts/7:publish
335
+ run: ->(draft, _) { Restep::Created.new(Restep.url("/versions/#{draft.publish!.id}")) })
336
+ ```
288
337
 
289
- - an item action's `run` changes the item, and the gem answers 200 with the item, its new `ETag` and
290
- `Content-Location`, or, with `Prefer: return=minimal`, 204 without `ETag`;
291
- - a collection action's `run` returns `[status, body]`: an unsafe one answers 201 or 204, a safe one
292
- 200 only with a declared `output` (anything else is a 500, as a programming error);
293
338
  - an action declared `idempotent: true` ignores `Idempotency-Key`, a malformed one too;
294
339
  - a `GET` action takes no `params`, so it answers any query parameter with `400
295
340
  unsupported_parameter` (§5.3, §11.1);
@@ -319,6 +364,11 @@ gives `invalid_parameter` too, with the limit in `detail`.
319
364
  | `Restep::Problem` | A Restep error; `raise Restep::Problem.new(409, "conflict", reason: "...", detail: "...")`. The codes are the closed table of §5.4 (`Restep::Problem::CODES`); a status it does not list takes `http_` and its digits, and a code that does not go with its status raises `ArgumentError`. Every problem is `no-store` |
320
365
  | `Restep::Rules`, `Restep::Discovery` | The rules of draft 7 for a discovery document, its JSON Schema, and the document itself |
321
366
  | `Restep::Query`, `Restep::Cursor`, `Restep::Conditional`, `Restep::Idempotency`, `Restep::Parents` | Query parsing, encrypted cursor, preconditions, idempotency, the parents of a request |
367
+ | `Restep::Body` | `parse(raw, decimal_class: BigDecimal)` parses a raw body as an I-JSON message (400, or an `Unpaired` whose 422 `object!` raises), with no `Restep::Request`; `media_type!(content_type, types)` gives the 415; `read(request, types, accept_ok:, decimal_class:)` does both for anything with `raw_body` and `content_type`; `object!` gives the 422 of a body that is not an object. `decimal_class: nil` gives `Float` |
368
+ | `Restep::Conditional` | `parse(name, value)` gives `:any`, a list of entity tags or 400; an empty header is an empty list (RFC 9110 §5.6.1), which no ETag matches. `evaluate(if_match, if_none_match, etag, safe:)` gives `nil`, `:not_modified` or 412 |
369
+ | `Restep::QueryString` | `parse(query_string)` keeps repeated names and brackets as received; a `%` that starts no escape gives 400 (RFC 3986 §2.1). `well_formed?`, `decode` |
370
+ | `Restep::MergePatch` | `apply(target, patch)`: JSON Merge Patch (RFC 7396) |
371
+ | `Restep::Created`, `Restep::NO_CONTENT` | What an action's `run` returns for a 201 with `Location`, or a 204 |
322
372
 
323
373
  ## Namespace
324
374
 
data/lib/restep/body.rb CHANGED
@@ -40,58 +40,74 @@ module Restep
40
40
  # Returns the body's JSON value (an object or not: see object!) or raises 415, 413 or 400, in
41
41
  # that order. Before the 413, the 406 has to be checked, as it comes first in §5.4: the caller
42
42
  # does it by passing accept_ok.
43
+ # request: anything with raw_body and content_type (a Restep::Request, or an object of the
44
+ # application's own).
43
45
  # empty_is_object: §11.1, a POST action takes an empty body, with or without Content-Type,
44
46
  # as "{}" sent as application/json.
45
47
  # max_bytes: the largest body (Restep.config.max_body_bytes, or the collection's own).
46
- def read(request, allowed_types, accept_ok:, empty_is_object: false, max_bytes: MAX_BYTES)
48
+ # decimal_class: what a number with a fraction or an exponent becomes (see parse).
49
+ def read(request, allowed_types, accept_ok:, empty_is_object: false, max_bytes: MAX_BYTES, decimal_class: BigDecimal)
47
50
  raw = request.raw_body
48
51
  if empty_is_object && raw.empty?
49
52
  raise not_acceptable unless accept_ok
50
53
  return {}
51
54
  end
52
- mt = media_type(request.content_type)
53
55
  # §3 (draft 6): an empty body is also a body; without Content-Type it gives 415, and empty
54
- # with application/json, 400 (JSON.parse rejects it further down).
55
- if mt.nil? || !allowed_types.include?(mt[0]) || (mt[1] && mt[1] != "utf-8")
56
- raise Problem.new(415, "unsupported_media_type",
57
- detail: "Send the body as #{allowed_types.join(" or ")} (UTF-8).",
58
- headers: allowed_types.include?("application/merge-patch+json") ? { "accept-patch" => "application/merge-patch+json, application/json" } : {})
59
- end
56
+ # with application/json, 400 (parse rejects it).
57
+ media_type!(request.content_type, allowed_types)
60
58
  if raw.bytesize > max_bytes
61
59
  raise not_acceptable unless accept_ok
62
60
  raise Problem.new(413, "content_too_large", detail: "The body takes at most #{max_bytes} bytes.")
63
61
  end
64
- raise Problem.new(400, "bad_request", detail: "The request needs a JSON object as its body.") if raw.empty?
62
+ doc = parse(raw, decimal_class: decimal_class)
63
+ # §5.1 and §4.3: a JSON value that is not an object is kept as is; it gives 422 through
64
+ # object!, which the operation calls after the preconditions (§5.4: the 412 comes before the
65
+ # content's 422).
66
+ raise not_acceptable unless accept_ok
67
+ doc
68
+ end
69
+
70
+ # §3: the media type of a body, or 415 unsupported_media_type. Only allowed_types, with no
71
+ # charset or charset=utf-8. Returns [type, charset].
72
+ def media_type!(content_type, allowed_types)
73
+ mt = media_type(content_type)
74
+ return mt unless mt.nil? || !allowed_types.include?(mt[0]) || (mt[1] && mt[1] != "utf-8")
75
+ raise Problem.new(415, "unsupported_media_type",
76
+ detail: "Send the body as #{allowed_types.join(" or ")} (UTF-8).",
77
+ headers: allowed_types.include?("application/merge-patch+json") ? { "accept-patch" => "application/merge-patch+json, application/json" } : {})
78
+ end
79
+
80
+ # §3: parses a raw body (a String of bytes) as an I-JSON message, with no media type or size
81
+ # check (media_type! and read do those). Returns its JSON value, which may not be an object
82
+ # (object! decides), or an Unpaired for a body with an unpaired surrogate, whose 422 object!
83
+ # raises. Raises 400 bad_request for an empty body, one that is not UTF-8 or not JSON, or one
84
+ # that repeats a member name.
85
+ # decimal_class: BigDecimal (the default) keeps every number with a fraction or an exponent
86
+ # exact, as §2 compares numbers ("equal as JSON values"); nil gives Float, as JSON.parse does.
87
+ # Integers are always Integer.
88
+ def parse(raw, decimal_class: BigDecimal)
89
+ raise Problem.new(400, "bad_request", detail: "The request needs a JSON object as its body.") if raw.nil? || raw.empty?
65
90
  raw = raw.dup.force_encoding(Encoding::UTF_8)
66
91
  raise Problem.new(400, "bad_request", detail: "The body is not valid UTF-8.") unless raw.valid_encoding?
92
+ options = { allow_nan: false, allow_duplicate_key: false }
93
+ options[:decimal_class] = decimal_class if decimal_class
67
94
  # §3 (draft 7): a body is an I-JSON message. Duplicate member names give 400 bad_request,
68
95
  # because the meaning would depend on the parser; an unpaired surrogate, which the parser
69
96
  # refuses, gives the 422 invalid with a format entry that §3 allows.
70
- doc = begin
71
- JSON.parse(raw, decimal_class: BigDecimal, allow_nan: false, allow_duplicate_key: false)
72
- rescue JSON::ParserError => e
73
- unpaired = nil
74
- message = e.message.lines.first.to_s.strip
75
- if message.include?("duplicate key")
76
- raise Problem.new(400, "bad_request", detail: "The body repeats a member name in an object: #{message[0, 120]}")
77
- end
78
- # Deferred like a body that is not an object: object! raises it after the preconditions
79
- # (§5.4: no 422 from the content while 412 applies).
80
- if message.include?("surrogate")
81
- # §3 and §5.4 (draft 7): a body that also has a JSON syntax error (or a duplicate member
82
- # name) gets 400 bad_request. The parser stops at the first surrogate, so the rest is
83
- # checked again with the unpaired ones replaced.
84
- syntax_error!(raw)
85
- unpaired = Unpaired.new(Problem.invalid([{ "pointer" => "", "code" => "format", "detail" => "The body has an unpaired surrogate." }],
86
- detail: "The body is not an I-JSON message: it has an unpaired surrogate."))
87
- end
88
- unpaired or raise Problem.new(400, "bad_request", detail: "The body is not valid JSON: #{message[0, 120]}")
97
+ JSON.parse(raw, **options)
98
+ rescue JSON::ParserError => e
99
+ message = e.message.lines.first.to_s.strip
100
+ if message.include?("duplicate key")
101
+ raise Problem.new(400, "bad_request", detail: "The body repeats a member name in an object: #{message[0, 120]}")
89
102
  end
90
- # §5.1 and §4.3: a JSON value that is not an object is kept as is; it gives 422 through
91
- # object!, which the operation calls after the preconditions (§5.4: the 412 comes before the
92
- # content's 422).
93
- raise not_acceptable unless accept_ok
94
- doc
103
+ raise Problem.new(400, "bad_request", detail: "The body is not valid JSON: #{message[0, 120]}") unless message.include?("surrogate")
104
+ # Deferred like a body that is not an object: object! raises it after the preconditions
105
+ # (§5.4: no 422 from the content while 412 applies). §3 and §5.4 (draft 7): a body that also
106
+ # has a JSON syntax error (or a duplicate member name) gets 400 bad_request. The parser stops
107
+ # at the first surrogate, so the rest is checked again with the unpaired ones replaced.
108
+ syntax_error!(raw)
109
+ Unpaired.new(Problem.invalid([{ "pointer" => "", "code" => "format", "detail" => "The body has an unpaired surrogate." }],
110
+ detail: "The body is not an I-JSON message: it has an unpaired surrogate."))
95
111
  end
96
112
 
97
113
  # A \u escape of a surrogate pair, of a lone surrogate, or any other escape (so that "\\ud800",
@@ -11,17 +11,32 @@ module Restep
11
11
  # With a hand-written discovery document (Restep.config.discovery), what discovery declares
12
12
  # (path, parent, description, filter, sort, max_limit...) may be left out here: the document
13
13
  # fills it in, and Restep.check! fails on anything the code contradicts.
14
+ # What an action's run returns to answer other than with its default (§11.1, draft 7):
15
+ # Restep::Created.new(location) # 201 with the Location of what it created (absolute path)
16
+ # Restep::Created.new(location, body) # the same with a JSON object as its body
17
+ # Restep::NO_CONTENT # 204, on an item or a singleton
18
+ Created = Struct.new(:location, :body)
19
+ NoContent = Class.new
20
+ NO_CONTENT = NoContent.new.freeze
21
+
14
22
  class Collection
15
23
  Field = Struct.new(:name, :type, :column, :values, :nullable, :required, :default, :read_only,
16
24
  :max_length, :pattern, :range, :scale, :relation, :description, :include,
17
- :languages, keyword_init: true)
25
+ :languages, :schema, :validate, keyword_init: true)
18
26
 
19
27
  # An action (§11.1). on: "item" or "collection"; method: "POST" or "GET" (only safe ones);
20
28
  # input: body fields (Fields.f), or nil. available: whether the item's state allows it
21
29
  # (what _actions lists); unavailable: the 409 it gives if not. run: the effect, which gets
22
30
  # the item (or, in a collection action, the source's scope for the parents: an Active Record
23
- # relation for Restep::Sources::ActiveRecord) and the validated input. In an item action, the
24
- # response is the re-read item; in a collection one, run returns [status, JSON object or nil].
31
+ # relation for Restep::Sources::ActiveRecord) and the validated input. §11.1 (draft 7) fixes
32
+ # what each kind answers:
33
+ # - unsafe, on an item: the re-read item (200), unless run returns Restep::Created (201 with
34
+ # Location) or Restep::NO_CONTENT (204);
35
+ # - unsafe, on a collection: run returns Restep::Created (201 with Location) or [204, nil];
36
+ # never 200, since a collection has no representation of its own;
37
+ # - safe, with GET or POST: run returns [status, result or nil]; a result (200) needs a
38
+ # declared output on a collection, and nil answers 204. A safe POST action takes an input,
39
+ # so it is how a client asks for a computed result from data in a body (a diff, a quote).
25
40
  # effects: what a person may want to approve first (§11.1, draft 7), a list out of destroys,
26
41
  # external and charges, or nil to leave it undeclared. output: the JSON Schema of a safe
27
42
  # action's result, which is not a representation; a safe action without output answers its
@@ -149,9 +164,22 @@ module Restep
149
164
  end
150
165
  end
151
166
  raise ArgumentError, "#{name}: #{f.name}: include is for relation fields (9)" if !f.include.nil? && f.type != "relation"
167
+ raise ArgumentError, "#{name}: #{f.name}: schema is for object and array fields (4.3)" if f.schema && !JSON_TYPES.include?(f.type)
168
+ raise ArgumentError, "#{name}: #{f.name}: validate takes ->(value, pointer) { [errors] or nil }" if f.validate && !f.validate.respond_to?(:call)
169
+ end
170
+ # §4.2 and §6.1: an object or array has no type of the discovery list, so it is filtered and
171
+ # sorted by a dotted path to a scalar inside it (address.city), never whole.
172
+ (filters.keys + sort.keys).each do |k|
173
+ if JSON_TYPES.include?(fields[k]&.type)
174
+ raise ArgumentError, "#{name}: #{k} is of type #{fields[k].type}: filter or sort by a member, such as #{k}.name, with its own sql: or value: (6.1)"
175
+ end
152
176
  end
153
177
  end
154
178
 
179
+ # Fields whose value is any JSON object or array (a document the item carries): their shape
180
+ # goes in the schemas (§4.3), never in the types of discovery (§4.2).
181
+ JSON_TYPES = %w[object array].freeze
182
+
155
183
  # ---- Paths ----------------------------------------------------------------------------------
156
184
 
157
185
  # The collection that holds this one's parent items (a singleton's parent may be a singleton).
@@ -372,6 +400,10 @@ module Restep
372
400
  # §3: merged by key, validated first (deleted keys too); left as it was, it changes nothing.
373
401
  merged = Language.merge(f, current[k] || {}, v, ptr, errors)
374
402
  changes[f.column] = merged unless merged == :error || merged == (current[k] || {})
403
+ elsif f.type == "object" && v.is_a?(Hash)
404
+ # §5.1: a merge patch (RFC 7396) merges an object member by member.
405
+ val = coerce(f, MergePatch.apply(current[k], v), ptr, errors)
406
+ changes[f.column] = val unless val == :error || Types.canonical_json(val) == Types.canonical_json(current[k])
375
407
  elsif f.type == "relation" && current_relation?(f, v, current[k])
376
408
  # Relation with its current value: ignored without checking that the target exists
377
409
  # (§5.1); only href, if present, is checked to be that item's path.
@@ -385,7 +417,8 @@ module Restep
385
417
  else
386
418
  val = coerce(f, v, ptr, errors)
387
419
  next if val == :error
388
- changes[f.column] = val unless same_value?(source.value(rec, f.column), val)
420
+ same = JSON_TYPES.include?(f.type) ? Types.canonical_json(val) == Types.canonical_json(current[k]) : same_value?(source.value(rec, f.column), val)
421
+ changes[f.column] = val unless same
389
422
  end
390
423
  end
391
424
  raise Problem.invalid(errors) unless errors.empty?
@@ -446,7 +479,18 @@ module Restep
446
479
  a && a == Types.parse_datetime(current)
447
480
  end
448
481
 
482
+ # The value of a field in a request body, checked against its type and then against the
483
+ # field's own validate: hook, or :error with the 422 entries added to errors.
449
484
  def coerce(f, v, ptr, errors)
485
+ val = coerce_type(f, v, ptr, errors)
486
+ return val if val == :error || f.validate.nil?
487
+ found = Array(f.validate.call(val, ptr))
488
+ return val if found.empty?
489
+ errors.concat(found)
490
+ :error
491
+ end
492
+
493
+ def coerce_type(f, v, ptr, errors)
450
494
  fail_with = ->(code, detail) { errors << err(ptr, code, detail); :error }
451
495
  case f.type
452
496
  when "string", "enum"
@@ -491,6 +535,12 @@ module Restep
491
535
  return fail_with.("format", "#{f.name} must be an RFC 3339 date-time with an offset.") unless r
492
536
  return fail_with.("format", "#{f.name} takes at most microsecond precision.") unless Types.micro_exact?(r)
493
537
  Time.at(r).utc
538
+ when "object"
539
+ return fail_with.("type", "#{f.name} must be a JSON object.") unless v.is_a?(Hash)
540
+ Types.json_value(v, ptr, errors)
541
+ when "array"
542
+ return fail_with.("type", "#{f.name} must be a JSON array.") unless v.is_a?(Array)
543
+ Types.json_value(v, ptr, errors)
494
544
  when "relation"
495
545
  return fail_with.("type", "#{f.name} must be an object with an id, such as {\"id\": \"3\"}.") unless v.is_a?(Hash)
496
546
  unless v.key?("id")
@@ -2,26 +2,31 @@ module Restep
2
2
  # If-Match / If-None-Match (RFC 9110 §13.1.1 and §13.1.2).
3
3
  module Conditional
4
4
  # entity-tag = [ "W/" ] DQUOTE *etagc DQUOTE; etagc = %x21 / %x23-7E / obs-text
5
- TAG = %r{\G[ \t]*(W/)?"([\x21\x23-\x7e\x80-\xff]*)"[ \t]*(?:,|\z)}n
5
+ TAG = %r{\G(W/)?"([\x21\x23-\x7e\x80-\xff]*)"}n
6
+ SEPARATORS = /\G[ \t,]*/n
6
7
 
7
8
  module_function
8
9
 
9
10
  # Returns :any, a list of [weak, opaque] or raises 400 if the header is malformed.
11
+ # The field is "*" / #entity-tag (RFC 9110, sections 13.1.1 and 5.6.1): a list may be empty
12
+ # and may have empty elements, so an empty If-Match is a list with no entity tag, which no
13
+ # ETag matches (412), and an empty If-None-Match matches none (the request goes on).
10
14
  def parse(name, value)
11
15
  return nil if value.nil?
12
16
  v = value.b.strip
13
17
  return :any if v == "*"
14
18
  tags = []
15
- pos = 0
16
- v = v.gsub(/,[ \t]*(?=,)/, ",") # empty list elements
17
- until pos >= v.length
19
+ pos = SEPARATORS.match(v, 0).end(0)
20
+ while pos < v.length
18
21
  m = TAG.match(v, pos)
19
- unless m && m.begin(0) == pos
22
+ sep = m && SEPARATORS.match(v, m.end(0))
23
+ # After a tag: optional whitespace, then a comma or the end.
24
+ unless m && m.begin(0) == pos && (sep.end(0) == v.length || v.byteslice(m.end(0), sep.end(0) - m.end(0)).include?(","))
20
25
  raise Problem.new(400, "bad_request", detail: "The #{name} header is malformed: expected * or a list of entity tags.",
21
26
  errors: [{ "header" => name, "code" => "format", "detail" => "Not a valid list of entity tags." }])
22
27
  end
23
28
  tags << [!m[1].nil?, m[2]]
24
- pos = m.end(0)
29
+ pos = sep.end(0)
25
30
  end
26
31
  tags
27
32
  end
@@ -130,6 +130,10 @@ module Restep
130
130
  required = target && !target.template.vars.empty? ? %w[id href] : ["id"]
131
131
  { "type" => "object", "required" => required,
132
132
  "properties" => { "id" => { "type" => "string" }, "href" => { "type" => "string" } } }
133
+ # §4.3: the shape of a document goes in the schemas. In an update schema an object is a
134
+ # merge patch (RFC 7396), where any member may be null or left out, so only its type is given.
135
+ when "object" then mode == :update ? { "type" => "object" } : { "type" => "object" }.merge(f.schema || {})
136
+ when "array" then { "type" => "array" }.merge(f.schema || {})
133
137
  when "language_map"
134
138
  # §3 and §4.3: an object of strings by lowercase tag; an update schema accepts null for
135
139
  # the field and for any well-formed key.
@@ -139,7 +143,7 @@ module Restep
139
143
  { "type" => "object", "propertyNames" => LANGUAGE_KEY, "additionalProperties" => { "type" => "string" } }
140
144
  end
141
145
  end
142
- s = { "type" => [s["type"], "null"] }.merge(s.except("type")) if f.nullable && f.type != "language_map"
146
+ s = { "type" => [s["type"], "null"] }.merge(s.except("type")) if f.nullable && f.type != "language_map" && s["type"].is_a?(String)
143
147
  s["description"] = f.description if f.description
144
148
  s["default"] = f.default if mode == :create && !f.default.nil?
145
149
  s["readOnly"] = true if f.read_only && mode == :item
@@ -14,6 +14,14 @@ module Restep
14
14
  # that a browser sent from an origin the API does not allow: the API's own origin and the
15
15
  # origins of cors are allowed; "*" allows none. Allowed origins also get
16
16
  # Access-Control-Allow-Credentials: true.
17
+ # - exempt: with credentials: true, ->(env) { true or false } says which requests the
18
+ # application authenticates only with a token a browser never attaches on its own (a bearer
19
+ # token in Authorization, an API key header). §5.8 does not cover them, so they skip the
20
+ # origin check. The application must not also authenticate them with a cookie:
21
+ # use Restep::Envelope, credentials: true, exempt: Restep::Envelope.method(:token_authorization?)
22
+ # - path: the API's root path ("/v1"), or a list of them. Only requests under it go through the
23
+ # envelope; the rest (the HTML pages of the same application) go straight to the application,
24
+ # untouched. Without it, every request is the API's.
17
25
  class Envelope
18
26
  KNOWN = %w[GET HEAD POST PUT PATCH DELETE OPTIONS TRACE CONNECT].freeze
19
27
  SAFE = %w[GET HEAD OPTIONS TRACE].freeze
@@ -24,8 +32,12 @@ module Restep
24
32
  ALLOW_HEADERS = "Content-Type, Content-Disposition, If-Match, If-None-Match, Idempotency-Key, Prefer, Authorization, DPoP"
25
33
  ALLOW_METHODS = "GET, HEAD, POST, PATCH, DELETE, QUERY"
26
34
 
27
- def initialize(app, cors: "*", credentials: false)
35
+ def initialize(app, cors: "*", credentials: false, exempt: nil, path: nil)
28
36
  @app = app
37
+ raise ArgumentError, "exempt takes a callable, ->(env) { true or false }" unless exempt.nil? || exempt.respond_to?(:call)
38
+ raise ArgumentError, "exempt goes with credentials: true" if exempt && !credentials
39
+ @exempt = exempt
40
+ @paths = path.nil? ? nil : Array(path).map { |p| normalize_path(p) }
29
41
  @cors =
30
42
  case cors
31
43
  when "*", false, nil then cors || false
@@ -35,7 +47,23 @@ module Restep
35
47
  @credentials = credentials
36
48
  end
37
49
 
50
+ # Whether Authorization carries a token a browser never attaches on its own: any scheme but
51
+ # Basic, Digest, Negotiate and NTLM, which a browser repeats by itself once the user has given
52
+ # them (§5.8 counts them as HTTP authentication).
53
+ def self.token_authorization?(env)
54
+ scheme = env["HTTP_AUTHORIZATION"].to_s.strip.split(/[ \t]/, 2).first.to_s.downcase
55
+ !scheme.empty? && !%w[basic digest negotiate ntlm].include?(scheme)
56
+ end
57
+
58
+ # Whether the request is under one of the envelope's paths (all are, without path:).
59
+ def covers?(env)
60
+ return true if @paths.nil?
61
+ full = "#{env["SCRIPT_NAME"]}#{env["PATH_INFO"]}"
62
+ @paths.any? { |p| p == "" || full == p || full.start_with?("#{p}/") }
63
+ end
64
+
38
65
  def call(env)
66
+ return @app.call(env) unless covers?(env)
39
67
  method = env["REQUEST_METHOD"].to_s
40
68
  # Rails parses the query and the body as soon as anyone asks for `params`, and its own
41
69
  # instrumentation (the "Parameters: ..." log line) asks for it before entering the action:
@@ -50,7 +78,7 @@ module Restep
50
78
  preflight(origin)
51
79
  elsif !KNOWN.include?(method)
52
80
  Problem.rack(501, "not_implemented", detail: "This server does not implement the #{method} method.")
53
- elsif @credentials && !SAFE.include?(method) && cross_origin?(env, origin)
81
+ elsif @credentials && !SAFE.include?(method) && cross_origin?(env, origin) && !@exempt&.call(env)
54
82
  Problem.rack(403, "forbidden", detail: "This API does not accept writes sent by a browser from #{origin || "another site"} (5.8).")
55
83
  else
56
84
  @app.call(env)
@@ -110,6 +138,11 @@ module Restep
110
138
  # The API's origin as Rack sees it (behind a proxy, from the forwarded headers Rack trusts).
111
139
  def own_origin(env) = normalize_origin(Rack::Request.new(env).base_url)
112
140
 
141
+ def normalize_path(p)
142
+ raise ArgumentError, "path: #{p.inspect} must be an absolute path such as \"/v1\"" unless p.is_a?(String) && p.start_with?("/")
143
+ p.delete_suffix("/")
144
+ end
145
+
113
146
  # scheme://host[:port] in lowercase, without the default port.
114
147
  def normalize_origin(o)
115
148
  m = %r{\A([a-z][a-z0-9+.-]*)://([^/?#:]+|\[[0-9a-f:.]+\])(?::([0-9]+))?/?\z}i.match(o.to_s) or return nil
@@ -79,8 +79,8 @@ module Restep
79
79
  def run(scope, request_hash, ttl:, precheck:, replay:)
80
80
  k = scope.values_at(:principal, :http_method, :path, :key)
81
81
  entry = @lock.synchronize do
82
- e = @entries[k]
83
- @entries.delete(k) if e && e.expires_at < Time.now
82
+ now = Time.now
83
+ @entries.delete_if { |_, e| e.expires_at < now }
84
84
  @entries[k] ||= Entry.new(request_hash: request_hash, completed: false, expires_at: Time.now + ttl, status: :new)
85
85
  end
86
86
  if entry.request_hash != request_hash
@@ -111,7 +111,15 @@ module Restep
111
111
 
112
112
  # Keys in a table, with PostgreSQL, valid with several processes. The table needs principal,
113
113
  # http_method, path, key, request_hash, completed, status, headers (json), body, expires_at,
114
- # and a unique index named index_idempotency_keys_unique on (principal, http_method, path, key).
114
+ # and a unique index on (principal, http_method, path, key), whatever its name:
115
+ #
116
+ # c.idempotency_store = Restep::Idempotency::ActiveRecordStore.new("IdempotencyKey")
117
+ # c.idempotency_store = Restep::Idempotency::ActiveRecordStore.new("IdempotencyKey", purge_every: 300)
118
+ #
119
+ # unique_by: the unique index, as its columns (the default) or its name, as insert_all takes it.
120
+ # purge_every: seconds between two purges of every expired key, run by whichever request comes
121
+ # first after that time (nil: never; then call purge from a job). A request always deletes the
122
+ # expired row of its own key first, so an expired key is never replayed.
115
123
  #
116
124
  # 1. The key's record (with the request hash) is inserted and committed right away, outside
117
125
  # the effect's transaction, so another request with the same key sees it.
@@ -123,18 +131,43 @@ module Restep
123
131
  # the effect exactly once.
124
132
  # 4. A rejected request (4xx) deletes the row: it does not spend the key.
125
133
  class ActiveRecordStore
126
- attr_reader :model_ref
134
+ UNIQUE_BY = %i[principal http_method path key].freeze
135
+ PURGE_EVERY = 3600
136
+
137
+ attr_reader :model_ref, :unique_by, :purge_every
127
138
 
128
139
  # By name or by class: with Rails autoloading, the model does not exist yet at configuration time.
129
- def initialize(model) = @model_ref = model
140
+ def initialize(model, unique_by: UNIQUE_BY, purge_every: PURGE_EVERY)
141
+ @model_ref, @unique_by, @purge_every = model, unique_by, purge_every
142
+ @purge_lock = Mutex.new
143
+ @purged_at = nil
144
+ end
130
145
 
131
146
  def model = @model_ref.is_a?(String) ? Object.const_get(@model_ref) : @model_ref
132
147
 
148
+ # Deletes every expired key, of any principal and target, and returns how many. A key whose
149
+ # request is still running is never expired: its lifetime starts when it is first used and
150
+ # is at least a day (7.1).
151
+ def purge(now = Time.now.utc)
152
+ @purge_lock.synchronize { @purged_at = now }
153
+ model.where("expires_at < ?", now).delete_all
154
+ end
155
+
156
+ # Purges when purge_every seconds have passed since the last purge of this process.
157
+ def purge_if_due(now = Time.now.utc)
158
+ return if purge_every.nil?
159
+ due = @purge_lock.synchronize do
160
+ next false if @purged_at && now - @purged_at < purge_every
161
+ @purged_at = now
162
+ end
163
+ model.where("expires_at < ?", now).delete_all if due
164
+ end
165
+
133
166
  def run(scope, request_hash, ttl:, precheck:, replay:)
167
+ purge_if_due
134
168
  3.times do
135
169
  model.where(scope).where("expires_at < ?", Time.now.utc).delete_all
136
- model.insert_all([scope.merge(request_hash: request_hash, expires_at: Time.now.utc + ttl)],
137
- unique_by: :index_idempotency_keys_unique)
170
+ model.insert_all([scope.merge(request_hash: request_hash, expires_at: Time.now.utc + ttl)], unique_by: unique_by)
138
171
  row = model.find_by(scope)
139
172
  next if row.nil? # a rejected request deleted it in between: try again
140
173
 
@@ -0,0 +1,22 @@
1
+ module Restep
2
+ # JSON Merge Patch (RFC 7396, section 2): what a PATCH does to a field of type object, member by
3
+ # member and recursively. A member set to null is removed; an array, a scalar or null in the
4
+ # patch replaces the target's value whole.
5
+ #
6
+ # Restep::MergePatch.apply({ "a" => 1, "b" => { "c" => 2 } }, { "b" => { "c" => nil, "d" => 3 } })
7
+ # # => { "a" => 1, "b" => { "d" => 3 } }
8
+ module MergePatch
9
+ module_function
10
+
11
+ def apply(target, patch)
12
+ return patch unless patch.is_a?(Hash)
13
+ out = target.is_a?(Hash) ? target.dup : {}
14
+ patch.each do |k, v|
15
+ if v.nil? then out.delete(k)
16
+ else out[k] = apply(out[k], v)
17
+ end
18
+ end
19
+ out
20
+ end
21
+ end
22
+ end
@@ -126,7 +126,7 @@ module Restep
126
126
  # the item's ETag, §7.2), 422 on the input, and then the effect.
127
127
  def action(ctx)
128
128
  a = ctx.action
129
- return safe_action(ctx, a) if a.method == "GET"
129
+ return safe_action(ctx, a) if a.safe
130
130
  return collection_action(ctx, a) unless a.item?
131
131
  coll = ctx.collection
132
132
  precheck = lambda do
@@ -148,10 +148,17 @@ module Restep
148
148
  Conditional.evaluate(ctx.if_match, ctx.if_none_match, coll.etag(coll.represent(rec, ctx.parents)), safe: false)
149
149
  input = coll.validate_input(a, Body.object!(ctx.body))
150
150
  before = coll.represent(rec, ctx.parents)
151
- a.run.call(rec, input)
152
- rec = coll.source.reload(rec, ctx.parents) or raise gone
153
- after = coll.represent(rec, ctx.parents)
154
- write_result(ctx, 200, rec, after, invalidate: after != before, action: true)
151
+ result = a.run.call(rec, input)
152
+ reloaded = coll.source.reload(rec, ctx.parents)
153
+ after = reloaded && coll.represent(reloaded, ctx.parents)
154
+ if result.is_a?(Created) || result.is_a?(NoContent)
155
+ # §11.1: a new resource (201 with Location) or nothing (204); neither carries an ETag
156
+ # (7.2), and the item, if the action changed or deleted it, is invalidated.
157
+ groups = [coll.url(ctx.parents)] + (after == before ? [] : [coll.item_url(target_id(coll, rec), ctx.parents)])
158
+ next created_or_empty(result, groups)
159
+ end
160
+ raise gone unless reloaded
161
+ write_result(ctx, 200, reloaded, after, invalidate: after != before, action: true)
155
162
  end
156
163
  end
157
164
  # §11.1: an idempotent action may ignore Idempotency-Key, because repeating it is already safe.
@@ -169,6 +176,10 @@ module Restep
169
176
  # _etag, nil if it no longer exists, :unknown if the response names no item.
170
177
  def stored_item_current(coll, parents, target_id = nil)
171
178
  lambda do |body, headers|
179
+ # The 201 of an action may name a resource of another collection (a new version): that
180
+ # one is not this collection's item.
181
+ location = headers["location"]
182
+ next :unknown if location && !location.start_with?("#{coll.url(parents)}/")
172
183
  id = (JSON.parse(body)["id"] rescue nil) if body
173
184
  id ||= headers["location"]&.split("/")&.last
174
185
  id ||= target_id if body.nil?
@@ -185,16 +196,39 @@ module Restep
185
196
  ctx.query.pairs.group_by(&:name).sort_by(&:first).map { |name, pairs| [name, pairs.map(&:value)] }
186
197
  end
187
198
 
188
- # A safe action with GET: no effects, with ETag and 304 like any read.
189
- # §11.1 (draft 7): its 200 is the result that output declares; without output, a collection's
190
- # safe action answers 204, never 200.
199
+ # A safe action: no effects. §11.1 (draft 7): its 200 is the result that output declares;
200
+ # without output, a collection's safe action answers 204, never 200, and a safe action never
201
+ # answers 201. With GET it is a read, with ETag and 304; with POST it takes an input and is
202
+ # answered with no-store, after the preconditions (412, against the item ETag on an item,
203
+ # 7.2) and before the 422 of its input (5.4).
191
204
  def safe_action(ctx, a)
192
205
  coll = ctx.collection
193
- target = a.item? ? ctx.record : coll.source.scope(ctx.parents)
194
- status, doc = a.run.call(target, {})
206
+ if a.item?
207
+ raise gone if ctx.record.is_a?(Resolver::Missing)
208
+ target = ctx.record
209
+ else
210
+ target = coll.source.scope(ctx.parents)
211
+ end
212
+ input = {}
213
+ if a.method == "POST"
214
+ if a.item?
215
+ if ctx.if_match || ctx.if_none_match
216
+ Conditional.evaluate(ctx.if_match, ctx.if_none_match, coll.etag(coll.represent(target, ctx.parents)), safe: false)
217
+ end
218
+ else
219
+ precheck_collection(ctx).call
220
+ end
221
+ input = coll.validate_input(a, Body.object!(ctx.body))
222
+ end
223
+ status, doc = a.run.call(target, input)
195
224
  if !doc.nil? && a.output.nil? && !a.item?
196
225
  raise ArgumentError, "the safe action #{a.name} on a collection answers 200 only with a declared output (11.1)"
197
226
  end
227
+ raise ArgumentError, "the safe action #{a.name} creates nothing, so it never answers 201 (11.1)" if status == 201
228
+ if a.method == "POST"
229
+ return [204, { "cache-control" => "no-store" }, nil] if doc.nil?
230
+ return [200, { "content-type" => "application/json", "cache-control" => "no-store" }, JSON.generate(doc)]
231
+ end
198
232
  return [status, { "cache-control" => read_cache_control }, nil] if doc.nil?
199
233
  read_response(ctx, JSON.generate(doc), groups: [coll.url(ctx.parents)])
200
234
  end
@@ -204,16 +238,32 @@ module Restep
204
238
  coll.source.transaction do
205
239
  precheck_collection(ctx).call
206
240
  input = coll.validate_input(a, Body.object!(ctx.body))
207
- status, doc = a.run.call(coll.source.scope(ctx.parents), input)
241
+ result = a.run.call(coll.source.scope(ctx.parents), input)
208
242
  # §11.1 (draft 7): an unsafe action on a collection has no representation of its own, so
209
243
  # it answers 201 with the Location of what it creates, or 204; never 200.
210
- unless [201, 204].include?(status)
244
+ next created_or_empty(result, [coll.url(ctx.parents)]) if result.is_a?(Created)
245
+ status, doc = result
246
+ if status == 201
247
+ raise ArgumentError, "the action #{a.name} answers 201 without Location: return Restep::Created.new(location) (11.1)"
248
+ end
249
+ unless status == 204 && doc.nil?
211
250
  raise ArgumentError, "the unsafe action #{a.name} on a collection answers 201 or 204, not #{status} (11.1)"
212
251
  end
213
- headers = { "cache-control" => "no-store", "cache-group-invalidation" => sf_list([coll.url(ctx.parents)]) }
214
- next [status, headers, nil] if doc.nil?
215
- [status, headers.merge("content-type" => "application/json"), JSON.generate(doc)]
252
+ created_or_empty(NO_CONTENT, [coll.url(ctx.parents)])
253
+ end
254
+ end
255
+
256
+ # The 201 (with Location and, if run gave one, a body) or the 204 of an unsafe action.
257
+ def created_or_empty(result, groups)
258
+ headers = { "cache-control" => "no-store", "cache-group-invalidation" => sf_list(groups) }
259
+ return [204, headers, nil] if result.is_a?(NoContent)
260
+ unless result.location.is_a?(String) && result.location.start_with?("/", "https:", "http:")
261
+ raise ArgumentError, "Restep::Created needs the Location of what the action created, an absolute path or URI (3, 11.1)"
216
262
  end
263
+ headers["location"] = result.location
264
+ return [201, headers, nil] if result.body.nil?
265
+ raise ArgumentError, "the body of Restep::Created is a JSON object" unless result.body.is_a?(Hash)
266
+ [201, headers.merge("content-type" => "application/json"), JSON.generate(result.body)]
217
267
  end
218
268
 
219
269
  # ---- Support -----------------------------------------------------------------------------
@@ -5,17 +5,32 @@ module Restep
5
5
  module QueryString
6
6
  Pair = Struct.new(:name, :value, :raw, keyword_init: true) # value is nil when there is no "="
7
7
 
8
+ # A "%" that does not start an escape of two hex digits: RFC 3986 (section 2.1) has no such
9
+ # query, and RFC 9112 (section 3) asks for 400 to an invalid request target.
10
+ MALFORMED_ESCAPE = /%(?![0-9A-Fa-f]{2})/
11
+
8
12
  module_function
9
13
 
14
+ # Whether every "%" in s starts an escape of two hex digits (RFC 3986, section 2.1).
15
+ def well_formed?(s) = !MALFORMED_ESCAPE.match?(s.to_s.b)
16
+
17
+ # The pairs of a query string, in the order received. A malformed escape ("%zz", a trailing
18
+ # "%") gives 400 bad_request, as text that is not UTF-8 after percent-decoding does.
10
19
  def parse(qs)
11
20
  return [] if qs.nil? || qs.empty?
21
+ unless well_formed?(qs)
22
+ raise Problem.new(400, "bad_request",
23
+ detail: "The query string has a % that does not start a percent-encoded octet (%XX); send a literal % as %25.")
24
+ end
12
25
  qs.split("&").reject(&:empty?).map do |seg|
13
26
  name, value = seg.split("=", 2)
14
27
  Pair.new(name: decode(name), value: value.nil? ? nil : decode(value), raw: seg)
15
28
  end
16
29
  end
17
30
 
18
- # "+" is decoded as a space, as forms and URLSearchParams do (see the journal).
31
+ # "+" is decoded as a space, as forms and URLSearchParams do (see the journal). A "%" that
32
+ # starts no escape is kept as is: parse refuses it in a query first, and in a path segment it
33
+ # names no item, since "%" is not in an id.
19
34
  def decode(s)
20
35
  out = s.tr("+", " ").gsub(/%([0-9A-Fa-f]{2})/) { $1.hex.chr }.force_encoding(Encoding::UTF_8)
21
36
  raise Problem.new(400, "bad_request", detail: "The query string is not valid UTF-8 after percent-decoding.") unless out.valid_encoding?
@@ -24,7 +39,8 @@ module Restep
24
39
 
25
40
  # §5.2 (draft 7): a parameter as received, ready for a link the server builds. Whatever RFC 3986
26
41
  # (section 3.4) does not allow unencoded in a query, [ and ] among them, is percent-encoded; a
27
- # % that starts no escape becomes %25. The rest stays as received, + (a space) included, since
42
+ # % that starts no escape becomes %25 (parse refuses one in a request, so that only guards a
43
+ # caller that builds a link from other text). The rest stays as received, + (a space) included, since
28
44
  # encoding again does not change a parameter.
29
45
  def link_form(raw)
30
46
  raw.b.gsub(/%(?![0-9A-Fa-f]{2})|[^A-Za-z0-9\-._~!$&'()*+,;=:@\/?%]/n) { |c| format("%%%02X", c.ord) }
data/lib/restep/types.rb CHANGED
@@ -130,6 +130,55 @@ module Restep
130
130
  s << "Z"
131
131
  end
132
132
 
133
+ # §3: a JSON value of a field of type object or array, as a request body carries it, checked
134
+ # as an I-JSON message and made ready to store and render. Strings (member names too) must be
135
+ # valid UTF-8 without U+0000 or noncharacters; a number with a fraction or an exponent becomes
136
+ # a Float, and one a double cannot hold without losing digits (I-JSON, RFC 7493 section 2.2)
137
+ # is refused rather than rounded. Integers stay exact. Each fault is a 422 entry: at the
138
+ # string that holds it, or at "" for a member name (§3: a pointer to it would carry it too).
139
+ # Returns the value, or :error with the entries added to errors.
140
+ def json_value(v, pointer, errors)
141
+ before = errors.size
142
+ out = normalize_json(v, pointer, errors)
143
+ errors.size == before ? out : :error
144
+ end
145
+
146
+ def normalize_json(v, pointer, errors)
147
+ case v
148
+ when Hash
149
+ v.to_h do |k, x|
150
+ k = k.to_s
151
+ unless storable_string?(k)
152
+ errors << { "pointer" => "", "code" => "format", "detail" => "A member name has a character that cannot be stored (NUL or a noncharacter)." }
153
+ next [k, nil]
154
+ end
155
+ [k, normalize_json(x, "#{pointer}/#{k.gsub("~", "~0").gsub("/", "~1")}", errors)]
156
+ end
157
+ when Array then v.each_with_index.map { |x, i| normalize_json(x, "#{pointer}/#{i}", errors) }
158
+ when String
159
+ unless storable_string?(v)
160
+ errors << { "pointer" => pointer, "code" => "format", "detail" => "The string has a character that cannot be stored (NUL, an unpaired surrogate or a noncharacter)." }
161
+ end
162
+ v
163
+ when BigDecimal, Float then json_float(v, pointer, errors)
164
+ when Integer, true, false, nil then v
165
+ else
166
+ errors << { "pointer" => pointer, "code" => "type", "detail" => "Not a JSON value." }
167
+ nil
168
+ end
169
+ end
170
+
171
+ def storable_string?(s) = s.valid_encoding? && !s.include?("\u0000") && !noncharacter?(s)
172
+
173
+ def json_float(v, pointer, errors)
174
+ f = v.to_f
175
+ exact = f.finite? && (v.is_a?(Float) || BigDecimal(f.to_s) == v)
176
+ return f if exact
177
+ errors << { "pointer" => pointer, "code" => "range",
178
+ "detail" => "The number has more digits or magnitude than a double holds (I-JSON); send it as a string." }
179
+ nil
180
+ end
181
+
133
182
  # Canonical form to compare bodies "equal as JSON values" (§7.1): sorted keys and normalized
134
183
  # exact numbers (1, 1.0 and 1e0 are the same number).
135
184
  def canonical_json(v)
@@ -1,3 +1,3 @@
1
1
  module Restep
2
- VERSION = "0.2.0".freeze
2
+ VERSION = "0.3.0".freeze
3
3
  end
data/lib/restep.rb CHANGED
@@ -116,7 +116,7 @@ end
116
116
 
117
117
  require_relative "restep/version"
118
118
 
119
- %w[problem query_string types language template parents source collection envelope conditional cursor
119
+ %w[problem query_string types merge_patch language template parents source collection envelope conditional cursor
120
120
  query body idempotency discovery rules check request resolver context relations operations
121
121
  sources/computed rack_app].each do |f|
122
122
  require_relative "restep/#{f}"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: restep
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - wubytes
@@ -45,6 +45,7 @@ files:
45
45
  - lib/restep/envelope.rb
46
46
  - lib/restep/idempotency.rb
47
47
  - lib/restep/language.rb
48
+ - lib/restep/merge_patch.rb
48
49
  - lib/restep/operations.rb
49
50
  - lib/restep/parents.rb
50
51
  - lib/restep/problem.rb