whoosh 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/CHANGELOG.md +18 -0
- data/LICENSE +21 -0
- data/README.md +209 -0
- data/lib/generators/whoosh/install/install_generator.rb +30 -0
- data/lib/generators/whoosh/install/templates/application_api.rb.tt +11 -0
- data/lib/generators/whoosh/install/templates/initializer.rb.tt +25 -0
- data/lib/generators/whoosh/install/templates/status_api.rb.tt +11 -0
- data/lib/generators/whoosh/install/templates/status_schema.rb.tt +4 -0
- data/lib/whoosh/api.rb +134 -0
- data/lib/whoosh/app.rb +280 -0
- data/lib/whoosh/configuration.rb +76 -0
- data/lib/whoosh/context.rb +56 -0
- data/lib/whoosh/endpoint.rb +168 -0
- data/lib/whoosh/errors.rb +62 -0
- data/lib/whoosh/idempotency.rb +70 -0
- data/lib/whoosh/json.rb +43 -0
- data/lib/whoosh/lazy_app.rb +28 -0
- data/lib/whoosh/openapi.rb +181 -0
- data/lib/whoosh/pagination.rb +109 -0
- data/lib/whoosh/railtie.rb +19 -0
- data/lib/whoosh/rate_limiter.rb +31 -0
- data/lib/whoosh/request.rb +120 -0
- data/lib/whoosh/router.rb +90 -0
- data/lib/whoosh/schema.rb +375 -0
- data/lib/whoosh/stores/cache.rb +40 -0
- data/lib/whoosh/stores/memory.rb +76 -0
- data/lib/whoosh/types.rb +153 -0
- data/lib/whoosh/version.rb +3 -0
- data/lib/whoosh.rb +72 -0
- metadata +92 -0
data/lib/whoosh/app.rb
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
module Whoosh
|
|
2
|
+
# The Rack application. Holds the compiled router for one or more API
|
|
3
|
+
# classes and runs every request through the same pipeline:
|
|
4
|
+
#
|
|
5
|
+
# request id -> CORS preflight -> route -> authenticate -> rate limit
|
|
6
|
+
# -> 401 unless public -> parse params -> authorize -> idempotency
|
|
7
|
+
# -> handler -> serialize through `returns` -> security headers
|
|
8
|
+
class App
|
|
9
|
+
SECURITY_HEADERS = {
|
|
10
|
+
"x-content-type-options" => "nosniff",
|
|
11
|
+
"x-frame-options" => "DENY",
|
|
12
|
+
"referrer-policy" => "no-referrer",
|
|
13
|
+
"content-security-policy" => "default-src 'none'; frame-ancestors 'none'",
|
|
14
|
+
"cross-origin-opener-policy" => "same-origin",
|
|
15
|
+
"cache-control" => "no-store"
|
|
16
|
+
}.freeze
|
|
17
|
+
JSON_CONTENT_TYPE = "application/json; charset=utf-8".freeze
|
|
18
|
+
CORS_ALLOWED_HEADERS = %w[authorization content-type idempotency-key x-request-id accept].freeze
|
|
19
|
+
OPENAPI_PATH = "/openapi.json".freeze
|
|
20
|
+
|
|
21
|
+
AR_NOT_FOUND = "ActiveRecord::RecordNotFound".freeze
|
|
22
|
+
AR_INVALID = "ActiveRecord::RecordInvalid".freeze
|
|
23
|
+
AR_NOT_UNIQUE = "ActiveRecord::RecordNotUnique".freeze
|
|
24
|
+
AR_STALE = "ActiveRecord::StaleObjectError".freeze
|
|
25
|
+
|
|
26
|
+
attr_reader :apis, :router
|
|
27
|
+
|
|
28
|
+
def initialize(apis, config: nil)
|
|
29
|
+
@apis = apis
|
|
30
|
+
@config_override = config
|
|
31
|
+
@router = Router.new
|
|
32
|
+
apis.each do |api|
|
|
33
|
+
api.endpoints.each { |ep| @router.add(ep.verb, ep.path, ep) }
|
|
34
|
+
end
|
|
35
|
+
@openapi_json = nil
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def config = @config_override || Whoosh.config
|
|
39
|
+
|
|
40
|
+
def call(env)
|
|
41
|
+
request = Request.new(env, config)
|
|
42
|
+
status, headers, body = dispatch(request)
|
|
43
|
+
finish(request, status, headers, body)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
private
|
|
47
|
+
|
|
48
|
+
# ---- dispatch ----------------------------------------------------------
|
|
49
|
+
|
|
50
|
+
def dispatch(request)
|
|
51
|
+
return preflight(request) if request.request_method == "OPTIONS"
|
|
52
|
+
return openapi(request) if serve_openapi?(request)
|
|
53
|
+
|
|
54
|
+
match = @router.match(request.request_method, request.path)
|
|
55
|
+
raise NotFound.new("No endpoint matches #{request.request_method} #{request.path}.") if match.nil?
|
|
56
|
+
|
|
57
|
+
if match.first == :method_not_allowed
|
|
58
|
+
allow = (match.last + (match.last.include?("GET") ? ["HEAD"] : []) + ["OPTIONS"]).join(", ")
|
|
59
|
+
raise MethodNotAllowed.new(headers: { "allow" => allow })
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
endpoint, path_params = match
|
|
63
|
+
run(endpoint, request, path_params)
|
|
64
|
+
rescue HTTPError => e
|
|
65
|
+
error_response(request, e)
|
|
66
|
+
rescue StandardError => e
|
|
67
|
+
error_response(request, translate(e, request))
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def run(endpoint, request, path_params)
|
|
71
|
+
user = authenticate(request)
|
|
72
|
+
request.user_id_for_limits = user_key(user)
|
|
73
|
+
client = config.client_identifier.call(request).to_s
|
|
74
|
+
limit_headers = check_rate_limit(endpoint, client)
|
|
75
|
+
|
|
76
|
+
raise Unauthorized if user.nil? && !endpoint.public?
|
|
77
|
+
|
|
78
|
+
context = endpoint.api.context_class.new(request, endpoint, user)
|
|
79
|
+
params = parse_params(endpoint, request, path_params)
|
|
80
|
+
context.assign_params(params)
|
|
81
|
+
|
|
82
|
+
if endpoint.authorizer && !context.instance_exec(user, params, &endpoint.authorizer)
|
|
83
|
+
raise Forbidden
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
execute = lambda do
|
|
87
|
+
result = context.instance_exec(params, &endpoint.handler)
|
|
88
|
+
render(endpoint, context, request, result)
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
status, headers, body =
|
|
92
|
+
if endpoint.idempotency
|
|
93
|
+
Idempotency.new(config.store, ttl: config.idempotency_ttl)
|
|
94
|
+
.call(request, scope: endpoint.id, client: client, required: endpoint.idempotency[:required], &execute)
|
|
95
|
+
else
|
|
96
|
+
execute.call
|
|
97
|
+
end
|
|
98
|
+
[status, headers.merge(limit_headers), body]
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def authenticate(request)
|
|
102
|
+
config.authenticate&.call(request)
|
|
103
|
+
rescue HTTPError
|
|
104
|
+
raise
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def user_key(user)
|
|
108
|
+
return nil if user.nil?
|
|
109
|
+
|
|
110
|
+
id = user.respond_to?(:id) ? user.id : user.object_id
|
|
111
|
+
"user:#{id}"
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
def check_rate_limit(endpoint, client)
|
|
115
|
+
limit, per = endpoint.effective_rate_limit(config)
|
|
116
|
+
return {} unless limit
|
|
117
|
+
|
|
118
|
+
result = RateLimiter.new(config.store).check!(endpoint.id, client, limit: limit, per: per)
|
|
119
|
+
{ "x-ratelimit-limit" => result.limit.to_s, "x-ratelimit-remaining" => result.remaining.to_s }
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
def parse_params(endpoint, request, path_params)
|
|
123
|
+
schema = endpoint.params_schema
|
|
124
|
+
return {}.freeze unless schema
|
|
125
|
+
|
|
126
|
+
input = request.query
|
|
127
|
+
input = input.except(*endpoint.pagination.query_fields) if endpoint.pagination
|
|
128
|
+
input = input.merge(request.json) if request.body?
|
|
129
|
+
input = input.merge(path_params) unless path_params.empty?
|
|
130
|
+
schema.parse(input)
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
def render(endpoint, context, request, result)
|
|
134
|
+
status = context.status || endpoint.status
|
|
135
|
+
headers = context.response_headers.dup
|
|
136
|
+
return [status, headers, []] if endpoint.no_content?
|
|
137
|
+
|
|
138
|
+
schema = endpoint.returns_schema
|
|
139
|
+
payload =
|
|
140
|
+
if endpoint.pagination
|
|
141
|
+
page = endpoint.pagination.call(result, request.query, config)
|
|
142
|
+
{ "data" => schema.dump_many(page.records), "meta" => page.meta }
|
|
143
|
+
elsif endpoint.many?
|
|
144
|
+
{ "data" => schema.dump_many(result.respond_to?(:to_a) ? result.to_a : Array(result)) }
|
|
145
|
+
else
|
|
146
|
+
raise NotFound if result.nil?
|
|
147
|
+
|
|
148
|
+
{ "data" => schema.dump(result) }
|
|
149
|
+
end
|
|
150
|
+
json_response(status, payload, headers)
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# ---- errors ------------------------------------------------------------
|
|
154
|
+
|
|
155
|
+
def translate(exception, request)
|
|
156
|
+
custom = rescue_handler_for(exception, request)
|
|
157
|
+
return custom if custom
|
|
158
|
+
|
|
159
|
+
case exception.class.name
|
|
160
|
+
when AR_NOT_FOUND then NotFound.new
|
|
161
|
+
when AR_INVALID then ValidationError.new(record_errors(exception))
|
|
162
|
+
when AR_NOT_UNIQUE then Conflict.new("A record with these values already exists.")
|
|
163
|
+
when AR_STALE then Conflict.new("This record was changed by someone else. Reload and try again.")
|
|
164
|
+
else
|
|
165
|
+
report(exception, request)
|
|
166
|
+
if config.expose_errors
|
|
167
|
+
InternalError.new("#{exception.class}: #{exception.message}",
|
|
168
|
+
details: { "backtrace" => Array(exception.backtrace).first(15) })
|
|
169
|
+
else
|
|
170
|
+
InternalError.new
|
|
171
|
+
end
|
|
172
|
+
end
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
def rescue_handler_for(exception, request)
|
|
176
|
+
apis.each do |api|
|
|
177
|
+
api.rescue_handlers.each do |klass, handler|
|
|
178
|
+
next unless exception.is_a?(klass)
|
|
179
|
+
|
|
180
|
+
result = handler.call(exception, request)
|
|
181
|
+
return result if result.is_a?(HTTPError)
|
|
182
|
+
end
|
|
183
|
+
end
|
|
184
|
+
nil
|
|
185
|
+
end
|
|
186
|
+
|
|
187
|
+
def record_errors(exception)
|
|
188
|
+
record = exception.respond_to?(:record) ? exception.record : nil
|
|
189
|
+
return {} unless record && record.respond_to?(:errors)
|
|
190
|
+
|
|
191
|
+
record.errors.to_hash.each_with_object({}) { |(k, v), h| h[k.to_s] = Array(v) }
|
|
192
|
+
end
|
|
193
|
+
|
|
194
|
+
def report(exception, request)
|
|
195
|
+
config.logger&.error("[whoosh] #{request.request_id} #{exception.class}: #{exception.message}\n" \
|
|
196
|
+
"#{Array(exception.backtrace).first(20).join("\n")}")
|
|
197
|
+
config.on_error&.call(exception, request)
|
|
198
|
+
rescue StandardError
|
|
199
|
+
nil
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
def error_response(request, error)
|
|
203
|
+
body = { "error" => error.to_h.transform_keys(&:to_s).merge("request_id" => request.request_id) }
|
|
204
|
+
json_response(error.status, body, error.headers.dup)
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
# ---- CORS, OpenAPI, headers -------------------------------------------
|
|
208
|
+
|
|
209
|
+
def preflight(request)
|
|
210
|
+
headers = {}
|
|
211
|
+
verbs = methods_for(request.path)
|
|
212
|
+
verbs += ["HEAD"] if verbs.include?("GET")
|
|
213
|
+
headers["allow"] = (verbs + ["OPTIONS"]).join(", ") unless verbs.empty?
|
|
214
|
+
|
|
215
|
+
if cors_allowed?(request.origin) && request.header("access-control-request-method")
|
|
216
|
+
headers["access-control-allow-methods"] = (verbs.empty? ? Endpoint::VERBS : verbs).join(", ")
|
|
217
|
+
requested = request.header("access-control-request-headers").to_s.downcase.split(/\s*,\s*/)
|
|
218
|
+
headers["access-control-allow-headers"] = (requested & CORS_ALLOWED_HEADERS).join(", ")
|
|
219
|
+
headers["access-control-max-age"] = config.cors_max_age.to_s
|
|
220
|
+
end
|
|
221
|
+
[204, headers, []]
|
|
222
|
+
end
|
|
223
|
+
|
|
224
|
+
def methods_for(path)
|
|
225
|
+
Endpoint::VERBS.select do |verb|
|
|
226
|
+
m = @router.match(verb, path)
|
|
227
|
+
m && m.first != :method_not_allowed
|
|
228
|
+
end
|
|
229
|
+
end
|
|
230
|
+
|
|
231
|
+
def cors_allowed?(origin)
|
|
232
|
+
return false if origin.nil? || origin.empty?
|
|
233
|
+
|
|
234
|
+
config.cors_origins.any? do |allowed|
|
|
235
|
+
allowed.is_a?(Regexp) ? allowed.match?(origin) : allowed == origin
|
|
236
|
+
end
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
def serve_openapi?(request)
|
|
240
|
+
config.openapi && request.request_method.match?(/\A(GET|HEAD)\z/) && request.path == OPENAPI_PATH
|
|
241
|
+
end
|
|
242
|
+
|
|
243
|
+
def openapi(request)
|
|
244
|
+
if config.openapi == :authenticated && authenticate(request).nil?
|
|
245
|
+
raise Unauthorized
|
|
246
|
+
end
|
|
247
|
+
|
|
248
|
+
@openapi_json ||= Whoosh::JSON.dump(OpenAPI.new(apis, server_url: request.script_name).document)
|
|
249
|
+
[200, { "content-type" => JSON_CONTENT_TYPE, "cache-control" => "no-cache" }, [@openapi_json]]
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
def json_response(status, payload, headers)
|
|
253
|
+
body = Whoosh::JSON.dump(payload)
|
|
254
|
+
headers["content-type"] = JSON_CONTENT_TYPE
|
|
255
|
+
[status, headers, [body]]
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
def finish(request, status, headers, body)
|
|
259
|
+
out = SECURITY_HEADERS.merge(config.default_headers).merge(headers)
|
|
260
|
+
out["x-request-id"] = request.request_id
|
|
261
|
+
out["strict-transport-security"] = "max-age=63072000; includeSubDomains" if request.https?
|
|
262
|
+
|
|
263
|
+
origin = request.origin
|
|
264
|
+
if cors_allowed?(origin)
|
|
265
|
+
out["access-control-allow-origin"] = origin
|
|
266
|
+
out["access-control-allow-credentials"] = "true" if config.cors_credentials
|
|
267
|
+
out["access-control-expose-headers"] = config.cors_expose_headers.join(", ")
|
|
268
|
+
end
|
|
269
|
+
out["vary"] = [out["vary"], "origin"].compact.join(", ") if config.cors_origins.any?
|
|
270
|
+
|
|
271
|
+
if status == 204 || status == 304
|
|
272
|
+
out.delete("content-type")
|
|
273
|
+
body = []
|
|
274
|
+
end
|
|
275
|
+
out["content-length"] = body.sum(&:bytesize).to_s if body.is_a?(Array)
|
|
276
|
+
body = [] if request.head?
|
|
277
|
+
[status, out, body]
|
|
278
|
+
end
|
|
279
|
+
end
|
|
280
|
+
end
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
module Whoosh
|
|
2
|
+
# Global settings. Every default is the safe choice; loosen them explicitly.
|
|
3
|
+
class Configuration
|
|
4
|
+
# ->(request) { User.find_by_token(request.bearer_token) }
|
|
5
|
+
# Returns the user, or nil for an anonymous request. Endpoints that aren't
|
|
6
|
+
# `public` respond 401 when it returns nil.
|
|
7
|
+
attr_accessor :authenticate
|
|
8
|
+
|
|
9
|
+
# Exact origins allowed for CORS, e.g. ["https://app.example.com"].
|
|
10
|
+
# Empty means no cross-origin access. "*" is refused for credentialed CORS.
|
|
11
|
+
attr_accessor :cors_origins, :cors_max_age, :cors_credentials, :cors_expose_headers
|
|
12
|
+
|
|
13
|
+
# Largest request body accepted, in bytes.
|
|
14
|
+
attr_accessor :max_body_size
|
|
15
|
+
|
|
16
|
+
# Default and maximum page sizes for paginated endpoints.
|
|
17
|
+
attr_accessor :default_page_size, :max_page_size
|
|
18
|
+
|
|
19
|
+
# Default limit for every endpoint: [requests, per_seconds]. nil turns it off.
|
|
20
|
+
attr_accessor :rate_limit
|
|
21
|
+
|
|
22
|
+
# Stores for rate limits and idempotency keys. Use a shared store
|
|
23
|
+
# (Whoosh::Stores::Cache.new(Rails.cache)) when running several processes.
|
|
24
|
+
attr_accessor :store
|
|
25
|
+
|
|
26
|
+
# How long a replayable idempotent response is kept, in seconds.
|
|
27
|
+
attr_accessor :idempotency_ttl
|
|
28
|
+
|
|
29
|
+
# Show exception messages and backtraces in 500 responses. Development only.
|
|
30
|
+
attr_accessor :expose_errors
|
|
31
|
+
|
|
32
|
+
# Serve the OpenAPI document at GET /openapi.json on each API.
|
|
33
|
+
attr_accessor :openapi
|
|
34
|
+
|
|
35
|
+
# Header used for request IDs; an incoming one is kept if it looks safe.
|
|
36
|
+
attr_accessor :request_id_header
|
|
37
|
+
|
|
38
|
+
# Extra response headers merged into every response.
|
|
39
|
+
attr_accessor :default_headers
|
|
40
|
+
|
|
41
|
+
# ->(exception, request) { Sentry.capture_exception(exception) }
|
|
42
|
+
attr_accessor :on_error
|
|
43
|
+
|
|
44
|
+
# Anything that responds to #info/#error. Rails sets Rails.logger.
|
|
45
|
+
attr_accessor :logger
|
|
46
|
+
|
|
47
|
+
# Maximum nesting depth and number of keys accepted in JSON bodies.
|
|
48
|
+
attr_accessor :max_json_depth, :max_json_keys
|
|
49
|
+
|
|
50
|
+
# Which address to key rate limits on: ->(request) { request.ip }.
|
|
51
|
+
attr_accessor :client_identifier
|
|
52
|
+
|
|
53
|
+
def initialize
|
|
54
|
+
@authenticate = ->(_request) { nil }
|
|
55
|
+
@cors_origins = []
|
|
56
|
+
@cors_max_age = 600
|
|
57
|
+
@cors_credentials = false
|
|
58
|
+
@cors_expose_headers = %w[x-request-id retry-after x-ratelimit-limit x-ratelimit-remaining]
|
|
59
|
+
@max_body_size = 1_048_576 # 1 MB
|
|
60
|
+
@default_page_size = 25
|
|
61
|
+
@max_page_size = 100
|
|
62
|
+
@rate_limit = [300, 60]
|
|
63
|
+
@store = Stores::Memory.new
|
|
64
|
+
@idempotency_ttl = 24 * 60 * 60
|
|
65
|
+
@expose_errors = false
|
|
66
|
+
@openapi = false
|
|
67
|
+
@request_id_header = "x-request-id"
|
|
68
|
+
@default_headers = {}
|
|
69
|
+
@on_error = nil
|
|
70
|
+
@logger = nil
|
|
71
|
+
@max_json_depth = 20
|
|
72
|
+
@max_json_keys = 1_000
|
|
73
|
+
@client_identifier = ->(request) { request.user_id_for_limits || request.ip }
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
end
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
module Whoosh
|
|
2
|
+
# The object `authorize` and `handle` blocks run in. A fresh one per
|
|
3
|
+
# request; the API's `helpers` are mixed into its class.
|
|
4
|
+
class Context
|
|
5
|
+
attr_reader :request, :params, :current_user, :endpoint
|
|
6
|
+
|
|
7
|
+
def initialize(request, endpoint, current_user)
|
|
8
|
+
@request = request
|
|
9
|
+
@endpoint = endpoint
|
|
10
|
+
@current_user = current_user
|
|
11
|
+
@params = {}.freeze
|
|
12
|
+
@response_headers = {}
|
|
13
|
+
@status = nil
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
def assign_params(params)
|
|
17
|
+
@params = params
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# Override the response status: `status 202`.
|
|
21
|
+
def status(code = nil)
|
|
22
|
+
return @status if code.nil?
|
|
23
|
+
|
|
24
|
+
@status = Integer(code)
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# Add a response header: `header "location", "/v1/orders/#{order.id}"`.
|
|
28
|
+
def header(name, value)
|
|
29
|
+
key = name.to_s.downcase
|
|
30
|
+
raise ArgumentError, "invalid header value" if value.to_s.match?(/[\r\n]/)
|
|
31
|
+
|
|
32
|
+
@response_headers[key] = value.to_s
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def response_headers = @response_headers
|
|
36
|
+
|
|
37
|
+
# Stop with an error response. All of these render the standard envelope.
|
|
38
|
+
def not_found!(message = nil) = raise(NotFound.new(message))
|
|
39
|
+
def forbidden!(message = nil) = raise(Forbidden.new(message))
|
|
40
|
+
def unauthorized!(message = nil) = raise(Unauthorized.new(message))
|
|
41
|
+
def conflict!(message = nil, code: nil) = raise(Conflict.new(message, code: code))
|
|
42
|
+
def bad_request!(message = nil, code: nil) = raise(BadRequest.new(message, code: code))
|
|
43
|
+
|
|
44
|
+
# Field-level errors, same shape as schema validation:
|
|
45
|
+
# invalid!(quantity: "is more than the stock left")
|
|
46
|
+
def invalid!(errors, message = nil)
|
|
47
|
+
details = errors.to_h.transform_keys(&:to_s).transform_values { |v| Array(v) }
|
|
48
|
+
raise ValidationError.new(details, message)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Any status and code: error!(402, "payment_required", "Top up your balance first.")
|
|
52
|
+
def error!(status, code, message, details: nil)
|
|
53
|
+
raise HTTPError.new(message, status: status, code: code, details: details)
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
end
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
module Whoosh
|
|
2
|
+
# One endpoint, built from the block given to get/post/put/patch/delete.
|
|
3
|
+
# `finalize!` enforces the secure-by-default rules when the API is defined:
|
|
4
|
+
# every endpoint says who may call it, and what it returns.
|
|
5
|
+
class Endpoint
|
|
6
|
+
VERBS = %w[GET POST PUT PATCH DELETE].freeze
|
|
7
|
+
PATH_PARAM = /:([a-z_][a-z0-9_]*)/
|
|
8
|
+
|
|
9
|
+
attr_reader :verb, :path, :api, :params_schema, :returns_schema, :pagination, :handler,
|
|
10
|
+
:authorizer, :idempotency, :status, :docs
|
|
11
|
+
|
|
12
|
+
def initialize(api, verb, path)
|
|
13
|
+
@api = api
|
|
14
|
+
@verb = verb
|
|
15
|
+
@path = path
|
|
16
|
+
@public = false
|
|
17
|
+
@authorizer = nil
|
|
18
|
+
@params_schema = nil
|
|
19
|
+
@returns_schema = nil
|
|
20
|
+
@returns_set = false
|
|
21
|
+
@many = false
|
|
22
|
+
@status = verb == "POST" ? 201 : 200
|
|
23
|
+
@pagination = nil
|
|
24
|
+
@idempotency = nil
|
|
25
|
+
@rate_limit = :default
|
|
26
|
+
@handler = nil
|
|
27
|
+
@docs = {}
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def id = "#{verb} #{path}"
|
|
31
|
+
def public? = @public
|
|
32
|
+
def many? = @many || !@pagination.nil?
|
|
33
|
+
def no_content? = @returns_set && @returns_schema.nil?
|
|
34
|
+
def path_params = path.scan(PATH_PARAM).flatten
|
|
35
|
+
|
|
36
|
+
# ---- DSL (evaluated inside the endpoint block) -------------------------
|
|
37
|
+
|
|
38
|
+
# Anyone may call this endpoint, signed in or not.
|
|
39
|
+
def public!
|
|
40
|
+
@public = true
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# Who may call this endpoint. Runs before the handler with the current
|
|
44
|
+
# user (never nil unless public!) and the parsed params. Falsey -> 403.
|
|
45
|
+
# authorize { |user| user.admin? }
|
|
46
|
+
# authorize { |user, p| user.store_ids.include?(p[:store_id]) }
|
|
47
|
+
def authorize(&block)
|
|
48
|
+
raise DefinitionError, "#{id}: authorize needs a block" unless block
|
|
49
|
+
|
|
50
|
+
@authorizer = block
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Accepted input: path params, query string and JSON body, merged.
|
|
54
|
+
# Undeclared keys never reach the handler.
|
|
55
|
+
# params do
|
|
56
|
+
# required :id, :integer
|
|
57
|
+
# optional :status, :string, enum: %w[pending paid]
|
|
58
|
+
# end
|
|
59
|
+
# params OrderInput
|
|
60
|
+
def params(schema = nil, &block)
|
|
61
|
+
@params_schema = schema || Schema.build("#{schema_prefix}Params", &block)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# The response shape. Only declared fields are serialized.
|
|
65
|
+
# returns OrderSchema
|
|
66
|
+
# returns OrderSchema, many: true
|
|
67
|
+
# returns OrderSchema, status: 202
|
|
68
|
+
# returns nil # 204 No Content
|
|
69
|
+
# returns { field :ok, :boolean }
|
|
70
|
+
def returns(schema = :__block, many: false, status: nil, &block)
|
|
71
|
+
@returns_set = true
|
|
72
|
+
@many = many
|
|
73
|
+
@status = status if status
|
|
74
|
+
if schema.nil?
|
|
75
|
+
@returns_schema = nil
|
|
76
|
+
@status = 204
|
|
77
|
+
elsif schema == :__block
|
|
78
|
+
raise DefinitionError, "#{id}: returns needs a schema or a block" unless block
|
|
79
|
+
|
|
80
|
+
@returns_schema = Schema.build("#{schema_prefix}Response", &block)
|
|
81
|
+
else
|
|
82
|
+
unless schema.is_a?(Class) && schema <= Schema
|
|
83
|
+
raise DefinitionError, "#{id}: returns expects a Whoosh::Schema subclass, got #{schema.inspect}"
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
@returns_schema = schema
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# paginate # cursor on id, ascending
|
|
91
|
+
# paginate :cursor, by: :created_at, order: :desc
|
|
92
|
+
# paginate :offset
|
|
93
|
+
def paginate(style = :cursor, by: :id, order: :asc)
|
|
94
|
+
@pagination = Pagination.new(style, by: by, order: order)
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# Replay responses for repeated Idempotency-Key headers.
|
|
98
|
+
# idempotent # header optional
|
|
99
|
+
# idempotent required: true # header required (payments)
|
|
100
|
+
def idempotent(required: false)
|
|
101
|
+
@idempotency = { required: required }
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# rate_limit 10, per: 60
|
|
105
|
+
# rate_limit false
|
|
106
|
+
def rate_limit(limit, per: 60)
|
|
107
|
+
@rate_limit = limit == false ? false : [Integer(limit), Integer(per)]
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def handle(&block)
|
|
111
|
+
raise DefinitionError, "#{id}: handle needs a block" unless block
|
|
112
|
+
|
|
113
|
+
@handler = block
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
def summary(text) = @docs[:summary] = text
|
|
117
|
+
def description(text) = @docs[:description] = text
|
|
118
|
+
def tags(*names) = @docs[:tags] = names.flatten.map(&:to_s)
|
|
119
|
+
def deprecated! = @docs[:deprecated] = true
|
|
120
|
+
|
|
121
|
+
# ---- Validation --------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
def finalize!
|
|
124
|
+
problems = []
|
|
125
|
+
problems << "has no handler (add `handle { |params| ... }`)" unless @handler
|
|
126
|
+
unless @public || @authorizer
|
|
127
|
+
problems << "has no access rule (add `authorize { |user| ... }`, or `public!` for anonymous access)"
|
|
128
|
+
end
|
|
129
|
+
problems << "doesn't declare its response (add `returns SomeSchema`, or `returns nil` for 204)" unless @returns_set
|
|
130
|
+
if @pagination && @returns_schema.nil?
|
|
131
|
+
problems << "is paginated but returns nothing"
|
|
132
|
+
end
|
|
133
|
+
raise DefinitionError, "#{api.name || 'API'} #{id} #{problems.join('; ')}" if problems.any?
|
|
134
|
+
|
|
135
|
+
add_path_params_to_schema
|
|
136
|
+
freeze_definition
|
|
137
|
+
self
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
def effective_rate_limit(config)
|
|
141
|
+
@rate_limit == :default ? config.rate_limit : @rate_limit
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
private
|
|
145
|
+
|
|
146
|
+
def schema_prefix
|
|
147
|
+
"#{api.name.to_s.gsub('::', '')}#{verb.capitalize}#{path.gsub(/[^a-zA-Z0-9]+/, '_').split('_').map(&:capitalize).join}"
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
# Path params are always accepted; declare them in `params` to type them.
|
|
151
|
+
def add_path_params_to_schema
|
|
152
|
+
names = path_params
|
|
153
|
+
return if names.empty?
|
|
154
|
+
|
|
155
|
+
@params_schema ||= Schema.build("#{schema_prefix}Params")
|
|
156
|
+
missing = names.reject { |n| @params_schema.fields.key?(n.to_sym) }
|
|
157
|
+
return if missing.empty?
|
|
158
|
+
|
|
159
|
+
@params_schema = @params_schema.build(@params_schema.schema_name) do
|
|
160
|
+
missing.each { |n| required n.to_sym, :string, max_length: 512 }
|
|
161
|
+
end
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
def freeze_definition
|
|
165
|
+
@docs.freeze
|
|
166
|
+
end
|
|
167
|
+
end
|
|
168
|
+
end
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
module Whoosh
|
|
2
|
+
class Error < StandardError; end
|
|
3
|
+
|
|
4
|
+
# Raised while defining endpoints: a misconfigured endpoint stops the app
|
|
5
|
+
# from booting instead of failing open in production.
|
|
6
|
+
class DefinitionError < Error; end
|
|
7
|
+
|
|
8
|
+
# Every HTTP error renders as the same envelope:
|
|
9
|
+
# { "error": { "code": "...", "message": "...", "details": {...}, "request_id": "..." } }
|
|
10
|
+
class HTTPError < Error
|
|
11
|
+
attr_reader :status, :code, :details, :headers
|
|
12
|
+
|
|
13
|
+
def initialize(message = nil, status: 500, code: "internal_error", details: nil, headers: {})
|
|
14
|
+
@status = status
|
|
15
|
+
@code = code
|
|
16
|
+
@details = details
|
|
17
|
+
@headers = headers
|
|
18
|
+
super(message || default_message)
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def default_message = "Something went wrong."
|
|
22
|
+
|
|
23
|
+
def to_h
|
|
24
|
+
body = { code: code, message: message }
|
|
25
|
+
body[:details] = details if details && !details.empty?
|
|
26
|
+
body
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
{
|
|
31
|
+
BadRequest: [400, "bad_request", "The request couldn't be read."],
|
|
32
|
+
Unauthorized: [401, "unauthorized", "Sign in or send a valid token."],
|
|
33
|
+
Forbidden: [403, "forbidden", "You don't have permission to do that."],
|
|
34
|
+
NotFound: [404, "not_found", "Not found."],
|
|
35
|
+
MethodNotAllowed: [405, "method_not_allowed", "This path doesn't accept that method."],
|
|
36
|
+
Conflict: [409, "conflict", "The request conflicts with the current state."],
|
|
37
|
+
PayloadTooLarge: [413, "payload_too_large", "The request body is too large."],
|
|
38
|
+
UnsupportedMediaType: [415, "unsupported_media_type", "Send the body as application/json."],
|
|
39
|
+
UnprocessableEntity: [422, "validation_failed", "Some fields are invalid."],
|
|
40
|
+
TooManyRequests: [429, "rate_limited", "Too many requests. Try again later."],
|
|
41
|
+
InternalError: [500, "internal_error", "Something went wrong."]
|
|
42
|
+
}.each do |name, (status, code, message)|
|
|
43
|
+
klass = Class.new(HTTPError) do
|
|
44
|
+
define_method(:initialize) do |msg = nil, details: nil, headers: {}, code: nil|
|
|
45
|
+
super(msg || message, status: status, code: code || self.class::CODE, details: details, headers: headers)
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
klass.const_set(:STATUS, status)
|
|
49
|
+
klass.const_set(:CODE, code)
|
|
50
|
+
const_set(name, klass)
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Input that fails its schema. details maps field paths to messages:
|
|
54
|
+
# { "items[0].quantity" => ["must be at least 1"] }
|
|
55
|
+
class ValidationError < UnprocessableEntity
|
|
56
|
+
def initialize(errors, message = nil)
|
|
57
|
+
super(message, details: errors)
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def errors = details
|
|
61
|
+
end
|
|
62
|
+
end
|