respondo 2.1.2 → 2.2.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.
@@ -34,6 +34,17 @@ module Respondo
34
34
  # config.default_meta = { api_version: "v1", platform: "mobile" }
35
35
  attr_accessor :default_meta
36
36
 
37
+ # When true, passing a raw ActiveRecord model/relation as `data:` without a
38
+ # custom `config.serializer` raises Respondo::UnsafeSerializationError
39
+ # instead of emitting every column via #as_json. Recommended for production.
40
+ # When false (default) a one-time warning is logged per model class.
41
+ attr_accessor :strict_serialization
42
+
43
+ # Maximum number of records/elements a collection may contain when it is
44
+ # serialized. Larger collections raise Respondo::CollectionTooLargeError
45
+ # instead of loading everything into memory. nil (default) = no limit.
46
+ attr_accessor :max_collection_size
47
+
37
48
  def initialize
38
49
  @default_success_message = "Success"
39
50
  @default_error_message = "An error occurred"
@@ -41,6 +52,8 @@ module Respondo
41
52
  @camelize_keys = false
42
53
  @serializer = nil
43
54
  @default_meta = {} # e.g. { api_version: "v1", env: "production" }
55
+ @strict_serialization = false
56
+ @max_collection_size = nil
44
57
  end
45
58
  end
46
59
  end
@@ -1,4 +1,5 @@
1
1
  # frozen_string_literal: true
2
+ require "uri"
2
3
 
3
4
  module Respondo
4
5
  # Mixed into Rails controllers to provide render_success and render_error.
@@ -39,33 +40,6 @@ module Respondo
39
40
  # render_network_authentication_required
40
41
  module ControllerHelpers
41
42
 
42
- # =========================================================================
43
- # 1xx Informational helpers
44
- # NOTE: 1xx responses are protocol-level and don't carry a body in HTTP/1.1.
45
- # These helpers return a JSON body for API consistency / logging purposes,
46
- # but most HTTP clients will not receive them as normal responses.
47
- # =========================================================================
48
-
49
- # 100 Continue
50
- def render_continue(message: "Continue", meta: {})
51
- render_success(data: nil, message: message, meta: meta, code: 100, status: :continue)
52
- end
53
-
54
- # 101 Switching Protocols
55
- def render_switching_protocols(message: "Switching protocols", meta: {})
56
- render_success(data: nil, message: message, meta: meta, code: 101, status: :switching_protocols)
57
- end
58
-
59
- # 102 Processing (WebDAV)
60
- def render_processing(message: "Processing", meta: {})
61
- render_success(data: nil, message: message, meta: meta, code: 102, status: :processing)
62
- end
63
-
64
- # 103 Early Hints
65
- def render_early_hints(message: "Early hints", meta: {})
66
- render_success(data: nil, message: message, meta: meta, code: 103, status: :early_hints)
67
- end
68
-
69
43
  # =========================================================================
70
44
  # 2xx Success helpers
71
45
  # =========================================================================
@@ -124,26 +98,36 @@ module Respondo
124
98
  # =========================================================================
125
99
  # 3xx Redirect helpers
126
100
  # NOTE: Pass the target URL via meta: render_moved_permanently(meta: { redirect_url: new_url })
101
+ # Pass the target with `location:` — it is sent as a real Location header
102
+ # (and mirrored into meta[:redirect_url]):
103
+ # render_found(location: "/login")
104
+ # Only same-host or relative targets are accepted. A different host raises
105
+ # Respondo::UnsafeRedirectError unless `allow_other_host: true` is given.
106
+ # Never pass unvalidated user input together with allow_other_host: true.
127
107
  # =========================================================================
128
108
 
129
109
  # 300 Multiple Choices
