boto-rb 0.7.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.
@@ -0,0 +1,283 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "rack/utils"
5
+
6
+ module Boto
7
+ # Rack app for one project. Discovers the endpoints under a namespace at boot and
8
+ # dispatches each request through a router compiled once.
9
+ class App
10
+ class BootError < StandardError; end
11
+
12
+ Entry = Data.define(
13
+ :endpoint, :status, :needs_input, :needs_query, :body_schema, :return_schema, :returns_list, :handler
14
+ )
15
+
16
+ JSON_HEADERS_TYPE = "application/json"
17
+ NO_CONTENT = 204
18
+ INTERNAL_ERROR = 500
19
+ EMPTY = {}.freeze
20
+ NO_INPUT = [EMPTY, EMPTY].freeze
21
+ HEAD = "HEAD"
22
+ ROOT_PATH = "/"
23
+ DEVELOPMENT = "development"
24
+ BODY_PARAM = "body"
25
+ GET = "GET"
26
+ OPENAPI_PATH = "/openapi.json"
27
+ OPENAPI_VERSION = "development"
28
+ PATH_PARAMS_KEY = "boto.path_params"
29
+ GLOBAL_SCOPE = :global
30
+ AUTH_PLUGIN = :auth
31
+
32
+ attr_reader :endpoints, :title
33
+
34
+ def initialize(namespace:, plugins: [], env_name: ENV.fetch("BOTO_ENV", "production"), error_output: $stderr)
35
+ @env_name = env_name
36
+ @error_output = error_output
37
+ @title = namespace.name.freeze
38
+ @global_plugins, @endpoint_plugins = ordered(plugins).partition { |plugin| plugin.class.scope == GLOBAL_SCOPE }
39
+ @auth_by_endpoint = {}
40
+ @router = Router.new
41
+ @endpoints = discover(namespace).each { |endpoint| register(endpoint) }.freeze
42
+ @router.compile
43
+ @handler = Boto::Plugin::Stack.build(@global_plugins, method(:dispatch))
44
+ @openapi_json = build_openapi_json
45
+ end
46
+
47
+ def call(env)
48
+ response = handle(env)
49
+ env["REQUEST_METHOD"] == HEAD ? [response[0], response[1], []] : response
50
+ end
51
+
52
+ # The instance of :auth that guards the endpoint, or nil when the endpoint is not authenticated.
53
+ def auth_for(endpoint)
54
+ @auth_by_endpoint[endpoint]
55
+ end
56
+
57
+ private
58
+
59
+ def handle(env)
60
+ @handler.call(env)
61
+ rescue Boto::Error => e
62
+ e.to_response
63
+ rescue StandardError => e
64
+ internal_error_response(e)
65
+ end
66
+
67
+ def discover(namespace)
68
+ found = []
69
+ collect(namespace, "#{namespace.name}::", Set[namespace], found)
70
+ found.sort_by(&:name)
71
+ end
72
+
73
+ def collect(mod, prefix, visited, found)
74
+ mod.constants(false).each do |const_name|
75
+ value = mod.const_get(const_name, false)
76
+ next unless inside_namespace?(value, prefix) && visited.add?(value)
77
+
78
+ found << value if endpoint?(value)
79
+ collect(value, prefix, visited, found)
80
+ end
81
+ end
82
+
83
+ def inside_namespace?(value, prefix)
84
+ value.is_a?(Module) && value.name&.start_with?(prefix)
85
+ end
86
+
87
+ def endpoint?(value)
88
+ value < Boto::Endpoint && !value.route.nil?
89
+ end
90
+
91
+ def register(endpoint)
92
+ check_path_params!(endpoint)
93
+ endpoint.compile!
94
+ check_skips!(endpoint)
95
+ plugins = endpoint_plugins_for(endpoint)
96
+ @auth_by_endpoint[endpoint] = plugins.find { |plugin| plugin.class.plugin_name == AUTH_PLUGIN }
97
+ @router.add(*endpoint.route, entry_for(endpoint, plugins))
98
+ rescue Router::DuplicateRouteError, ArgumentError => e
99
+ raise BootError, "#{endpoint.name}: #{e.message}"
100
+ end
101
+
102
+ def check_path_params!(endpoint)
103
+ missing = endpoint.path_param_names - endpoint.params.names
104
+ return if missing.empty?
105
+
106
+ raise BootError, "#{endpoint.name}: path param :#{missing.first} is not declared"
107
+ end
108
+
109
+ def check_skips!(endpoint)
110
+ endpoint.skipped_plugins.each { |name| check_skip!(endpoint, name) }
111
+ end
112
+
113
+ def check_skip!(endpoint, name)
114
+ raise BootError, "#{endpoint.name}: cannot skip global plugin :#{name}" if plugin_named?(@global_plugins, name)
115
+ return if plugin_named?(@endpoint_plugins, name)
116
+
117
+ raise BootError, "#{endpoint.name}: skip :#{name} but plugin :#{name} is not enabled"
118
+ end
119
+
120
+ def plugin_named?(plugins, name)
121
+ plugins.any? { |plugin| plugin.class.plugin_name == name }
122
+ end
123
+
124
+ def endpoint_plugins_for(endpoint)
125
+ plugins = @endpoint_plugins.reject { |plugin| endpoint.skipped_plugins.include?(plugin.class.plugin_name) }
126
+ return plugins unless endpoint.authentication
127
+
128
+ kept = plugins.reject { |plugin| plugin.class.plugin_name == AUTH_PLUGIN }
129
+ ordered(kept << endpoint_auth(endpoint))
130
+ end
131
+
132
+ def endpoint_auth(endpoint)
133
+ strategy, options = endpoint.authentication
134
+ Configuration.new(env_name: @env_name).use(AUTH_PLUGIN, strategy: strategy, **options).plugin(AUTH_PLUGIN)
135
+ end
136
+
137
+ def ordered(plugins)
138
+ plugins.sort_by.with_index { |plugin, index| [plugin.class.order_index, index] }
139
+ end
140
+
141
+ def entry_for(endpoint, plugins)
142
+ needs_query = needs_query?(endpoint)
143
+ base = Entry.new(
144
+ endpoint: endpoint, status: endpoint.default_status,
145
+ needs_input: needs_query || !endpoint.body_schema.nil?, needs_query: needs_query,
146
+ body_schema: endpoint.body_schema, return_schema: endpoint.return_schema,
147
+ returns_list: endpoint.returns_list?, handler: nil
148
+ )
149
+ return base if plugins.empty?
150
+
151
+ base.with(handler: Boto::Plugin::Stack.build(plugins, endpoint_handler(base)))
152
+ end
153
+
154
+ def endpoint_handler(entry)
155
+ ->(env) { run(entry, env[PATH_PARAMS_KEY], env) }
156
+ end
157
+
158
+ def needs_query?(endpoint)
159
+ !(endpoint.params.names - endpoint.path_param_names).empty?
160
+ end
161
+
162
+ def dispatch(env)
163
+ verb = env["REQUEST_METHOD"]
164
+ path = request_path(env)
165
+ match = @router.match(verb, path)
166
+ return unmatched_response(verb, path) unless match
167
+
168
+ respond(match, env)
169
+ rescue Boto::Error => e
170
+ e.to_response
171
+ rescue StandardError => e
172
+ internal_error_response(e)
173
+ end
174
+
175
+ def respond(match, env)
176
+ entry = match.target
177
+ return run(entry, match.params, env) unless entry.handler
178
+
179
+ env[PATH_PARAMS_KEY] = match.params
180
+ entry.handler.call(env)
181
+ end
182
+
183
+ def build_openapi_json
184
+ return nil unless @env_name == DEVELOPMENT
185
+
186
+ JSON.generate(Boto::OpenAPI.generate(self, title: title, version: OPENAPI_VERSION)).freeze
187
+ end
188
+
189
+ def openapi_request?(verb, path)
190
+ !@openapi_json.nil? && (verb == GET || verb == HEAD) && path == OPENAPI_PATH
191
+ end
192
+
193
+ def openapi_response
194
+ [200, { "content-type" => JSON_HEADERS_TYPE }, [@openapi_json]]
195
+ end
196
+
197
+ def request_path(env)
198
+ path = env["PATH_INFO"].to_s
199
+ path.empty? ? ROOT_PATH : path
200
+ end
201
+
202
+ # Runs only when no route matched, so a user endpoint on OPENAPI_PATH wins and matched requests pay nothing.
203
+ def unmatched_response(verb, path)
204
+ return openapi_response if openapi_request?(verb, path)
205
+
206
+ allowed = @router.allowed_verbs(path)
207
+ return Boto::Error::NotFound.new.to_response if allowed.empty?
208
+
209
+ Boto::Error::MethodNotAllowed.new(allowed).to_response
210
+ end
211
+
212
+ def run(entry, path_params, env)
213
+ args = entry.body_schema ? body_args(entry, path_params, env) : plain_args(entry, path_params, env)
214
+ success_response(entry, entry.endpoint.new(env).call(**args))
215
+ end
216
+
217
+ def plain_args(entry, path_params, env)
218
+ query, body = entry.needs_input ? read_input(env) : NO_INPUT
219
+ entry.endpoint.params.call(path: path_params, query: query, body: body)
220
+ end
221
+
222
+ # The body is read once, through the schema; params only see the query, so they never touch the body.
223
+ def body_args(entry, path_params, env)
224
+ query = entry.needs_query ? query_hash(env) : EMPTY
225
+ args = entry.endpoint.params.call(path: path_params, query: query, body: EMPTY)
226
+ args.merge(body: coerce_body(entry.body_schema, env))
227
+ end
228
+
229
+ def read_input(env)
230
+ [query_hash(env), Boto::RequestBody.parse(env)]
231
+ end
232
+
233
+ def query_hash(env)
234
+ Rack::Utils.parse_query(env["QUERY_STRING"].to_s)
235
+ end
236
+
237
+ def coerce_body(schema, env)
238
+ schema.coerce(Boto::RequestBody.parse(env))
239
+ rescue Types::Invalid => e
240
+ raise Boto::Error::Unprocessable.new(body_errors(e.errors))
241
+ end
242
+
243
+ def body_errors(errors)
244
+ errors.map { |error| { param: error_param(error[:path]), message: error[:message] } }
245
+ end
246
+
247
+ def error_param(path)
248
+ path.empty? ? BODY_PARAM : path
249
+ end
250
+
251
+ def success_response(entry, result)
252
+ return [NO_CONTENT, {}, []] if result.nil?
253
+
254
+ payload = entry.return_schema ? serialize_result(entry, result) : result
255
+ [entry.status, { "content-type" => JSON_HEADERS_TYPE }, [JSON.generate(payload)]]
256
+ end
257
+
258
+ def serialize_result(entry, result)
259
+ return entry.return_schema.serialize(result) unless entry.returns_list
260
+
261
+ serialize_list(entry, result)
262
+ end
263
+
264
+ def serialize_list(entry, result)
265
+ # Any collection with map (Array, ORM relation) is accepted; a Hash would iterate pairs.
266
+ if result.is_a?(Hash) || !result.respond_to?(:map)
267
+ raise Boto::Schema::OutputError, "#{entry.endpoint.name} must return a list"
268
+ end
269
+
270
+ result.map { |item| entry.return_schema.serialize(item) }
271
+ end
272
+
273
+ def internal_error_response(error)
274
+ log_error(error)
275
+ detail = "#{error.class}: #{error.message}" if @env_name == DEVELOPMENT
276
+ Boto::Problem.response(INTERNAL_ERROR, detail: detail)
277
+ end
278
+
279
+ def log_error(error)
280
+ @error_output.puts(["#{error.class}: #{error.message}", *error.backtrace])
281
+ end
282
+ end
283
+ end
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rack/utils"
4
+
5
+ module Boto
6
+ # Base error. Each subclass maps to an HTTP status and renders as a problem response.
7
+ class Error < StandardError
8
+ STATUS = 500
9
+ NO_HEADERS = {}.freeze
10
+
11
+ attr_reader :detail
12
+
13
+ def initialize(detail = nil)
14
+ @detail = detail
15
+ super(detail || Rack::Utils::HTTP_STATUS_CODES.fetch(self.class::STATUS))
16
+ end
17
+
18
+ def status
19
+ self.class::STATUS
20
+ end
21
+
22
+ def errors
23
+ nil
24
+ end
25
+
26
+ def headers
27
+ NO_HEADERS
28
+ end
29
+
30
+ def to_response
31
+ Problem.response(status, detail: detail, errors: errors, headers: headers)
32
+ end
33
+
34
+ class BadRequest < Error
35
+ STATUS = 400
36
+ end
37
+
38
+ class NotFound < Error
39
+ STATUS = 404
40
+ end
41
+
42
+ class MethodNotAllowed < Error
43
+ STATUS = 405
44
+
45
+ attr_reader :allowed
46
+
47
+ def initialize(allowed, detail = nil)
48
+ @allowed = allowed
49
+ super(detail)
50
+ end
51
+
52
+ def headers
53
+ { "allow" => allowed.join(", ") }
54
+ end
55
+ end
56
+
57
+ class PayloadTooLarge < Error
58
+ STATUS = 413
59
+ end
60
+
61
+ class Unprocessable < Error
62
+ STATUS = 422
63
+
64
+ attr_reader :errors
65
+
66
+ def initialize(errors, detail = nil)
67
+ @errors = errors
68
+ super(detail)
69
+ end
70
+ end
71
+
72
+ class Unauthorized < Error
73
+ STATUS = 401
74
+
75
+ attr_reader :challenge
76
+
77
+ def initialize(challenge = nil, detail = nil)
78
+ @challenge = challenge
79
+ super(detail)
80
+ end
81
+
82
+ def headers
83
+ challenge ? { "www-authenticate" => challenge } : NO_HEADERS
84
+ end
85
+ end
86
+
87
+ class Forbidden < Error
88
+ STATUS = 403
89
+ end
90
+
91
+ class TooManyRequests < Error
92
+ STATUS = 429
93
+
94
+ attr_reader :retry_after
95
+
96
+ def initialize(retry_after, detail = nil)
97
+ @retry_after = retry_after
98
+ super(detail)
99
+ end
100
+
101
+ def headers
102
+ { "retry-after" => retry_after.to_s }
103
+ end
104
+ end
105
+
106
+ class ServiceUnavailable < Error
107
+ STATUS = 503
108
+
109
+ attr_reader :retry_after
110
+
111
+ def initialize(detail = nil, retry_after: nil)
112
+ @retry_after = retry_after
113
+ super(detail)
114
+ end
115
+
116
+ def headers
117
+ retry_after ? { "retry-after" => retry_after.to_s } : NO_HEADERS
118
+ end
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "rack/utils"
5
+
6
+ module Boto
7
+ # Builds RFC 9457 "application/problem+json" Rack responses.
8
+ module Problem
9
+ CONTENT_TYPE = "application/problem+json"
10
+
11
+ def self.response(status, detail: nil, errors: nil, headers: {})
12
+ body = JSON.generate(compact_body(status, detail, errors))
13
+ [status, { "content-type" => CONTENT_TYPE }.merge(headers), [body]]
14
+ end
15
+
16
+ def self.compact_body(status, detail, errors)
17
+ {
18
+ type: "about:blank",
19
+ title: Rack::Utils::HTTP_STATUS_CODES.fetch(status),
20
+ status: status,
21
+ detail: detail,
22
+ errors: errors
23
+ }.compact
24
+ end
25
+ private_class_method :compact_body
26
+ end
27
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Boto
6
+ # Reads and parses JSON request bodies, rejecting bodies above a size limit.
7
+ module RequestBody
8
+ DEFAULT_LIMIT = 1_048_576
9
+ EMPTY = {}.freeze
10
+ JSON_MEDIA_TYPE = "application/json"
11
+ JSON_SUFFIX = "+json"
12
+
13
+ def self.parse(env, limit: DEFAULT_LIMIT)
14
+ return EMPTY unless json_content_type?(env["CONTENT_TYPE"])
15
+
16
+ check_declared_length(env["CONTENT_LENGTH"], limit)
17
+ raw = read_body(env["rack.input"], limit)
18
+ return EMPTY if raw.nil? || raw.empty?
19
+
20
+ decode(raw)
21
+ end
22
+
23
+ def self.json_content_type?(content_type)
24
+ media_type = content_type.to_s.partition(";").first.strip.downcase
25
+ media_type == JSON_MEDIA_TYPE || media_type.end_with?(JSON_SUFFIX)
26
+ end
27
+
28
+ def self.check_declared_length(content_length, limit)
29
+ return if content_length.nil?
30
+
31
+ raise Boto::Error::PayloadTooLarge if content_length.to_i > limit
32
+ end
33
+
34
+ # Reads one byte past the limit so an oversized body is detected without buffering it whole.
35
+ def self.read_body(input, limit)
36
+ return if input.nil?
37
+
38
+ raw = input.read(limit + 1)
39
+ raise Boto::Error::PayloadTooLarge if raw && raw.bytesize > limit
40
+
41
+ raw
42
+ end
43
+
44
+ def self.decode(raw)
45
+ parsed = parse_json(raw)
46
+ raise Boto::Error::BadRequest.new("JSON body must be an object") unless parsed.is_a?(Hash)
47
+
48
+ parsed
49
+ end
50
+
51
+ def self.parse_json(raw)
52
+ JSON.parse(raw)
53
+ rescue JSON::ParserError
54
+ raise Boto::Error::BadRequest.new("invalid JSON body")
55
+ end
56
+
57
+ private_class_method :json_content_type?, :check_declared_length, :read_body, :decode, :parse_json
58
+ end
59
+ end
@@ -0,0 +1,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rack/utils"
4
+
5
+ module Boto
6
+ # Radix-style router: static segments win over dynamic ones, with backtracking.
7
+ class Router
8
+ # A plain class instead of Data: Data.new builds an internal Hash on every call.
9
+ class Match
10
+ attr_reader :target, :params
11
+
12
+ def initialize(target, params)
13
+ @target = target
14
+ @params = params
15
+ freeze
16
+ end
17
+ end
18
+
19
+ class DuplicateRouteError < StandardError; end
20
+
21
+ class Node
22
+ attr_reader :static, :handlers
23
+ attr_accessor :dynamic
24
+
25
+ def initialize
26
+ @static = {}
27
+ @dynamic = nil
28
+ @handlers = {}
29
+ end
30
+
31
+ def freeze
32
+ static.each_value(&:freeze)
33
+ dynamic&.freeze
34
+ handlers.freeze
35
+ static.freeze
36
+ super
37
+ end
38
+ end
39
+
40
+ EMPTY_PARAMS = {}.freeze
41
+
42
+ SEPARATOR = "/"
43
+ PERCENT = "%"
44
+ DYNAMIC_PREFIX = ":"
45
+ VERB_GET = "GET"
46
+ VERB_HEAD = "HEAD"
47
+
48
+ def initialize
49
+ @root = Node.new
50
+ end
51
+
52
+ def add(verb, pattern, target)
53
+ segments = segments_of(pattern)
54
+ leaf = segments.reduce(@root) { |node, segment| child_for_add(node, segment) }
55
+ raise DuplicateRouteError, "route #{verb} #{pattern} is already registered" if leaf.handlers.key?(verb)
56
+
57
+ leaf.handlers[verb] = [target, param_names_of(segments).freeze]
58
+ self
59
+ end
60
+
61
+ def compile
62
+ @root.freeze
63
+ self
64
+ end
65
+
66
+ def match(verb, path)
67
+ values = []
68
+ handler = resolve(@root, segments_of(path), 0, verb, values)
69
+ Match.new(handler[0], params_for(handler[1], values)) if handler
70
+ end
71
+
72
+ def allowed_verbs(path)
73
+ verbs = leaf_verbs(@root, segments_of(path), 0).uniq
74
+ verbs << VERB_HEAD if verbs.include?(VERB_GET) && !verbs.include?(VERB_HEAD)
75
+ verbs.sort
76
+ end
77
+
78
+ private
79
+
80
+ # Walks the path by byte offsets so no intermediate arrays or empty strings are built.
81
+ def segments_of(path)
82
+ segments = []
83
+ start = 0
84
+ while start < path.bytesize
85
+ separator = path.byteindex(SEPARATOR, start) || path.bytesize
86
+ segments << path.byteslice(start, separator - start) if separator > start
87
+ start = separator + SEPARATOR.bytesize
88
+ end
89
+ segments
90
+ end
91
+
92
+ # Rack's unescape is only needed when a percent-escape is present.
93
+ def unescape(segment)
94
+ segment.include?(PERCENT) ? Rack::Utils.unescape_path(segment) : segment
95
+ end
96
+
97
+ def dynamic_segment?(segment)
98
+ segment.start_with?(DYNAMIC_PREFIX)
99
+ end
100
+
101
+ def param_names_of(segments)
102
+ segments.filter_map { |segment| segment[1..].to_sym if dynamic_segment?(segment) }
103
+ end
104
+
105
+ def child_for_add(node, segment)
106
+ if dynamic_segment?(segment)
107
+ node.dynamic ||= Node.new
108
+ else
109
+ node.static[segment] ||= Node.new
110
+ end
111
+ end
112
+
113
+ # Returns [target, param_names] for the leaf handling verb, filling values with captured segments.
114
+ def resolve(node, segments, index, verb, values)
115
+ return handler_for(node, verb) if index == segments.size
116
+
117
+ segment = segments[index]
118
+ handler = resolve_static(node, segment, segments, index, verb, values)
119
+ handler || resolve_dynamic(node, segment, segments, index, verb, values)
120
+ end
121
+
122
+ def resolve_static(node, segment, segments, index, verb, values)
123
+ child = node.static[segment]
124
+ child && resolve(child, segments, index + 1, verb, values)
125
+ end
126
+
127
+ def resolve_dynamic(node, segment, segments, index, verb, values)
128
+ return unless node.dynamic
129
+
130
+ values.push(unescape(segment))
131
+ handler = resolve(node.dynamic, segments, index + 1, verb, values)
132
+ values.pop unless handler
133
+ handler
134
+ end
135
+
136
+ def handler_for(node, verb)
137
+ node.handlers[verb] || head_fallback(node, verb)
138
+ end
139
+
140
+ def head_fallback(node, verb)
141
+ node.handlers[VERB_GET] if verb == VERB_HEAD
142
+ end
143
+
144
+ def params_for(names, values)
145
+ return EMPTY_PARAMS if names.empty?
146
+
147
+ # A while loop avoids the block and enumerator objects of each_with_index.
148
+ params = {}
149
+ index = 0
150
+ while index < names.size
151
+ params[names[index]] = values[index]
152
+ index += 1
153
+ end
154
+ params
155
+ end
156
+
157
+ def leaf_verbs(node, segments, index)
158
+ return node.handlers.keys if index == segments.size
159
+
160
+ segment = segments[index]
161
+ verbs = []
162
+ child = node.static[segment]
163
+ verbs.concat(leaf_verbs(child, segments, index + 1)) if child
164
+ verbs.concat(leaf_verbs(node.dynamic, segments, index + 1)) if node.dynamic
165
+ verbs
166
+ end
167
+ end
168
+ end