restep 0.1.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 +7 -0
- data/LICENSE +21 -0
- data/README.md +224 -0
- data/lib/restep/body.rb +142 -0
- data/lib/restep/collection.rb +378 -0
- data/lib/restep/conditional.rb +56 -0
- data/lib/restep/context.rb +42 -0
- data/lib/restep/cursor.rb +55 -0
- data/lib/restep/discovery.rb +109 -0
- data/lib/restep/envelope.rb +41 -0
- data/lib/restep/idempotency.rb +92 -0
- data/lib/restep/operations.rb +289 -0
- data/lib/restep/problem.rb +105 -0
- data/lib/restep/query.rb +469 -0
- data/lib/restep/query_string.rb +37 -0
- data/lib/restep/rack_app.rb +59 -0
- data/lib/restep/rails/controller.rb +83 -0
- data/lib/restep/rails/routes.rb +33 -0
- data/lib/restep/request.rb +42 -0
- data/lib/restep/resolver.rb +84 -0
- data/lib/restep/types.rb +147 -0
- data/lib/restep/version.rb +3 -0
- data/lib/restep.rb +57 -0
- metadata +95 -0
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
module Restep
|
|
2
|
+
# A collection (or a singleton) of the application's catalog: the fields, filters and order it
|
|
3
|
+
# declares, and its representation, validation and ETag. The domain creates it with Fields.f.
|
|
4
|
+
class Collection
|
|
5
|
+
Field = Struct.new(:name, :type, :column, :values, :nullable, :required, :default, :read_only,
|
|
6
|
+
:max_length, :pattern, :range, :scale, :relation, :description, keyword_init: true)
|
|
7
|
+
|
|
8
|
+
# An action (§11.1). on: "item" or "collection"; method: "POST" or "GET" (only safe ones);
|
|
9
|
+
# input: body fields (Fields.f), or nil. available: whether the item's state allows it
|
|
10
|
+
# (what _actions lists); unavailable: the 409 it gives if not. run: the effect, which gets
|
|
11
|
+
# the item (or the model, in a collection action) and the validated input. In an item
|
|
12
|
+
# action, the response is the re-read item; in a collection one, run returns
|
|
13
|
+
# [status, JSON object or nil].
|
|
14
|
+
# effects: what a person may want to approve first (§11.1, draft 7), a list out of destroys,
|
|
15
|
+
# external and charges, or nil to leave it undeclared. output: the JSON Schema of a safe
|
|
16
|
+
# action's result, which is not a representation; a safe action without output answers its
|
|
17
|
+
# item's representation or nothing (204).
|
|
18
|
+
Action = Struct.new(:name, :on, :method, :safe, :idempotent, :description, :input, :available,
|
|
19
|
+
:unavailable, :run, :effects, :output, keyword_init: true) do
|
|
20
|
+
def item? = on == "item"
|
|
21
|
+
def allowed_methods = method == "GET" ? %w[GET HEAD] : [method]
|
|
22
|
+
def available?(rec) = available.nil? || available.call(rec)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
attr_reader :name, :path, :fields, :filters, :named_filters, :sort, :max_limit,
|
|
26
|
+
:default_limit, :description, :actions, :method_effects
|
|
27
|
+
|
|
28
|
+
# conflicts: which 409 to give when the database rejects a write, by kind of error:
|
|
29
|
+
# { unique: ->(rec) { Problem }, foreign_key: ->(rec) { Problem } }
|
|
30
|
+
# method_effects: only for a singleton (§5.9, draft 7), the effects of its PATCH, as
|
|
31
|
+
# { "PATCH" => [...] } out of destroys, external and charges; nil leaves it undeclared, which
|
|
32
|
+
# a client counts as all three.
|
|
33
|
+
def initialize(name:, path:, model:, description:, fields:, filters: {}, named_filters: {}, sort: {},
|
|
34
|
+
max_limit: nil, default_limit: nil, conflicts: {}, singleton: false, actions: [],
|
|
35
|
+
method_effects: nil)
|
|
36
|
+
@name, @path, @model, @description = name, path, model, description
|
|
37
|
+
@actions = actions.to_h { |a| [a.name, a] }
|
|
38
|
+
@conflicts, @singleton = conflicts, singleton
|
|
39
|
+
@fields = fields.to_h { |f| [f.name, f] }
|
|
40
|
+
@filters, @named_filters, @sort = filters, named_filters, sort
|
|
41
|
+
@max_limit, @default_limit = max_limit, default_limit
|
|
42
|
+
@method_effects = method_effects
|
|
43
|
+
check_filters!
|
|
44
|
+
check_method_effects!
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# §4.3 and §5.9 (draft 7): a singleton may declare method_effects with PATCH as its only key.
|
|
48
|
+
# This gem declares it on singletons only.
|
|
49
|
+
def check_method_effects!
|
|
50
|
+
return if method_effects.nil?
|
|
51
|
+
bad = ->(why) { raise ArgumentError, "#{name}: method_effects #{why} (4.3, 5.9)" }
|
|
52
|
+
bad.("is declared here only on a singleton") unless singleton?
|
|
53
|
+
bad.("takes PATCH as its only key") unless method_effects.is_a?(Hash) && method_effects.keys == ["PATCH"]
|
|
54
|
+
e = method_effects["PATCH"]
|
|
55
|
+
bad.("takes #{Fields::EFFECTS.join(", ")}") unless e.is_a?(Array) && (e - Fields::EFFECTS).empty? && e.uniq == e
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
OPS = %w[eq ne lt le gt ge in nin null prefix contains].freeze
|
|
59
|
+
|
|
60
|
+
# §6.1 (draft 7): what a collection may declare in filter and named_filters. A declaration that
|
|
61
|
+
# breaks it is a programming error, raised when the domain is loaded.
|
|
62
|
+
def check_filters!
|
|
63
|
+
bad = ->(name, why) { raise ArgumentError, "#{self.name}: filter #{name}: #{why} (6.1)" }
|
|
64
|
+
filters.each do |name, d|
|
|
65
|
+
ops = d["ops"]
|
|
66
|
+
bad.(name, "operators come from #{OPS.join(", ")}") unless (ops - OPS).empty?
|
|
67
|
+
bad.(name, "a boolean filter declares only eq, ne and null") if d["type"] == "boolean" && !(ops - %w[eq ne null]).empty?
|
|
68
|
+
bad.(name, "the id filter declares no order operators") if d[:id_like] && !(ops & %w[lt le gt ge]).empty?
|
|
69
|
+
if !(ops & %w[prefix contains]).empty? && (d["type"] != "string" || d[:id_like])
|
|
70
|
+
bad.(name, "prefix and contains only on string fields, never on an id")
|
|
71
|
+
end
|
|
72
|
+
bad.(name, "shares its name with a named filter") if named_filters.key?(name)
|
|
73
|
+
end
|
|
74
|
+
named_filters.each do |name, d|
|
|
75
|
+
bad.(name, "only a switch, a named filter without type, can be a default filter") if d["default"] && d["type"]
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# Paths relative to the API root (discovery) and absolute ones (links and headers).
|
|
80
|
+
def item_path(id) = singleton? ? path : "#{path}/#{id}"
|
|
81
|
+
def url = Restep.url(path)
|
|
82
|
+
def item_url(id) = Restep.url(item_path(id))
|
|
83
|
+
|
|
84
|
+
def singleton? = @singleton
|
|
85
|
+
|
|
86
|
+
def find_singleton = model.order(:id).first
|
|
87
|
+
|
|
88
|
+
# The 409 that matches a database error on write (§5.4).
|
|
89
|
+
def conflict(kind, rec)
|
|
90
|
+
hook = @conflicts[kind]
|
|
91
|
+
hook ? hook.call(rec) : Problem.new(409, "conflict", detail: "The write conflicts with the current state of #{name}.")
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# The model is resolved late: this file loads before the app/models autoload.
|
|
95
|
+
def model = Object.const_get(@model)
|
|
96
|
+
|
|
97
|
+
def find(id_text)
|
|
98
|
+
return nil unless id_text.match?(/\A[1-9][0-9]{0,17}\z/) && Types::BIGINT.cover?(id_text.to_i)
|
|
99
|
+
model.find_by(id: id_text.to_i)
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# ---- Reading ---------------------------------------------------------------------------
|
|
103
|
+
|
|
104
|
+
def represent(rec)
|
|
105
|
+
rep = fields.values.to_h do |f|
|
|
106
|
+
v = rec[f.column]
|
|
107
|
+
out =
|
|
108
|
+
case f.type
|
|
109
|
+
when "id" then v.to_s
|
|
110
|
+
when "relation" then v.nil? ? nil : { "id" => v.to_s, "href" => Restep.collections.fetch(f.relation).item_url(v) }
|
|
111
|
+
when "decimal" then Types.render_decimal(v, f.scale)
|
|
112
|
+
when "datetime" then Types.render_datetime(v)
|
|
113
|
+
when "date" then v&.iso8601
|
|
114
|
+
else v
|
|
115
|
+
end
|
|
116
|
+
[f.name, out]
|
|
117
|
+
end
|
|
118
|
+
item_actions = actions.values.select(&:item?)
|
|
119
|
+
return rep if item_actions.empty?
|
|
120
|
+
# §11.1: the actions its current state allows, so the client need not repeat the rules.
|
|
121
|
+
rep.merge("_actions" => item_actions.select { |a| a.available?(rec) }.to_h { |a|
|
|
122
|
+
[a.name, { "method" => a.method, "href" => "#{item_url(rec.id)}:#{a.name}" }]
|
|
123
|
+
})
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# Validates an action's body against its input. Returns { name => value } or raises 422.
|
|
127
|
+
def validate_input(action, body)
|
|
128
|
+
fields = (action.input || []).to_h { |f| [f.name, f] }
|
|
129
|
+
errors = []
|
|
130
|
+
out = {}
|
|
131
|
+
body.each_key do |k|
|
|
132
|
+
next if k.start_with?("_") || fields.key?(k)
|
|
133
|
+
errors << unknown_member(k, "a member of the #{action.name} input")
|
|
134
|
+
end
|
|
135
|
+
fields.each_value do |f|
|
|
136
|
+
ptr = "/#{esc(f.name)}"
|
|
137
|
+
if !body.key?(f.name)
|
|
138
|
+
errors << err(ptr, "required", "#{f.name} is required.") if f.required
|
|
139
|
+
elsif body[f.name].nil?
|
|
140
|
+
f.nullable ? out[f.name] = nil : errors << err(ptr, "required", "#{f.name} cannot be null.")
|
|
141
|
+
else
|
|
142
|
+
val = coerce(f, body[f.name], ptr, errors)
|
|
143
|
+
out[f.name] = val unless val == :error
|
|
144
|
+
end
|
|
145
|
+
end
|
|
146
|
+
raise Problem.invalid(errors) unless errors.empty?
|
|
147
|
+
out
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
# §7.2 (draft 6): strong ETag of the full representation, computed as if "_etag" were not
|
|
151
|
+
# there; the other "_" members count.
|
|
152
|
+
def etag(rep)
|
|
153
|
+
%("#{Digest::SHA256.hexdigest(JSON.generate(rep.except("_etag")))[0, 32]}")
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# Every response whose body is an item carries "_etag" (§7.2, draft 6).
|
|
157
|
+
def with_etag(rep) = rep.merge("_etag" => etag(rep))
|
|
158
|
+
|
|
159
|
+
# ---- Writing -------------------------------------------------------------------------
|
|
160
|
+
|
|
161
|
+
# Validates a POST body. Returns the column attributes or raises 422.
|
|
162
|
+
# §5.1 (draft 7): in a POST, a field that only the server sets is ignored whatever its value.
|
|
163
|
+
# Such a field is one no client can set directly, in a POST or a PATCH. In this gem that is
|
|
164
|
+
# what read_only: true means for a field other than id: a POST ignores it and a PATCH accepts
|
|
165
|
+
# only its current value, so no request sets it (created_at, updated_at). The gem has no
|
|
166
|
+
# effective or localized fields, and the readOnly it writes in the item schema follows from
|
|
167
|
+
# that behaviour; it does not define it.
|
|
168
|
+
def attributes_for_create(body)
|
|
169
|
+
errors = []
|
|
170
|
+
attrs = {}
|
|
171
|
+
body.each_key do |k|
|
|
172
|
+
next if k.start_with?("_") # §5.1: ignored
|
|
173
|
+
f = fields[k]
|
|
174
|
+
if f.nil?
|
|
175
|
+
errors << unknown_member(k, "a field of #{name}")
|
|
176
|
+
elsif f.type == "id"
|
|
177
|
+
errors << err("/id", "read_only", "id is assigned by the server.")
|
|
178
|
+
end
|
|
179
|
+
end
|
|
180
|
+
fields.each_value do |f|
|
|
181
|
+
next if f.read_only
|
|
182
|
+
ptr = "/#{f.name}"
|
|
183
|
+
if !body.key?(f.name)
|
|
184
|
+
if f.required then errors << err(ptr, "required", "#{f.name} is required.")
|
|
185
|
+
elsif !f.default.nil? then attrs[f.column] = f.default
|
|
186
|
+
else attrs[f.column] = nil
|
|
187
|
+
end
|
|
188
|
+
elsif body[f.name].nil?
|
|
189
|
+
if f.nullable then attrs[f.column] = nil
|
|
190
|
+
else errors << err(ptr, "required", "#{f.name} cannot be null.")
|
|
191
|
+
end
|
|
192
|
+
else
|
|
193
|
+
val = coerce(f, body[f.name], ptr, errors)
|
|
194
|
+
attrs[f.column] = val unless val == :error
|
|
195
|
+
end
|
|
196
|
+
end
|
|
197
|
+
raise Problem.invalid(errors) unless errors.empty?
|
|
198
|
+
attrs
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
# Validates a merge patch against the current item. Returns only the columns that change.
|
|
202
|
+
def changes_for_patch(rec, body)
|
|
203
|
+
errors = []
|
|
204
|
+
changes = {}
|
|
205
|
+
current = represent(rec)
|
|
206
|
+
body.each do |k, v|
|
|
207
|
+
next if k.start_with?("_")
|
|
208
|
+
f = fields[k]
|
|
209
|
+
ptr = "/#{esc(k)}"
|
|
210
|
+
if f.nil?
|
|
211
|
+
errors << unknown_member(k, "a field of #{name}")
|
|
212
|
+
elsif f.read_only && f.type == "datetime" && Types.leap_second?(v)
|
|
213
|
+
# §3 (draft 7): a leap second in a request body is rejected with a format entry, even
|
|
214
|
+
# in a read-only field, instead of being taken as the next minute.
|
|
215
|
+
errors << err(ptr, "format", leap_second_detail(f))
|
|
216
|
+
elsif f.read_only
|
|
217
|
+
errors << err(ptr, "read_only", "#{k} cannot be changed.") unless same_read_only?(f, v, current[k])
|
|
218
|
+
elsif f.type == "relation" && v.is_a?(Hash) && current[k].is_a?(Hash) && v["id"] == current[k]["id"]
|
|
219
|
+
# Relation with its current value: ignored without checking that the target exists
|
|
220
|
+
# (§5.1); only href, if present, is checked to be that item's path.
|
|
221
|
+
check_href(f, v, ptr, errors)
|
|
222
|
+
elsif v.nil?
|
|
223
|
+
if f.nullable
|
|
224
|
+
changes[f.column] = nil unless rec[f.column].nil?
|
|
225
|
+
else
|
|
226
|
+
errors << err(ptr, "required", "#{k} cannot be null.")
|
|
227
|
+
end
|
|
228
|
+
else
|
|
229
|
+
val = coerce(f, v, ptr, errors)
|
|
230
|
+
next if val == :error
|
|
231
|
+
changes[f.column] = val unless same_value?(rec[f.column], val)
|
|
232
|
+
end
|
|
233
|
+
end
|
|
234
|
+
raise Problem.invalid(errors) unless errors.empty?
|
|
235
|
+
changes
|
|
236
|
+
end
|
|
237
|
+
|
|
238
|
+
private
|
|
239
|
+
|
|
240
|
+
def err(pointer, code, detail) = { "pointer" => pointer, "code" => code, "detail" => detail }
|
|
241
|
+
|
|
242
|
+
# An unknown member. §3 (council round 3, decision 10): a member name with a noncharacter gets
|
|
243
|
+
# a format entry with pointer "", because a pointer to it (or a detail that quotes it) would
|
|
244
|
+
# carry the same code point, and the response must be an I-JSON message. An unpaired
|
|
245
|
+
# surrogate never gets here: Body rejects it first, also with pointer "".
|
|
246
|
+
def unknown_member(k, what)
|
|
247
|
+
if !k.valid_encoding? || Types.noncharacter?(k)
|
|
248
|
+
return err("", "format", "A member name has a noncharacter, which a request body cannot carry.")
|
|
249
|
+
end
|
|
250
|
+
err("/#{esc(k)}", "unknown", "#{k} is not #{what}.")
|
|
251
|
+
end
|
|
252
|
+
|
|
253
|
+
def esc(k) = k.gsub("~", "~0").gsub("/", "~1")
|
|
254
|
+
|
|
255
|
+
# §5.1: an href that is not the path of an item of the target collection, or whose last
|
|
256
|
+
# segment is not the id sent, gives 422 (see the journal, B6-4: the text is worded for
|
|
257
|
+
# subcollections).
|
|
258
|
+
def check_href(f, v, ptr, errors)
|
|
259
|
+
return true unless v.key?("href")
|
|
260
|
+
target = Restep.collections.fetch(f.relation)
|
|
261
|
+
href = v["href"]
|
|
262
|
+
decoded = href.is_a?(String) ? (QueryString.decode(href) rescue nil) : nil
|
|
263
|
+
return true if decoded && v["id"].is_a?(String) && decoded == target.item_url(v["id"])
|
|
264
|
+
errors << err("#{ptr}/href", "format", "#{f.name}.href must be the path of the item, #{target.url}/{id}, with the id sent.")
|
|
265
|
+
false
|
|
266
|
+
end
|
|
267
|
+
|
|
268
|
+
def leap_second_detail(f) = "#{f.name} has a leap second (:60), which this API does not accept; use :59 or the next minute."
|
|
269
|
+
|
|
270
|
+
def same_value?(old, new)
|
|
271
|
+
return old.nil? && new.nil? if old.nil? || new.nil?
|
|
272
|
+
old == new
|
|
273
|
+
end
|
|
274
|
+
|
|
275
|
+
# §5.1: a read-only field with its current value is ignored. It is compared by type: the
|
|
276
|
+
# same instant written another way is also the current value (see the journal, L14).
|
|
277
|
+
def same_read_only?(f, v, current)
|
|
278
|
+
return v == current unless f.type == "datetime" && v.is_a?(String) && current.is_a?(String)
|
|
279
|
+
a = Types.parse_datetime(v)
|
|
280
|
+
a && a == Types.parse_datetime(current)
|
|
281
|
+
end
|
|
282
|
+
|
|
283
|
+
def coerce(f, v, ptr, errors)
|
|
284
|
+
fail_with = ->(code, detail) { errors << err(ptr, code, detail); :error }
|
|
285
|
+
case f.type
|
|
286
|
+
when "string", "enum"
|
|
287
|
+
return fail_with.("type", "#{f.name} must be a string.") unless v.is_a?(String)
|
|
288
|
+
# §3 (draft 7): no unpaired surrogates or noncharacters (I-JSON), nor U+0000.
|
|
289
|
+
return fail_with.("format", "#{f.name} contains characters that cannot be stored (NUL, an unpaired surrogate or a noncharacter).") if !v.valid_encoding? || v.include?("\u0000") || Types.noncharacter?(v)
|
|
290
|
+
if f.type == "enum"
|
|
291
|
+
return fail_with.("format", "#{f.name} must be one of: #{f.values.join(", ")}.") unless f.values.include?(v)
|
|
292
|
+
else
|
|
293
|
+
return fail_with.("format", "#{f.name} cannot be empty.") if v.empty?
|
|
294
|
+
return fail_with.("too_long", "#{f.name} takes at most #{f.max_length} characters.") if f.max_length && v.length > f.max_length
|
|
295
|
+
return fail_with.("format", "#{f.name} must match #{f.pattern.source}.") if f.pattern && !f.pattern.match?(v)
|
|
296
|
+
end
|
|
297
|
+
v
|
|
298
|
+
when "integer"
|
|
299
|
+
int =
|
|
300
|
+
if v.is_a?(Integer) then v
|
|
301
|
+
elsif (v.is_a?(BigDecimal) || v.is_a?(Float)) && v.finite? && v.to_r.denominator == 1 then v.to_i
|
|
302
|
+
end
|
|
303
|
+
return fail_with.("type", "#{f.name} must be an integer.") if int.nil? || v == true || v == false
|
|
304
|
+
return fail_with.("range", "#{f.name} must be between #{f.range.min} and #{f.range.max}.") unless f.range.cover?(int)
|
|
305
|
+
int
|
|
306
|
+
when "decimal"
|
|
307
|
+
return fail_with.("type", "#{f.name} must be a decimal number written as a string, such as \"12.5\".") unless v.is_a?(String)
|
|
308
|
+
return fail_with.("format", "#{f.name} must match -?[0-9]+(\\.[0-9]+)?.") unless Types::DECIMAL_RE.match?(v)
|
|
309
|
+
return fail_with.("format", "#{f.name} takes at most #{f.scale} decimal places.") if v[/\.([0-9]+)\z/, 1].to_s.length > f.scale
|
|
310
|
+
bd = BigDecimal(v)
|
|
311
|
+
return fail_with.("range", "#{f.name} must be between #{f.range.min.to_s("F")} and #{f.range.max.to_s("F")}.") unless f.range.cover?(bd)
|
|
312
|
+
bd
|
|
313
|
+
when "boolean"
|
|
314
|
+
return fail_with.("type", "#{f.name} must be true or false.") unless v == true || v == false
|
|
315
|
+
v
|
|
316
|
+
when "date"
|
|
317
|
+
return fail_with.("type", "#{f.name} must be a date string (YYYY-MM-DD).") unless v.is_a?(String)
|
|
318
|
+
d = Types.parse_date(v)
|
|
319
|
+
return fail_with.("format", "#{f.name} must be an RFC 3339 full-date (YYYY-MM-DD).") unless d
|
|
320
|
+
d
|
|
321
|
+
when "datetime"
|
|
322
|
+
return fail_with.("type", "#{f.name} must be an RFC 3339 date-time string.") unless v.is_a?(String)
|
|
323
|
+
return fail_with.("format", leap_second_detail(f)) if Types.leap_second?(v)
|
|
324
|
+
r = Types.parse_datetime(v)
|
|
325
|
+
return fail_with.("format", "#{f.name} must be an RFC 3339 date-time with an offset.") unless r
|
|
326
|
+
return fail_with.("format", "#{f.name} takes at most microsecond precision.") unless Types.micro_exact?(r)
|
|
327
|
+
Time.at(r).utc
|
|
328
|
+
when "relation"
|
|
329
|
+
return fail_with.("type", "#{f.name} must be an object with an id, such as {\"id\": \"3\"}.") unless v.is_a?(Hash)
|
|
330
|
+
unless v.key?("id")
|
|
331
|
+
errors << err("#{ptr}/id", "required", "#{f.name}.id is required.")
|
|
332
|
+
return :error
|
|
333
|
+
end
|
|
334
|
+
id = v["id"]
|
|
335
|
+
unless id.is_a?(String)
|
|
336
|
+
errors << err("#{ptr}/id", "type", "#{f.name}.id must be a string.")
|
|
337
|
+
return :error
|
|
338
|
+
end
|
|
339
|
+
return :error unless check_href(f, v, ptr, errors)
|
|
340
|
+
target = Restep.collections.fetch(f.relation).find(id)
|
|
341
|
+
unless target
|
|
342
|
+
errors << err("#{ptr}/id", "unknown", "There is no #{f.relation} item with id #{id.inspect}.")
|
|
343
|
+
return :error
|
|
344
|
+
end
|
|
345
|
+
target.id
|
|
346
|
+
end
|
|
347
|
+
end
|
|
348
|
+
end
|
|
349
|
+
|
|
350
|
+
module Fields
|
|
351
|
+
module_function
|
|
352
|
+
|
|
353
|
+
def f(**kw) = Collection::Field.new(**{ column: kw[:name] }.merge(kw))
|
|
354
|
+
|
|
355
|
+
EFFECTS = %w[destroys external charges].freeze
|
|
356
|
+
|
|
357
|
+
# Checks the declaration against §11.1 (draft 7); a declaration that breaks it is a
|
|
358
|
+
# programming error, raised when the domain is loaded.
|
|
359
|
+
def action(name, on:, method: "POST", safe: false, idempotent: false, **kw)
|
|
360
|
+
bad = ->(why) { raise ArgumentError, "action #{name}: #{why} (11.1)" }
|
|
361
|
+
bad.("on must be item or collection") unless %w[item collection].include?(on)
|
|
362
|
+
bad.("method must be POST or GET") unless %w[POST GET].include?(method)
|
|
363
|
+
bad.("only a safe action may use GET") if method == "GET" && !safe
|
|
364
|
+
bad.("a safe action declares idempotent: true") if safe && !idempotent
|
|
365
|
+
bad.("a GET action has no body, so no input") if method == "GET" && kw[:input]
|
|
366
|
+
bad.("output is only for a safe action") if kw[:output] && !safe
|
|
367
|
+
bad.("changes is reserved for sync") if name == "changes"
|
|
368
|
+
if name == "new" && !(on == "collection" && safe && method == "GET")
|
|
369
|
+
bad.("new is the safe GET action of a collection that gives the starting values of a new item")
|
|
370
|
+
end
|
|
371
|
+
if (effects = kw[:effects])
|
|
372
|
+
bad.("effects takes #{EFFECTS.join(", ")}") unless effects.is_a?(Array) && (effects - EFFECTS).empty? && effects.uniq == effects
|
|
373
|
+
bad.("a safe action declares only charges") if safe && !(effects - ["charges"]).empty?
|
|
374
|
+
end
|
|
375
|
+
Collection::Action.new(name: name, on: on, method: method, safe: safe, idempotent: idempotent, **kw)
|
|
376
|
+
end
|
|
377
|
+
end
|
|
378
|
+
end
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
module Restep
|
|
2
|
+
# If-Match / If-None-Match (RFC 9110 §13.1.1 and §13.1.2).
|
|
3
|
+
module Conditional
|
|
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
|
|
6
|
+
|
|
7
|
+
module_function
|
|
8
|
+
|
|
9
|
+
# Returns :any, a list of [weak, opaque] or raises 400 if the header is malformed.
|
|
10
|
+
def parse(name, value)
|
|
11
|
+
return nil if value.nil?
|
|
12
|
+
v = value.b.strip
|
|
13
|
+
return :any if v == "*"
|
|
14
|
+
tags = []
|
|
15
|
+
pos = 0
|
|
16
|
+
v = v.gsub(/,[ \t]*(?=,)/, ",") # empty list elements
|
|
17
|
+
until pos >= v.length
|
|
18
|
+
m = TAG.match(v, pos)
|
|
19
|
+
unless m && m.begin(0) == pos
|
|
20
|
+
raise Problem.new(400, "bad_request", detail: "The #{name} header is malformed: expected * or a list of entity tags.",
|
|
21
|
+
errors: [{ "header" => name, "code" => "format", "detail" => "Not a valid list of entity tags." }])
|
|
22
|
+
end
|
|
23
|
+
tags << [!m[1].nil?, m[2]]
|
|
24
|
+
pos = m.end(0)
|
|
25
|
+
end
|
|
26
|
+
tags
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def opaque(etag) = etag.delete_prefix("W/").delete_prefix('"').delete_suffix('"')
|
|
30
|
+
|
|
31
|
+
def strong_match?(list, etag)
|
|
32
|
+
return !etag.nil? if list == :any
|
|
33
|
+
return false if etag.nil? || etag.start_with?("W/")
|
|
34
|
+
list.any? { |weak, op| !weak && op == opaque(etag) }
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def weak_match?(list, etag)
|
|
38
|
+
return !etag.nil? if list == :any
|
|
39
|
+
return false if etag.nil?
|
|
40
|
+
list.any? { |_weak, op| op == opaque(etag) }
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# Order of RFC 9110 §13.2.2 (If-Match before If-None-Match). Returns nil, :not_modified or
|
|
44
|
+
# raises 412.
|
|
45
|
+
def evaluate(if_match, if_none_match, etag, safe:)
|
|
46
|
+
if if_match && !strong_match?(if_match, etag)
|
|
47
|
+
raise Problem.new(412, "precondition_failed", detail: "If-Match does not match the current ETag: the resource has changed.")
|
|
48
|
+
end
|
|
49
|
+
if if_none_match && weak_match?(if_none_match, etag)
|
|
50
|
+
return :not_modified if safe
|
|
51
|
+
raise Problem.new(412, "precondition_failed", detail: "If-None-Match matches the current representation.")
|
|
52
|
+
end
|
|
53
|
+
nil
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
end
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
module Restep
|
|
2
|
+
# Steps 3 and 4 of §5.4 for a request whose resource is already resolved (404) and whose method
|
|
3
|
+
# is allowed (405): reserved parameters (400), malformed headers (400), and body (415, 413,
|
|
4
|
+
# 400) and Accept (406). What remains (412, 422, 409) is decided by the operation.
|
|
5
|
+
class Context
|
|
6
|
+
MAX_QUERY_BYTES = 8 * 1024
|
|
7
|
+
|
|
8
|
+
attr_reader :request, :collection, :kind, :record, :action, :query, :if_match, :if_none_match,
|
|
9
|
+
:idempotency_key, :body
|
|
10
|
+
|
|
11
|
+
# 414 outside the order of §5.4. Puma cuts off any query over 10 KB earlier, with a plain-text
|
|
12
|
+
# 400 (a limit fixed at compile time); here the 414 is given as problem+json below that.
|
|
13
|
+
def self.check_uri_length!(request)
|
|
14
|
+
return if request.query_string.bytesize <= MAX_QUERY_BYTES
|
|
15
|
+
raise Problem.new(414, "uri_too_long", detail: "The query string takes at most #{MAX_QUERY_BYTES} bytes.")
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# kind: :root, :collection, :item, :singleton, :item_action o :collection_action.
|
|
19
|
+
def initialize(request, kind:, collection: nil, record: nil, action: nil)
|
|
20
|
+
@request, @kind, @collection, @record, @action = request, kind, collection, record, action
|
|
21
|
+
m = request.method
|
|
22
|
+
@query = Query.new(collection, kind, request.head? ? "GET" : m, QueryString.parse(request.query_string))
|
|
23
|
+
@if_match = Conditional.parse("If-Match", request.header("If-Match"))
|
|
24
|
+
@if_none_match = Conditional.parse("If-None-Match", request.header("If-None-Match"))
|
|
25
|
+
# §7.1: only a POST reads the key. §11.1 (draft 7): an action declared idempotent ignores
|
|
26
|
+
# keys here, so it ignores a malformed one too instead of answering 400.
|
|
27
|
+
@idempotency_key = m == "POST" && !action&.idempotent ? Body.idempotency_key(request.header("Idempotency-Key")) : nil
|
|
28
|
+
accept_ok = Body.accepts_json?(request.header("Accept"))
|
|
29
|
+
@body =
|
|
30
|
+
case m
|
|
31
|
+
when "POST" then Body.read(request, %w[application/json], accept_ok: accept_ok, empty_is_object: !action.nil?)
|
|
32
|
+
when "PATCH" then Body.read(request, %w[application/merge-patch+json application/json], accept_ok: accept_ok)
|
|
33
|
+
else
|
|
34
|
+
raise Body.not_acceptable if request.safe? && !accept_ok
|
|
35
|
+
nil
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def path = request.path
|
|
40
|
+
def minimal? = Body.prefers_minimal?(request.header("Prefer"))
|
|
41
|
+
end
|
|
42
|
+
end
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
module Restep
|
|
2
|
+
# Opaque cursor (§6.4): bound to the collection, the filters, the order and the principal,
|
|
3
|
+
# never to limit, fields, include or count. It carries the keyset position, encrypted and
|
|
4
|
+
# authenticated (AES-256-GCM), so the sort values stay unreadable in the logs where the
|
|
5
|
+
# next URLs end up (§6.4 and §13.9, draft 6).
|
|
6
|
+
module Cursor
|
|
7
|
+
module_function
|
|
8
|
+
|
|
9
|
+
def secret
|
|
10
|
+
@secret ||= ENV["RESTEP_CURSOR_SECRET"] || begin
|
|
11
|
+
path = Restep.config.cursor_key_path or raise "Restep.config.cursor_key_path is not set"
|
|
12
|
+
File.write(path, SecureRandom.hex(32)) unless File.exist?(path)
|
|
13
|
+
File.read(path).strip
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
# Deterministic encryption: the nonce comes from an HMAC of the content (SIV style). With a
|
|
18
|
+
# random nonce, every response would carry a different next and the page would change body
|
|
19
|
+
# and ETag on every read, so If-None-Match would never give 304 on a collection (see the
|
|
20
|
+
# journal, B6-6).
|
|
21
|
+
def keys
|
|
22
|
+
@keys ||= begin
|
|
23
|
+
material = OpenSSL::KDF.pbkdf2_hmac(secret, salt: "restep-cursor", iterations: 1000, length: 64, hash: "SHA256")
|
|
24
|
+
[material[0, 32], material[32, 32]]
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def issue(payload)
|
|
29
|
+
enc_key, mac_key = keys
|
|
30
|
+
plain = JSON.generate(payload)
|
|
31
|
+
nonce = OpenSSL::HMAC.digest("SHA256", mac_key, plain)[0, 12]
|
|
32
|
+
c = OpenSSL::Cipher.new("aes-256-gcm").encrypt
|
|
33
|
+
c.key = enc_key
|
|
34
|
+
c.iv = nonce
|
|
35
|
+
c.auth_data = "restep-cursor-v1"
|
|
36
|
+
ct = c.update(plain) + c.final
|
|
37
|
+
Base64.urlsafe_encode64(nonce + c.auth_tag + ct, padding: false)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def read(token)
|
|
41
|
+
raw = Base64.urlsafe_decode64(token.to_s)
|
|
42
|
+
return nil if raw.bytesize < 29
|
|
43
|
+
enc_key, = keys
|
|
44
|
+
c = OpenSSL::Cipher.new("aes-256-gcm").decrypt
|
|
45
|
+
c.key = enc_key
|
|
46
|
+
c.iv = raw[0, 12]
|
|
47
|
+
c.auth_tag = raw[12, 16]
|
|
48
|
+
c.auth_data = "restep-cursor-v1"
|
|
49
|
+
v = JSON.parse(c.update(raw[28..]) + c.final)
|
|
50
|
+
v.is_a?(Hash) ? v : nil
|
|
51
|
+
rescue ArgumentError, JSON::ParserError, OpenSSL::Cipher::CipherError
|
|
52
|
+
nil
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
end
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
module Restep
|
|
2
|
+
# Discovery document (§4.2) and the JSON Schemas of each collection (§4.3).
|
|
3
|
+
module Discovery
|
|
4
|
+
module_function
|
|
5
|
+
|
|
6
|
+
def document
|
|
7
|
+
{
|
|
8
|
+
"restep" => "1.0-draft.7",
|
|
9
|
+
"version" => "1",
|
|
10
|
+
"profiles" => %w[core query writes cache],
|
|
11
|
+
"extensions" => Restep.collections.values.any? { |c| c.actions.any? } ? ["actions"] : [],
|
|
12
|
+
"idempotency" => { "ttl" => Idempotency::TTL },
|
|
13
|
+
"status" => Restep.url("/status"), # a link, absolute like those in bodies (§4.2)
|
|
14
|
+
"reasons" => Restep.config.reasons,
|
|
15
|
+
"collections" => Restep.collections.transform_values { |c| collection(c) },
|
|
16
|
+
"singletons" => Restep.singletons.transform_values { |c| singleton(c) }
|
|
17
|
+
}
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def collection(c)
|
|
21
|
+
{
|
|
22
|
+
"path" => c.path,
|
|
23
|
+
"description" => c.description,
|
|
24
|
+
"methods" => %w[GET POST],
|
|
25
|
+
"item_methods" => %w[GET PATCH DELETE],
|
|
26
|
+
"schemas" => { "item" => item_schema(c), "create" => create_schema(c), "update" => update_schema(c) },
|
|
27
|
+
"filter" => c.filters.transform_values { |d| d.select { |k, _| k.is_a?(String) } },
|
|
28
|
+
"named_filters" => c.named_filters.transform_values { |d| d.select { |k, _| k.is_a?(String) } },
|
|
29
|
+
"sort" => c.sort.keys,
|
|
30
|
+
# Declared even though it is the default value: the columns carry COLLATE "C" (§6.1).
|
|
31
|
+
"collations" => collations(c),
|
|
32
|
+
"max_limit" => c.max_limit,
|
|
33
|
+
"count" => "exact"
|
|
34
|
+
}.merge(c.actions.empty? ? {} : { "actions" => c.actions.transform_values { |a| action(a) } })
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# §11.1: on, safe and idempotent always; method only if it is not POST; input only with POST.
|
|
38
|
+
# Draft 7: effects where the domain declares them, and output for a safe action's result.
|
|
39
|
+
def action(a)
|
|
40
|
+
d = { "on" => a.on, "safe" => a.safe, "idempotent" => a.idempotent }
|
|
41
|
+
d["method"] = a.method unless a.method == "POST"
|
|
42
|
+
d["description"] = a.description if a.description
|
|
43
|
+
d["effects"] = a.effects if a.effects
|
|
44
|
+
d["output"] = a.output if a.output
|
|
45
|
+
if a.input && a.method == "POST"
|
|
46
|
+
d["input"] = { "$schema" => "https://json-schema.org/draft/2020-12/schema", "type" => "object",
|
|
47
|
+
"properties" => a.input.to_h { |f| [f.name, property(f, :create)] },
|
|
48
|
+
"required" => a.input.select(&:required).map(&:name),
|
|
49
|
+
"additionalProperties" => false }
|
|
50
|
+
end
|
|
51
|
+
d
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def collations(c)
|
|
55
|
+
names = c.filters.select { |_, d| d["type"] == "string" && !d[:id_like] }.keys
|
|
56
|
+
names |= c.sort.select { |_, d| d[:type] == "string" }.keys
|
|
57
|
+
names.to_h { |n| [n, "codepoint"] }
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def singleton(c)
|
|
61
|
+
d = { "path" => c.path, "description" => c.description, "methods" => %w[GET PATCH],
|
|
62
|
+
"schemas" => { "item" => item_schema(c), "update" => update_schema(c) } }
|
|
63
|
+
# §5.9 (draft 7): the effects of its PATCH, where the domain declares them.
|
|
64
|
+
c.method_effects ? d.merge("method_effects" => c.method_effects) : d
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def property(f, mode)
|
|
68
|
+
s =
|
|
69
|
+
case f.type
|
|
70
|
+
when "id" then { "type" => "string" }
|
|
71
|
+
when "string" then { "type" => "string", "minLength" => 1 }.merge(f.max_length ? { "maxLength" => f.max_length } : {}).merge(f.pattern ? { "pattern" => f.pattern.source.sub(/\A\\A/, "^").sub(/\\z\z/, "$") } : {})
|
|
72
|
+
when "enum" then { "type" => "string", "enum" => f.values }
|
|
73
|
+
when "integer" then { "type" => "integer", "minimum" => f.range.min, "maximum" => f.range.max }
|
|
74
|
+
when "decimal" then { "type" => "string", "pattern" => "^-?[0-9]+(\\.[0-9]{1,#{f.scale}})?$" }
|
|
75
|
+
when "boolean" then { "type" => "boolean" }
|
|
76
|
+
when "date" then { "type" => "string", "format" => "date" }
|
|
77
|
+
when "datetime" then { "type" => "string", "format" => "date-time" }
|
|
78
|
+
when "relation"
|
|
79
|
+
{ "type" => "object", "required" => ["id"],
|
|
80
|
+
"properties" => { "id" => { "type" => "string" }, "href" => { "type" => "string" } } }
|
|
81
|
+
end
|
|
82
|
+
s = { "type" => [s["type"], "null"] }.merge(s.except("type")) if f.nullable
|
|
83
|
+
s["description"] = f.description if f.description
|
|
84
|
+
s["default"] = f.default if mode == :create && !f.default.nil?
|
|
85
|
+
s["readOnly"] = true if f.read_only && mode == :item
|
|
86
|
+
s
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def item_schema(c)
|
|
90
|
+
{ "$schema" => "https://json-schema.org/draft/2020-12/schema", "type" => "object",
|
|
91
|
+
"properties" => c.fields.transform_values { |f| property(f, :item) } }
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def create_schema(c)
|
|
95
|
+
writable = c.fields.values.reject(&:read_only)
|
|
96
|
+
{ "$schema" => "https://json-schema.org/draft/2020-12/schema", "type" => "object",
|
|
97
|
+
"properties" => writable.to_h { |f| [f.name, property(f, :create)] },
|
|
98
|
+
"required" => writable.select(&:required).map(&:name),
|
|
99
|
+
"additionalProperties" => false }
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def update_schema(c)
|
|
103
|
+
writable = c.fields.values.reject(&:read_only)
|
|
104
|
+
{ "$schema" => "https://json-schema.org/draft/2020-12/schema", "type" => "object",
|
|
105
|
+
"properties" => writable.to_h { |f| [f.name, property(f, :update)] },
|
|
106
|
+
"additionalProperties" => false }
|
|
107
|
+
end
|
|
108
|
+
end
|
|
109
|
+
end
|