130
- def render_multiple_choices(data: nil, message: "Multiple choices available", meta: {}, pagination: nil)
131
- render_success(data: data, message: message, meta: meta, pagination: pagination, code: 300, status: :multiple_choices)
110
+ def render_multiple_choices(data: nil, message: "Multiple choices available", meta: {}, pagination: nil, location: nil, allow_other_host: false)
111
+ render_success(data: data, message: message, meta: meta, pagination: pagination, code: 300, status: :multiple_choices,
112
+ location: location, allow_other_host: allow_other_host)
132
113
  end
133
114
 
134
115
  # 301 Moved Permanently
135
- def render_moved_permanently(message: "Resource has moved permanently", meta: {}, pagination: nil)
136
- render_success(data: nil, message: message, meta: meta, pagination: pagination, code: 301, status: :moved_permanently)
116
+ def render_moved_permanently(message: "Resource has moved permanently", meta: {}, pagination: nil, location: nil, allow_other_host: false)
117
+ render_success(data: nil, message: message, meta: meta, pagination: pagination, code: 301, status: :moved_permanently,
118
+ location: location, allow_other_host: allow_other_host)
137
119
  end
138
120
 
139
121
  # 302 Found (temporary redirect)
140
- def render_found(message: "Resource temporarily located elsewhere", meta: {}, pagination: nil)
141
- render_success(data: nil, message: message, meta: meta, pagination: pagination, code: 302, status: :found)
122
+ def render_found(message: "Resource temporarily located elsewhere", meta: {}, pagination: nil, location: nil, allow_other_host: false)
123
+ render_success(data: nil, message: message, meta: meta, pagination: pagination, code: 302, status: :found,
124
+ location: location, allow_other_host: allow_other_host)
142
125
  end
143
126
 
144
127
  # 303 See Other — redirect to another URI with GET
145
- def render_see_other(message: "See other resource", meta: {}, pagination: nil)
146
- render_success(data: nil, message: message, meta: meta, pagination: pagination, code: 303, status: :see_other)
128
+ def render_see_other(message: "See other resource", meta: {}, pagination: nil, location: nil, allow_other_host: false)
129
+ render_success(data: nil, message: message, meta: meta, pagination: pagination, code: 303, status: :see_other,
130
+ location: location, allow_other_host: allow_other_host)
147
131
  end
148
132
 
149
133
  # 304 Not Modified — client cache is still valid
@@ -152,13 +136,15 @@ module Respondo
152
136
  end
153
137
 
154
138
  # 307 Temporary Redirect — repeat request with same method to new URL
155
- def render_temporary_redirect(message: "Temporary redirect", meta: {}, pagination: nil)
156
- render_success(data: nil, message: message, meta: meta, pagination: pagination, code: 307, status: :temporary_redirect)
139
+ def render_temporary_redirect(message: "Temporary redirect", meta: {}, pagination: nil, location: nil, allow_other_host: false)
140
+ render_success(data: nil, message: message, meta: meta, pagination: pagination, code: 307, status: :temporary_redirect,
141
+ location: location, allow_other_host: allow_other_host)
157
142
  end
158
143
 
159
144
  # 308 Permanent Redirect — like 301 but method must not change
160
- def render_permanent_redirect(message: "Permanent redirect", meta: {}, pagination: nil)
161
- render_success(data: nil, message: message, meta: meta, pagination: pagination, code: 308, status: :permanent_redirect)
145
+ def render_permanent_redirect(message: "Permanent redirect", meta: {}, pagination: nil, location: nil, allow_other_host: false)
146
+ render_success(data: nil, message: message, meta: meta, pagination: pagination, code: 308, status: :permanent_redirect,
147
+ location: location, allow_other_host: allow_other_host)
162
148
  end
163
149
 
164
150
  # =========================================================================
@@ -232,7 +218,7 @@ module Respondo
232
218
 
233
219
  # 413 Payload Too Large — request body exceeds server limit
234
220
  def render_payload_too_large(message: "Payload too large", errors: nil, meta: {})
