RFC 8785 canonicalization raises NoMethodError (not JSON::GeneratorError) for colliding mixed-type object keys
Les mainteneurs répondent en général sous 1 jour
Personne n'a encore pris cette issue.
Évaluation
- Difficulté
- 2/5
- Temps estimé
- 1-3 heures
- Accessibilité débutants
- 76/100
Piste de recherche
Commencez à ext/json/ext/generator/generator.c:1102 et lisez le chemin de tri des clés de RFC 8785 avec lib/json/ext.rb:160-162 et Ext.coerce_key. Reproduisez l’échec avec l’exemple qui mélange des clés String et Integer, puis trouvez les tests pertinents sur les clés en double, y compris test_generate_duplicate_keys_disallowed. Le travail est terminé lorsque le chemin RFC 8785 déclenche JSON::GeneratorError en cas de collision, comme pour les autres cas de clés en double.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Description
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
- Langage dominant
- Ruby
- Étoiles
- 787
- Forks
- 392
- Merge moyen
- 6 h 4 min
- PR mergées (30 j)
- 22
Préparer son environnement
Ce projet ne fournit ni conteneur de développement, ni Dockerfile, ni guide de contribution : l'installation est à votre charge. Commencez par son README, et consultez notre guide de la première contribution pour les étapes générales.
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Autres issues de ruby/json
-
Difficulté 4/5 3-5 jours Accessibilité débutants 55/100
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 3/5 1-2 jours Accessibilité débutants 55/100
Les mainteneurs répondent en général sous 1 jour
-
Audit excluded tests on JRuby and address differencesPeut-être pris @ojuschugh1 l’a pris il y a 5 jours. Ouverte
Difficulté 4/5 3-5 jours Accessibilité débutants 48/100
ruby/json#1123 · 5 commentaires ·
Les mainteneurs répondent en général sous 1 jour
-
Can `ResumableParser` return whether the last `partial_value` container is completed or not?Ouverte
Difficulté 3/5 1-2 jours Accessibilité débutants 55/100
ruby/json#1041 · 7 commentaires ·
Les mainteneurs répondent en général sous 1 jour
-
Output formatting differences between jRuby 10.0.0.1 and Ruby 3.4 when converting Float to JSON.Peut-être pris @headius l’a pris il y a 459 jours. Ouvertejruby
ruby/json#817 · 3 commentaires · 1 réaction · 1 personne assignée ·
Les mainteneurs répondent en général sous 1 jour
Toutes les issues de ruby/json
Issues similaires
-
SecureRandom.alphanumeric can silently return an empty or wrong-length secret instead of raisingOuverte
Difficulté 2/5 1-3 heures Accessibilité débutants 67/100
ruby/securerandom#92 ·
-
Difficulté 2/5 1-3 heures Accessibilité débutants 72/100
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 85/100
open-feature/ruby-sdk-contrib#340 ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 88/100
zold-io/wts.zold.io#651 ·
Les mainteneurs répondent en général sous 1 jour
-
good first issue help wanted
Difficulté 2/5 1-3 heures Accessibilité débutants 87/100
erkamyaman/rust-anything#788 ·
Les mainteneurs répondent en général sous 1 jour