respondo 2.1.3 → 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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +47 -0
- data/README.md +34 -5
- data/lib/generators/respondo/install/install_generator.rb +109 -11
- data/lib/respondo/configuration.rb +13 -0
- data/lib/respondo/controller_helpers.rb +104 -46
- data/lib/respondo/errors.rb +15 -0
- data/lib/respondo/response_builder.rb +33 -8
- data/lib/respondo/serializer.rb +47 -1
- data/lib/respondo/version.rb +1 -1
- data/lib/respondo.rb +1 -0
- metadata +3 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: d6ca76a634ae41adbeeb0a8a5fa4e7821497b38fde9eca353660ec309560871a
|
|
4
|
+
data.tar.gz: d9dd248b313227e38377e5cc378408ef5f0b8a6d9c96876accfebb3d259c9937
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 5deece2436f11c11c864c9df1907cef64b2d2225c6fc3867c98fbda0fe3757fa5ee2250bfb0d55ca525e8251df752aa2b86ee070cc04b2fdeaf789b77e6ec59a
|
|
7
|
+
data.tar.gz: 6bf043bca44a2d60be789e3f7a53b7d9a142b01df51c7527e037fac657d50af3f51af383dcd77178a09eb961047715a5b9963f8ad896d02b88924b9e3ee52b3d
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [2.2.0] — Security hardening
|
|
4
|
+
|
|
5
|
+
Fixes from an independent security assessment of 2.1.3. Upgrade notes are at the bottom.
|
|
6
|
+
|
|
7
|
+
### Security
|
|
8
|
+
- **Install generator code injection (CWE-94).** Keys entered for `default_meta` were written
|
|
9
|
+
unescaped into `config/initializers/respondo.rb`, which Rails executes on boot. Keys are now
|
|
10
|
+
validated (`/\A[a-z_][a-z0-9_]*\z/i`) and emitted through a safe literal. Project name is
|
|
11
|
+
single-lined. An existing initializer is backed up to `respondo.rb.bak` instead of silently overwritten.
|
|
12
|
+
- **Excessive data exposure.** New `config.strict_serialization` raises
|
|
13
|
+
`Respondo::UnsafeSerializationError` when a raw ActiveRecord model/relation is passed without a
|
|
14
|
+
serializer; otherwise a one-time warning is logged per model class. README now leads with
|
|
15
|
+
allow-listed output.
|
|
16
|
+
- **`meta` can no longer spoof `request_id` / `timestamp`.** They are applied after all
|
|
17
|
+
caller/default meta, string-keyed meta is normalised so no duplicate keys appear.
|
|
18
|
+
- **Redirect helpers** accept `location:` and send a real `Location` header. Targets are limited
|
|
19
|
+
to relative paths / same host (`allow_other_host: true` to opt out); CR/LF, protocol-relative and
|
|
20
|
+
non-http(s) targets are rejected.
|
|
21
|
+
- **Unbounded collections.** New `config.max_collection_size` (default `nil`, i.e. unchanged) raises
|
|
22
|
+
`Respondo::CollectionTooLargeError`; relations are capped in SQL with `LIMIT max+1`.
|
|
23
|
+
- README `rescue_from` example no longer returns `e.message` to clients.
|
|
24
|
+
|
|
25
|
+
### Fixed
|
|
26
|
+
- `camelize_keys` no longer silently drops a value when two keys collapse to the same camelCase
|
|
27
|
+
name (`user_id` + `userId`); colliding keys are left unchanged.
|
|
28
|
+
- `meta: nil` no longer raises `NoMethodError` in every code-setting helper.
|
|
29
|
+
- Helpers no longer depend on ActiveSupport's `#try`, so manual inclusion outside Rails works.
|
|
30
|
+
- `render_im_a_teapot` crashed on Rack 2.x ("Unrecognized status code :im_a_teapot", found by running a real Rails 6.1 app against every helper); it now falls back to the number 418 when Rack has no symbol for it.
|
|
31
|
+
- Rack 3.1+ deprecation warnings: `render_payload_too_large` now uses `:content_too_large` when Rack knows it, and `render_not_extended` sends the number 510 (Rack deprecated the `:not_extended` symbol). Found by running the demo app on Rails 8.1.
|
|
32
|
+
- `render_unprocessable` picks `:unprocessable_content` or `:unprocessable_entity` depending on the
|
|
33
|
+
installed Rack (older Rack rejects the new name).
|
|
34
|
+
- Generator no longer uses Ruby 3-only endless method definitions.
|
|
35
|
+
|
|
36
|
+
### Removed (breaking)
|
|
37
|
+
- `render_continue`, `render_switching_protocols`, `render_processing`, `render_early_hints`.
|
|
38
|
+
1xx statuses are interim protocol responses; sending a JSON body with them can desync clients and
|
|
39
|
+
proxies. Use a normal 2xx helper, or Rails' `head`/`send_early_hints`.
|
|
40
|
+
|
|
41
|
+
### Changed (breaking)
|
|
42
|
+
- Caller-supplied `meta: { timestamp: ... }` is now ignored (the server timestamp always wins).
|
|
43
|
+
|
|
44
|
+
### Upgrading from 2.x
|
|
45
|
+
1. Replace any use of the four 1xx helpers.
|
|
46
|
+
2. If you relied on overriding `meta[:timestamp]`/`meta[:request_id]`, put your value under a different key.
|
|
47
|
+
3. Recommended: set `config.strict_serialization = true` and a `config.max_collection_size`.
|
|
48
|
+
4. Redirect helpers: pass `location:` instead of `meta: { redirect_url: ... }`.
|
|
49
|
+
|
|
3
50
|
## [2.1.3] — Docs & Dependency Updates
|
|
4
51
|
|
|
5
52
|
### Changed
|
data/README.md
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
Consistent JSON API responses for Rails, in one line.
|
|
6
6
|
|
|
7
|
+
[](https://github.com/spatelpatidar/respondo/actions/workflows/ci.yml)
|
|
7
8
|
[](https://rubygems.org/gems/respondo)
|
|
8
9
|
[](https://rubygems.org/gems/respondo)
|
|
9
10
|
[](LICENSE)
|
|
@@ -205,6 +206,22 @@ Respondo automatically handles:
|
|
|
205
206
|
| Anything with `#to_h` | `.to_h` |
|
|
206
207
|
| Primitives (String, Integer...) | As-is |
|
|
207
208
|
|
|
209
|
+
> ⚠️ **Don't expose raw models.** `record.as_json` includes **every column** — including
|
|
210
|
+
> `password_digest`, API tokens and internal flags. Always return an explicit, allow-listed
|
|
211
|
+
> shape in production:
|
|
212
|
+
>
|
|
213
|
+
> ```ruby
|
|
214
|
+
> render_ok(data: user.as_json(only: %i[id name email]))
|
|
215
|
+
> # or configure a serializer once for the whole app:
|
|
216
|
+
> config.serializer = ->(obj) { UserBlueprint.render_as_hash(obj) }
|
|
217
|
+
> ```
|
|
218
|
+
>
|
|
219
|
+
> Set `config.strict_serialization = true` to make Respondo **raise**
|
|
220
|
+
> (`Respondo::UnsafeSerializationError`) when a raw ActiveRecord model or relation is passed
|
|
221
|
+
> without a serializer. Without it, Respondo logs a one-time warning per model class.
|
|
222
|
+
> Respondo also camelizes keys inside your `data` hashes — if two keys collapse to the same
|
|
223
|
+
> camelCase name (`user_id` / `userId`) both are left untouched rather than one overwriting the other.
|
|
224
|
+
|
|
208
225
|
---
|
|
209
226
|
|
|
210
227
|
## Configuration
|
|
@@ -225,9 +242,14 @@ Respondo.configure do |config|
|
|
|
225
242
|
config.include_request_id = true # adds request_id to every meta
|
|
226
243
|
config.camelize_keys = true # snake_case → camelCase (Flutter/JS friendly)
|
|
227
244
|
config.default_meta = { api_version: "v1" }
|
|
245
|
+
config.strict_serialization = true # raise on raw ActiveRecord data: (recommended)
|
|
246
|
+
config.max_collection_size = 1_000 # raise instead of loading huge collections (default: nil = no limit)
|
|
228
247
|
end
|
|
229
248
|
```
|
|
230
249
|
|
|
250
|
+
`request_id` and `timestamp` in `meta` are always generated by Respondo; values passed via `meta:` or
|
|
251
|
+
`default_meta` can't override them.
|
|
252
|
+
|
|
231
253
|
### camelCase output (great for Flutter / React Native)
|
|
232
254
|
|
|
233
255
|
```ruby
|
|
@@ -256,12 +278,16 @@ Add this to `ApplicationController` to handle exceptions app-wide without a try/
|
|
|
256
278
|
|
|
257
279
|
```ruby
|
|
258
280
|
class ApplicationController < ActionController::API
|
|
281
|
+
# Use fixed messages: e.message contains model names and lookup keys
|
|
282
|
+
# (e.g. "Couldn't find User with 'id'=42"), which helps attackers enumerate your schema.
|
|
259
283
|
rescue_from ActiveRecord::RecordNotFound do |e|
|
|
260
|
-
|
|
284
|
+
Rails.logger.info(e.message)
|
|
285
|
+
render_not_found(message: "Resource not found")
|
|
261
286
|
end
|
|
262
287
|
|
|
263
288
|
rescue_from ActionController::ParameterMissing do |e|
|
|
264
|
-
|
|
289
|
+
Rails.logger.info(e.message)
|
|
290
|
+
render_bad_request(message: "Required parameter missing")
|
|
265
291
|
end
|
|
266
292
|
|
|
267
293
|
rescue_from StandardError do |e|
|
|
@@ -327,13 +353,16 @@ render_bad_gateway(message: "Payment processor is unreachable — you have not b
|
|
|
327
353
|
<details>
|
|
328
354
|
<summary><strong>Full list of all helpers (click to expand)</strong></summary>
|
|
329
355
|
|
|
330
|
-
#### 1xx — Informational
|
|
331
|
-
`render_continue` · `render_switching_protocols` · `render_processing` · `render_early_hints`
|
|
332
|
-
|
|
333
356
|
#### 2xx — Success
|
|
334
357
|
`render_ok` · `render_created` · `render_accepted` · `render_non_authoritative` · `render_no_content` · `render_reset_content` · `render_partial_content` · `render_multi_status` · `render_already_reported` · `render_im_used`
|
|
335
358
|
|
|
336
359
|
#### 3xx — Redirect
|
|
360
|
+
Pass the target with `location:` — it is sent as a real `Location` header (and mirrored to
|
|
361
|
+
`meta.redirect_url`). Only relative paths and same-host URLs are accepted; anything else raises
|
|
362
|
+
`Respondo::UnsafeRedirectError` unless you pass `allow_other_host: true` (never do that with user input).
|
|
363
|
+
```ruby
|
|
364
|
+
render_found(location: "/login")
|
|
365
|
+
```
|
|
337
366
|
`render_multiple_choices` · `render_moved_permanently` · `render_found` · `render_see_other` · `render_not_modified` · `render_temporary_redirect` · `render_permanent_redirect`
|
|
338
367
|
|
|
339
368
|
#### 4xx — Client Error
|
|
@@ -38,6 +38,7 @@ module Respondo
|
|
|
38
38
|
step_camelize
|
|
39
39
|
step_default_meta
|
|
40
40
|
step_serializer
|
|
41
|
+
step_security
|
|
41
42
|
|
|
42
43
|
print_summary
|
|
43
44
|
write_initializer
|
|
@@ -123,6 +124,12 @@ module Respondo
|
|
|
123
124
|
|
|
124
125
|
k = key.strip
|
|
125
126
|
v = (value || "").strip
|
|
127
|
+
|
|
128
|
+
unless k.match?(META_KEY_PATTERN)
|
|
129
|
+
out line(yellow(" Key must be a plain identifier (letters, digits, underscores; not starting with a digit). Skipping."))
|
|
130
|
+
next
|
|
131
|
+
end
|
|
132
|
+
|
|
126
133
|
@cfg[:default_meta][k] = v
|
|
127
134
|
out line(green(" ✓ #{k}: #{v.inspect}"))
|
|
128
135
|
end
|
|
@@ -138,6 +145,23 @@ module Respondo
|
|
|
138
145
|
@cfg[:custom_serializer] = confirm(" Add a custom serializer stub? (y/n) ")
|
|
139
146
|
end
|
|
140
147
|
|
|
148
|
+
def step_security
|
|
149
|
+
out section("Security")
|
|
150
|
+
out line(" A raw ActiveRecord model is serialized with EVERY column, including")
|
|
151
|
+
out line(" password_digest and API tokens. Strict mode raises an error instead of")
|
|
152
|
+
out line(" leaking them, so you must pass an explicit shape:")
|
|
153
|
+
out line(yellow(" render_ok(data: user.as_json(only: %i[id name email]))"))
|
|
154
|
+
out line(" (or configure config.serializer).")
|
|
155
|
+
out blank
|
|
156
|
+
@cfg[:strict_serialization] = confirm_default_yes(" Enable strict_serialization? (recommended) (Y/n) ")
|
|
157
|
+
|
|
158
|
+
out blank
|
|
159
|
+
out line(" Maximum items allowed in one collection (protects against huge responses).")
|
|
160
|
+
out line(yellow(" Enter a number such as 1000, or leave blank for no limit."))
|
|
161
|
+
raw = prompt_default("no limit")
|
|
162
|
+
@cfg[:max_collection_size] = parse_collection_limit(raw)
|
|
163
|
+
end
|
|
164
|
+
|
|
141
165
|
# =========================================================================
|
|
142
166
|
# Summary
|
|
143
167
|
# =========================================================================
|
|
@@ -155,6 +179,8 @@ module Respondo
|
|
|
155
179
|
summary_row "Include request_id", @cfg[:include_request_id]
|
|
156
180
|
summary_row "Camelize keys", @cfg[:camelize_keys]
|
|
157
181
|
summary_row "Custom serializer", @cfg[:custom_serializer]
|
|
182
|
+
summary_row "Strict serialization", @cfg[:strict_serialization]
|
|
183
|
+
summary_row "Max collection size", @cfg[:max_collection_size] || "no limit"
|
|
158
184
|
|
|
159
185
|
unless @cfg[:default_meta].empty?
|
|
160
186
|
out blank
|
|
@@ -181,11 +207,30 @@ module Respondo
|
|
|
181
207
|
dir = File.join(destination_root, "config", "initializers")
|
|
182
208
|
path = File.join(dir, "respondo.rb")
|
|
183
209
|
FileUtils.mkdir_p(dir)
|
|
210
|
+
|
|
211
|
+
if File.exist?(path)
|
|
212
|
+
FileUtils.cp(path, "#{path}.bak")
|
|
213
|
+
out line(yellow(" ℹ️ Existing initializer backed up to config/initializers/respondo.rb.bak"))
|
|
214
|
+
end
|
|
215
|
+
|
|
184
216
|
File.write(path, build_content)
|
|
185
217
|
out line(green(" ✅ Created config/initializers/respondo.rb"))
|
|
186
218
|
out blank
|
|
187
219
|
end
|
|
188
220
|
|
|
221
|
+
# Valid Ruby identifier-style keys only. Anything else is never written
|
|
222
|
+
# raw into the generated Ruby file.
|
|
223
|
+
META_KEY_PATTERN = /\A[a-z_][a-z0-9_]*\z/i.freeze
|
|
224
|
+
|
|
225
|
+
# Returns the key as safe Ruby source, including the separator, e.g.
|
|
226
|
+
# `platform: ` for plain identifiers or `:"odd key" => ` as a fallback.
|
|
227
|
+
# String#inspect / Symbol#inspect escape quotes and newlines, so the key
|
|
228
|
+
# can never terminate the hash literal or inject statements.
|
|
229
|
+
def meta_key_literal(key)
|
|
230
|
+
key = key.to_s
|
|
231
|
+
key.match?(META_KEY_PATTERN) ? "#{key}: " : "#{key.to_sym.inspect} => "
|
|
232
|
+
end
|
|
233
|
+
|
|
189
234
|
def build_content
|
|
190
235
|
# meta = { "api_version" => @cfg[:api_version] }.merge(@cfg[:default_meta])
|
|
191
236
|
meta = @cfg[:default_meta].dup
|
|
@@ -194,7 +239,7 @@ module Respondo
|
|
|
194
239
|
|
|
195
240
|
b << "# frozen_string_literal: true"
|
|
196
241
|
b << ""
|
|
197
|
-
b << "# Respondo initializer — #{@cfg[:project_name]}"
|
|
242
|
+
b << "# Respondo initializer — #{@cfg[:project_name].to_s.gsub(/[\r\n]+/, " ")}"
|
|
198
243
|
b << "# Generated by: rails generate respondo:install"
|
|
199
244
|
b << "# Respondo version: #{Respondo::VERSION}"
|
|
200
245
|
b << "# Docs: https://github.com/spatelpatidar/respondo"
|
|
@@ -214,6 +259,16 @@ module Respondo
|
|
|
214
259
|
b << " # CamelCase all JSON keys — recommended for Flutter / JS clients."
|
|
215
260
|
b << " config.camelize_keys = #{@cfg[:camelize_keys]}"
|
|
216
261
|
b << ""
|
|
262
|
+
b << " # ── Security ─────────────────────────────────────────────────────────"
|
|
263
|
+
b << " # Raise Respondo::UnsafeSerializationError when a raw ActiveRecord model or"
|
|
264
|
+
b << " # relation is passed as data: without a serializer (it would expose every"
|
|
265
|
+
b << " # column, e.g. password_digest or API tokens). Recommended: true."
|
|
266
|
+
b << " config.strict_serialization = #{@cfg[:strict_serialization] == true}"
|
|
267
|
+
b << ""
|
|
268
|
+
b << " # Raise Respondo::CollectionTooLargeError when a collection has more items"
|
|
269
|
+
b << " # than this (nil = no limit). Paginate large lists instead."
|
|
270
|
+
b << " config.max_collection_size = #{@cfg[:max_collection_size].inspect}"
|
|
271
|
+
b << ""
|
|
217
272
|
b << " # ── Global Meta ──────────────────────────────────────────────────────"
|
|
218
273
|
b << " # Static fields merged into the meta block of every response."
|
|
219
274
|
|
|
@@ -223,7 +278,7 @@ module Respondo
|
|
|
223
278
|
b << " config.default_meta = {"
|
|
224
279
|
meta.each_with_index do |(k, v), i|
|
|
225
280
|
comma = i < meta.size - 1 ? "," : ""
|
|
226
|
-
b << " #{k}
|
|
281
|
+
b << " #{meta_key_literal(k)}#{v.inspect}#{comma}"
|
|
227
282
|
end
|
|
228
283
|
b << " }"
|
|
229
284
|
end
|
|
@@ -257,7 +312,9 @@ module Respondo
|
|
|
257
312
|
out line(" Next steps:")
|
|
258
313
|
out line(" 1. Review config/initializers/respondo.rb")
|
|
259
314
|
out line(" 2. Use render_success / render_error in your controllers")
|
|
260
|
-
out line(" 3.
|
|
315
|
+
out line(" 3. Handle Respondo::UnsafeSerializationError and")
|
|
316
|
+
out line(" Respondo::CollectionTooLargeError with rescue_from")
|
|
317
|
+
out line(" 4. Re-run rails generate respondo:install to regenerate")
|
|
261
318
|
out blank
|
|
262
319
|
out divider
|
|
263
320
|
out blank
|
|
@@ -272,8 +329,12 @@ module Respondo
|
|
|
272
329
|
$stdout.flush
|
|
273
330
|
end
|
|
274
331
|
|
|
275
|
-
def line(str)
|
|
276
|
-
|
|
332
|
+
def line(str)
|
|
333
|
+
"#{str}\n"
|
|
334
|
+
end
|
|
335
|
+
def blank
|
|
336
|
+
"\n"
|
|
337
|
+
end
|
|
277
338
|
|
|
278
339
|
def divider
|
|
279
340
|
" #{cyan("─" * 68)}\n"
|
|
@@ -291,6 +352,29 @@ module Respondo
|
|
|
291
352
|
result.empty? ? default.to_s : result
|
|
292
353
|
end
|
|
293
354
|
|
|
355
|
+
# Like confirm, but pressing Enter means yes (used for the secure default).
|
|
356
|
+
def confirm_default_yes(question)
|
|
357
|
+
$stdout.print question
|
|
358
|
+
$stdout.flush
|
|
359
|
+
answer = $stdin.gets.to_s.strip.downcase
|
|
360
|
+
answer.empty? || answer.start_with?("y")
|
|
361
|
+
end
|
|
362
|
+
|
|
363
|
+
# "1000" / "1_000" / "1,000" -> 1000. Blank, "no limit", zero, negative or
|
|
364
|
+
# non-numeric input -> nil (no limit), with a hint when the input was invalid.
|
|
365
|
+
def parse_collection_limit(raw)
|
|
366
|
+
text = raw.to_s.strip.downcase
|
|
367
|
+
return nil if text.empty? || text == "no limit"
|
|
368
|
+
|
|
369
|
+
digits = text.delete("_,")
|
|
370
|
+
if digits.match?(/\A\d+\z/) && digits.to_i.positive?
|
|
371
|
+
digits.to_i
|
|
372
|
+
else
|
|
373
|
+
out line(yellow(" Not a positive whole number — using no limit."))
|
|
374
|
+
nil
|
|
375
|
+
end
|
|
376
|
+
end
|
|
377
|
+
|
|
294
378
|
def confirm(question)
|
|
295
379
|
$stdout.print question
|
|
296
380
|
$stdout.flush
|
|
@@ -301,9 +385,15 @@ module Respondo
|
|
|
301
385
|
# ANSI colors
|
|
302
386
|
# =========================================================================
|
|
303
387
|
|
|
304
|
-
def cyan(t)
|
|
305
|
-
|
|
306
|
-
|
|
388
|
+
def cyan(t)
|
|
389
|
+
"\e[36m#{t}\e[0m"
|
|
390
|
+
end
|
|
391
|
+
def green(t)
|
|
392
|
+
"\e[32m#{t}\e[0m"
|
|
393
|
+
end
|
|
394
|
+
def yellow(t)
|
|
395
|
+
"\e[33m#{t}\e[0m"
|
|
396
|
+
end
|
|
307
397
|
|
|
308
398
|
# =========================================================================
|
|
309
399
|
# ASCII logo
|
|
@@ -343,9 +433,17 @@ module Respondo
|
|
|
343
433
|
# =========================================================================
|
|
344
434
|
|
|
345
435
|
class Lines
|
|
346
|
-
def initialize
|
|
347
|
-
|
|
348
|
-
|
|
436
|
+
def initialize
|
|
437
|
+
@buf = []
|
|
438
|
+
end
|
|
439
|
+
|
|
440
|
+
def <<(str)
|
|
441
|
+
@buf << str
|
|
442
|
+
end
|
|
443
|
+
|
|
444
|
+
def to_s
|
|
445
|
+
@buf.join("\n") + "\n"
|
|
446
|
+
end
|
|
349
447
|
end
|
|
350
448
|
end
|
|
351
449
|
end
|
|
@@ -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:
|
|
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:
|
|
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:
|
|
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:
|
|
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
|
-
|
|
80
|
+
authoritative[:request_id] = @request.request_id
|
|
77
81
|
end
|
|
78
82
|
|
|
79
83
|
# 2. Timestamp second
|
|
80
|
-
|
|
84
|
+
authoritative[:timestamp] = current_timestamp
|
|
85
|
+
meta.merge!(authoritative)
|
|
81
86
|
|
|
82
|
-
# 3. Global defaults
|
|
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.
|
|
117
|
-
|
|
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) }
|
data/lib/respondo/serializer.rb
CHANGED
|
@@ -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
|
-
|
|
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
|
data/lib/respondo/version.rb
CHANGED
data/lib/respondo.rb
CHANGED
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.
|
|
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-
|
|
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
|