235
- render_error(message: message, errors: errors, meta: meta, code: 413, status: :payload_too_large)
221
+ render_error(message: message, errors: errors, meta: meta, code: 413, status: respondo_status(:content_too_large, :payload_too_large, 413))
236
222
  end
237
223
 
238
224
  # 414 URI Too Long — request URI exceeds server limit
@@ -257,7 +243,7 @@ module Respondo
257
243
 
258
244
  # 418 I'm a Teapot — RFC 2324
259
245
  def render_im_a_teapot(message: "I'm a teapot", errors: nil, meta: {})
260
- render_error(message: message, errors: errors, meta: meta, code: 418, status: :im_a_teapot)
246
+ render_error(message: message, errors: errors, meta: meta, code: 418, status: respondo_status(:im_a_teapot, 418))
261
247
  end
262
248
 
263
249
  # 421 Misdirected Request — request sent to wrong server
@@ -267,7 +253,7 @@ module Respondo
267
253
 
268
254
  # 422 Unprocessable Entity — validation errors (most common for APIs)
269
255
  def render_unprocessable(message: "Validation failed", errors: nil, meta: {})
270
- render_error(message: message, errors: errors, meta: meta, code: 422, status: :unprocessable_content)
256
+ render_error(message: message, errors: errors, meta: meta, code: 422, status: respondo_unprocessable_status)
271
257
  end
272
258
 
273
259
  # 423 Locked — resource is locked
@@ -361,7 +347,7 @@ module Respondo
361
347
 
362
348
  # 510 Not Extended — further extensions needed
363
349
  def render_not_extended(message: "Not extended", errors: nil, meta: {})
364
- render_error(message: message, errors: errors, meta: meta, code: 510, status: :not_extended)
350
+ render_error(message: message, errors: errors, meta: meta, code: 510, status: 510)
365
351
  end
366
352
 
367
353
  # 511 Network Authentication Required — must authenticate to access network
@@ -385,16 +371,24 @@ module Respondo
385
371
  # total_count: 100, next_page: 2, prev_page: nil }
386
372
  # Pass nil (default) to omit pagination from meta.
387
373
  # @param status [Symbol, Integer] HTTP status (default: :ok / 200)
388
- def render_success(data: nil, message: nil, meta: {}, code: nil, pagination: nil, status: :ok)
374
+ def render_success(data: nil, message: nil, meta: {}, code: nil, pagination: nil, status: :ok,
375
+ location: nil, allow_other_host: false)
376
+ meta = {} if meta.nil?
389
377
  merged_meta = code ? meta.merge(code: code, status: status) : meta
390
378
 
379
+ if location
380
+ safe_location = respondo_safe_location!(location, allow_other_host)
381
+ merged_meta = merged_meta.merge(redirect_url: safe_location)
382
+ respondo_set_location_header(safe_location)
383
+ end
384
+
391
385
  payload = ResponseBuilder.new(
392
386
  success: true,
393
387
  data: data,
394
388
  message: message,
395
389
  meta: merged_meta,
396
390
  pagination: pagination,
397
- request: try(:request)
391
+ request: respondo_request
398
392
  ).build
399
393
 
400
394
  render json: payload, status: status
@@ -409,6 +403,7 @@ module Respondo
409
403
  # @param status [Symbol, Integer] HTTP status (default: :unprocessable_entity / 422)
410
404
 
411
405
  def render_error(message: nil, errors: nil, code: nil, meta: {}, status: :unprocessable_entity)
406
+ meta = {} if meta.nil?
412
407
  extracted_errors = extract_errors(errors)
413
408
  merged_meta = code ? meta.merge(code: code, status: status) : meta
414
409
 
@@ -418,12 +413,75 @@ module Respondo
418
413
  message: message,
419
414
  meta: merged_meta,
420
415
  errors: extracted_errors,
421
- request: try(:request)
416
+ request: respondo_request
422
417
  ).build
423
418
 
424
419
  render json: payload, status: status
