RFC 8785 canonicalization raises NoMethodError (not JSON::GeneratorError) for colliding mixed-type object keys
I maintainer di solito rispondono entro 1 giorno
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 2/5
- Tempo stimato
- 1-3 ore
- Idoneità per principianti
- 76/100
Direzione di ricerca
Parti da ext/json/ext/generator/generator.c:1102 e leggi il percorso di ordinamento delle chiavi RFC 8785 insieme a lib/json/ext.rb:160-162 e Ext.coerce_key. Riproduci il malfunzionamento con l’esempio che mescola chiavi String e Integer, poi individua i test pertinenti per le chiavi duplicate, incluso test_generate_duplicate_keys_disallowed. Il lavoro è completato quando il percorso RFC 8785 solleva JSON::GeneratorError in caso di collisione, in modo coerente con gli altri casi di chiavi duplicate.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
About
Title: RFC 8785 canonicalization raises NoMethodError (not JSON::GeneratorError) for colliding mixed-type object keys
Repository: ruby/json
Location: ext/json/ext/generator/generator.c:1102
Severity: Low
Impacted versions: 3.1.0, 3.2.0
Summary
In rfc8785: true mode the C generator hands the object to State.rfc8785_sort_keys_proc
and passes nil or false as the second argument whenever there is no as_json
converter to call - nil for a non-strict state (plain JSON.generate), false for a
strict JSON::Coder created without a block (generator.c:1102). The Ruby proc only looks
for duplicate keys when hash.transform_keys(&:to_s) produced fewer entries than the
original hash, i.e. when two keys stringify to the same value (lib/json/ext.rb:160-162).
When that happens it calls Ext.on_duplicate_key(hash, as_json), which sends every key
through Ext.coerce_key, and coerce_key starts with as_json.call(key, true) for any
key that is not a String or a Symbol. With nil/false that is a
NoMethodError: undefined method 'call' for nil (or for false), raised from inside the
generator.
The trigger is an ordinary Hash that mixes a String key with a non-String key that
stringifies to the same name - for instance a Hash holding the String key 1 and the
Integer key 1, the kind of hash produced by merging request parameters (string keys) with
integer-keyed defaults or with values keyed by database IDs. Without rfc8785 the same
input correctly raises a JSON::GeneratorError reporting the detected duplicate key; a
Symbol/Integer variant and a JSON::Coder with a converter block also raise
JSON::GeneratorError under rfc8785. So the check exists but its error path is broken
in precisely the configuration the option is designed for.
Recommendation: pass a usable as_json callable to the sort proc (e.g. a
no-op/String()-based proc when the state has none), or make
Ext.coerce_key/Ext.on_duplicate_key fall back to String() when as_json is falsy,
so the collision is reported as a JSON::GeneratorError like every other key problem.
Impact
The concrete cost is the same denial-of-service primitive as the sibling rfc8785 bugs: an
application that rescues JSON::GeneratorError (the documented way to reject
un-serializable input) does not catch a NoMethodError, so a single request containing a
colliding String/Integer pair for the same member name terminates the request with a 500,
kills a background job, or aborts a signing/verification operation. Because the exception
is a NoMethodError, it also looks like a bug in the application's own code rather than
bad input, so error monitoring and alerting (which are normally keyed on JSON exception
classes) either page the wrong team or raise a new incident on every request; the operator
cannot distinguish'the client sent something we must reject' from'the library is
broken'.
Beyond availability, the broken error path defeats input triage: a caller cannot catch the
condition, inspect error.invalid_object, and turn it into a 4xx response, and it cannot
sanitize/coerce the offending keys and continue - both of which are possible for every
other key error the generator raises. The failure therefore escalates a routine,
caller-fixable input problem into an unhandled crash, which is exactly what the JSON error
hierarchy exists to prevent.
Mitigations
Pass a valid as_json callable (or skip the coerce_key path) for the rfc8785 sort proc;
normalise keys to String/Symbol before canonicalising; rescue StandardError around
untrusted serialisation; upgrade to a fixed json release. Confirmed workaround: supply a
converter block (JSON::Coder.new(rfc8785: true) { |o, *| o.to_s}) or use the non-rfc8785
path, both of which raise JSON::GeneratorError for the same document.
Examples
example 1
Merging untrusted parameters with defaults: a Hash built by merging request params (whose
keys are Strings) with defaults keyed by Integers, or simply a Hash holding the String key
1 and the Integer key 1, raises NoMethodError: undefined method 'call' for nil instead
of the documented JSON::GeneratorError.
example 2
The same input is exercised by this project's own test suite: json 3.2.0 added cases for a
String key 1 followed by an Integer key 1 to test_generate_duplicate_keys_disallowed,
plus a CHANGES.md entry about JSON.generate not detecting duplicate keys such as those,
so raising a JSON error here is the intended, tested behaviour - only the canonicalisation
code path is out of step.
example 3
Hashes keyed by identifiers commonly mix types: a JSON request body yields String keys
while a lookup table, an array index, or a range-to-Hash conversion yields Integer keys.
Canonicalizing such a map (for a signature, an idempotency key or a cache key) is a normal
use of rfc8785: true and is exactly the case that crashes.
example 4
Same defect class as other error-path bugs this project already fixed:
JSON::ParserError#json_path raising NoMethodError when symbolize_names: true (fixed
in 3.2.0) and the as_json-returning-Symbol stack overflow on JRuby/TruffleRuby (fixed in
3.2.0). Narrow, documented error types matter because callers build their input-validation
and HTTP status mapping on them.
Proof of concept
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# PoC: unhandled NoMethodError in the RFC 8785 path (generator.c:1102)
#
# generate_json_object passes Qnil (plain JSON.generate) or Qfalse
# (JSON::Coder without as_json) as the as_json argument of the rfc8785 sort
# proc. When two keys collide after String()ification and one of them is not a
# String/Symbol (e.g. an ordinary Integer key), the duplicate-key path reaches
# Ext.coerce_key's `as_json.call(key, true)` and calls `.call` on nil/false.
lib = File.expand_path("lib", Dir.pwd)
lib = File.expand_path("../lib", __dir__) unless File.directory?(lib)
$LOAD_PATH.unshift(lib)
require "json"
puts "json gem #{JSON::VERSION} (generator: #{JSON.generator})"
def probe(label)
yield
puts "#{label}: no exception (unexpected)"
rescue JSON::GeneratorError => e
puts "#{label}: JSON::GeneratorError (correct): #{e.message}"
rescue => e
puts "#{label}: #{e.class}: #{e.message} <-- NOT a GeneratorError"
end
# A plain hash: the String key "1" and the Integer key 1 both String()-ify to "1".
doc = { "1" => "user", 1 => "admin" }
puts "document: #{doc.inspect}"
probe("JSON.generate(..., rfc8785: true) ") { JSON.generate(doc, rfc8785: true) }
probe("JSON::Coder.new(rfc8785: true).dump(...) ") { JSON::Coder.new(rfc8785: true).dump(doc) }
puts "\nRESULT: uncaught NoMethodError escapes callers that rescue only JSON::GeneratorError"
stdout
json gem 3.2.0 (generator: JSON::Ext::Generator)
document: {"1" => "user", 1 => "admin"}
JSON.generate(..., rfc8785: true) : NoMethodError: undefined method 'call' for nil <-- NOT a GeneratorError
JSON::Coder.new(rfc8785: true).dump(...) : NoMethodError: undefined method 'call' for false <-- NOT a GeneratorError
RESULT: uncaught NoMethodError escapes callers that rescue only JSON::GeneratorError
- Lingua principale
- Ruby
- Stelle
- 787
- Fork
- 392
- Merge medio
- 6h 4m
- PR unite (30g)
- 22
Preparare l'ambiente
Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di ruby/json
-
Difficoltà 4/5 3-5 giorni Idoneità per principianti 55/100
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 3/5 1-2 giorni Idoneità per principianti 55/100
I maintainer di solito rispondono entro 1 giorno
-
Audit excluded tests on JRuby and address differencesForse già presa @ojuschugh1 l’ha presa 5 giorni fa. Aperta
Difficoltà 4/5 3-5 giorni Idoneità per principianti 48/100
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 3/5 1-2 giorni Idoneità per principianti 55/100
I maintainer di solito rispondono entro 1 giorno
-
Output formatting differences between jRuby 10.0.0.1 and Ruby 3.4 when converting Float to JSON.Forse già presa @headius l’ha presa 459 giorni fa. Apertajruby
ruby/json#817 · 3 commenti · 1 reazione · 1 assegnatario ·
I maintainer di solito rispondono entro 1 giorno
Issue simili
-
SecureRandom.alphanumeric can silently return an empty or wrong-length secret instead of raisingAperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 67/100
ruby/securerandom#92 ·
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 85/100
open-feature/ruby-sdk-contrib#340 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 88/100
zold-io/wts.zold.io#651 ·
I maintainer di solito rispondono entro 1 giorno
-
good first issue help wanted
Difficoltà 2/5 1-3 ore Idoneità per principianti 87/100
erkamyaman/rust-anything#788 ·
I maintainer di solito rispondono entro 1 giorno