425
420
  end
426
421
 
422
+ # Rack 3.1+ renamed :unprocessable_entity to :unprocessable_content, and
423
+ # older Rack raises on the new name. Pick whichever the installed Rack knows.
424
+ def respondo_unprocessable_status
425
+ table = defined?(Rack::Utils::SYMBOL_TO_STATUS_CODE) ? Rack::Utils::SYMBOL_TO_STATUS_CODE : nil
426
+ return :unprocessable_entity if table && !table.key?(:unprocessable_content)
427
+ :unprocessable_content
428
+ end
429
+
430
+ # Picks the first status symbol the installed Rack knows (newest name first),
431
+ # or the plain numeric code if it knows none. Rack renames status symbols
432
+ # between versions (e.g. :payload_too_large -> :content_too_large in 3.1) and
433
+ # warns about / eventually removes the old names. Without Rack loaded the
434
+ # last (oldest) symbol is returned.
435
+ # respondo_status(:content_too_large, :payload_too_large, 413)
436
+ def respondo_status(*candidates, code)
437
+ table = defined?(Rack::Utils::SYMBOL_TO_STATUS_CODE) ? Rack::Utils::SYMBOL_TO_STATUS_CODE : nil
438
+ return candidates.last if table.nil?
439
+
440
+ candidates.find { |sym| table.key?(sym) } || code
441
+ end
442
+
443
+ # The current request, or nil outside Rails / when none is available.
444
+ def respondo_request
445
+ respond_to?(:request, true) ? request : nil
446
+ end
447
+
448
+ def respondo_set_location_header(location)
449
+ if respond_to?(:response, true) && response.respond_to?(:set_header)
450
+ response.set_header("Location", location)
451
+ end
452
+ end
453
+
454
+ # Validates a redirect target: no control characters (header injection),
455
+ # and either a relative path or the current host unless allow_other_host.
456
+ def respondo_safe_location!(location, allow_other_host)
457
+ str = location.to_s
458
+ raise UnsafeRedirectError, "Redirect location contains control characters" if str.match?(/[\x00-\x1f\x7f]/)
459
+ raise UnsafeRedirectError, "Redirect location is blank" if str.strip.empty?
460
+
461
+ # Browsers treat "//host" and "/\\host" as protocol-relative absolute URLs.
462
+ if str.start_with?("/")
463
+ return str unless str.start_with?("//", "/\\")
464
+ raise UnsafeRedirectError, "Protocol-relative redirect locations are not allowed" unless allow_other_host
465
+ return str
466
+ end
467
+
468
+ uri = begin
469
+ URI.parse(str)
470
+ rescue URI::InvalidURIError
471
+ raise UnsafeRedirectError, "Redirect location is not a valid URI"
472
+ end
473
+
474
+ unless %w[http https].include?(uri.scheme.to_s.downcase)
475
+ raise UnsafeRedirectError, "Redirect location must be http(s) or a relative path"
476
+ end
477
+
478
+ req = respondo_request
479
+ same_host = req.respond_to?(:host) && uri.host.to_s.casecmp?(req.host.to_s)
480
+ return str if same_host || allow_other_host
481
+
482
+ raise UnsafeRedirectError, "Redirect to another host requires allow_other_host: true"
483
+ end
484
+
427
485
  # Normalize errors into a plain Hash regardless of source type.
428
486
  def extract_errors(errors)
429
487
  return nil if errors.nil?
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Respondo
4
+ class Error < StandardError; end
5
+
6
+ # Raised when strict_serialization is on and a raw ActiveRecord object is
7
+ # passed as `data:` without a custom serializer.
8
+ class UnsafeSerializationError < Error; end
9
+
10
+ # Raised when a collection exceeds config.max_collection_size.
11
+ class CollectionTooLargeError < Error; end
12
+
13
+ # Raised when a redirect location is malformed or points to another host.
14
+ class UnsafeRedirectError < Error; end
15
+ end
@@ -33,7 +33,7 @@ module Respondo
33
33
  @success = success
34
34
  @raw_data = data
35
35
  @message = message
36
- @extra_meta = meta || {}
36
+ @extra_meta = normalize_meta(meta)
37
37
  @errors = errors
38
38
  @pagination = pagination
39
39
  @request = request
@@ -71,24 +71,32 @@ module Respondo
71
71
  def build_meta
72
72
  meta = {}
73
73
 
74
+ # Server-generated fields. These are computed up front, keep their
75
+ # position at the top of the meta block, and are re-applied after every
76
+ # caller-controlled merge below so caller input can never overwrite them.
74
77
  # 1. Request ID first (opt-in, always authoritative)
78
+ authoritative = {}
75
79
  if Respondo.config.include_request_id && @request&.respond_to?(:request_id)
76
- meta[:request_id] = @request.request_id
80
+ authoritative[:request_id] = @request.request_id
77
81
  end
78
82
 
79
83
  # 2. Timestamp second
80
- meta[:timestamp] = current_timestamp
84
+ authoritative[:timestamp] = current_timestamp
85
+ meta.merge!(authoritative)
81
86
 
82
- # 3. Global defaults in the middle (lowest priority)
83
- meta.merge!(Respondo.config.default_meta)
87
+ # 3. Global defaults (lowest priority of the caller-controlled sources)
88
+ meta.merge!(normalize_meta(Respondo.config.default_meta))
84
89
 
85
- # 4. Caller-supplied meta (overrides defaults)
90
+ # 4. Caller-supplied meta (overrides defaults, but not authoritative fields)
86
91
  meta.merge!(@extra_meta)
87
92
 
88
93
  # 5. Pagination — plain hash from the caller, placed last before code/status
89
94
  meta[:pagination] = @pagination if @pagination.is_a?(Hash) && !@pagination.empty?
90
95
 
91
96
  # 6. Re-pin code and status to the very end
97
+ # Re-assert authoritative fields (Hash#merge! keeps original key order)
98
+ meta.merge!(authoritative)
99
+ # Re-pin code and status to the very end
92
100
  code = meta.delete(:code)
93
101
  status = meta.delete(:status)
94
102
  meta[:code] = code if code
@@ -97,6 +105,15 @@ module Respondo
97
105
  meta
98
106
  end
99
107
 
108
+ # Accepts nil / Hash / anything responding to #to_h and returns a Hash with
109
+ # Symbol keys, so { "request_id" => "x" } cannot sneak past the symbol-keyed
110
+ # authoritative fields as a duplicate key.
111
+ def normalize_meta(meta)
112
+ return {} if meta.nil?
113
+ hash = meta.respond_to?(:to_h) ? meta.to_h : {}
114
+ hash.each_with_object({}) { |(k, v), memo| memo[k.respond_to?(:to_sym) ? k.to_sym : k] = v }
115
+ end
116
+
100
117
  def current_timestamp
101
118
  if Time.respond_to?(:current)
102
119
  Time.current.iso8601
@@ -110,11 +127,19 @@ module Respondo
110
127
  camelize_hash(hash)
111
128
  end
112
129
 
130
+ # Recursively camelizes hash keys. If two different keys in the same hash
131
+ # would collapse to the same camelized key (e.g. "user_id" and "userId"),
132
+ # the colliding keys are left exactly as they were so no value is silently
133
+ # overwritten.
113
134
  def camelize_hash(obj)
114
135
  case obj
115
136
  when Hash
116
- obj.each_with_object({}) do |(k, v), memo|
117
- memo[camelize_key(k)] = camelize_hash(v)
137
+ targets = obj.keys.map { |k| camelize_key(k) }
138
+ counts = targets.tally
139
+
140
+ obj.each_with_object({}).with_index do |((k, v), memo), i|
141
+ new_key = counts[targets[i]] > 1 ? k : targets[i]
142
+ memo[new_key] = camelize_hash(v)
118
143
  end
119
144
  when Array
120
145
  obj.map { |item| camelize_hash(item) }
@@ -25,16 +25,19 @@ module Respondo
25
25
 
26
26
  # 2. ActiveRecord::Relation or any object with #map (lazy collections)
27
27
  if ar_relation?(object)
28
- return object.map { |record| serialize_record(record) }
28
+ guard_raw_record!(object)
29
+ return load_relation(object).map { |record| serialize_record(record) }
29
30
  end
30
31
 
31
32
  # 3. Array — recurse
32
33
  if object.is_a?(Array)
34
+ enforce_collection_limit!(object.size)
33
35
  return object.map { |item| call(item) }
34
36
  end
35
37
 
36
38
  # 4. ActiveRecord model instance
37
39
  if ar_model?(object)
40
+ guard_raw_record!(object)
38
41
  return serialize_record(object)
39
42
  end
40
43
 
@@ -67,6 +70,49 @@ module Respondo
67
70
  object
68
71
  end
69
72
 
73
+ def load_relation(relation)
74
+ max = Respondo.config.max_collection_size
75
+ return relation unless max
76
+
77
+ records = relation.respond_to?(:limit) ? relation.limit(max + 1).to_a : relation.to_a
78
+ enforce_collection_limit!(records.size)
79
+ records
80
+ end
81
+
82
+ def enforce_collection_limit!(size)
83
+ max = Respondo.config.max_collection_size
84
+ return unless max && size > max
85
+
86
+ raise CollectionTooLargeError,
87
+ "Collection has more than #{max} items (config.max_collection_size)"
88
+ end
89
+
90
+ # Raw ActiveRecord objects expose every column through #as_json, including
91
+ # tokens and digests. Fail (strict) or warn once per class (default).
92
+ def guard_raw_record!(object)
93
+ klass = object.class
94
+
95
+ if Respondo.config.strict_serialization
96
+ raise UnsafeSerializationError,
97
+ "#{klass.name || klass} was passed as data: without a serializer. Set config.serializer " \
98
+ "or pass an explicit hash (e.g. record.as_json(only: [...]))."
99
+ end
100
+
101
+ label = klass.name || klass.to_s
102
+ @warned_classes ||= {}
103
+ return if @warned_classes[label]
104
+
105
+ @warned_classes[label] = true
106
+ message = "[Respondo] #{label} serialized with all attributes via #as_json. " \
107
+ "Configure config.serializer or pass `record.as_json(only: [...])` " \
108
+ "to avoid exposing sensitive columns (set config.strict_serialization = true to enforce)."
109
+ if defined?(Rails) && Rails.respond_to?(:logger) && Rails.logger
110
+ Rails.logger.warn(message)
111
+ else
112
+ Kernel.warn(message)
113
+ end
114
+ end
115
+
70
116
  private
71
117
 
72
118
  module_function
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Respondo
4
- VERSION = "2.1.2"
4
+ VERSION = "2.2.0"
5
5
  end
data/lib/respondo.rb CHANGED
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "respondo/version"
4
+ require_relative "respondo/errors"
4
5
  require_relative "respondo/configuration"
5
6
  require_relative "respondo/serializer"
6
7
  # require_relative "respondo/pagination"
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: respondo
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.1.2
4
+ version: 2.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - shailendra Kumar
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-05-13 00:00:00.000000000 Z
11
+ date: 2026-11-06 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: railties
@@ -98,6 +98,7 @@ files:
98
98
  - lib/respondo.rb
99
99
  - lib/respondo/configuration.rb
100
100
  - lib/respondo/controller_helpers.rb
101
+ - lib/respondo/errors.rb
101
102
  - lib/respondo/railtie.rb
102
103
  - lib/respondo/response_builder.rb
103
104
  - lib/respondo/serializer.rb