RFC 8785 canonicalization raises NoMethodError (not JSON::GeneratorError) for colliding mixed-type object keys
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 2/5
- Tiempo estimado
- 1-3 horas
- Aptitud para principiantes
- 76/100
Línea de trabajo
Empieza en ext/json/ext/generator/generator.c:1102 y lee la ruta de ordenación de claves de RFC 8785 junto con lib/json/ext.rb:160-162 y Ext.coerce_key. Reproduce el fallo con el ejemplo que mezcla claves String e Integer y, después, busca las pruebas relevantes para claves duplicadas, incluida test_generate_duplicate_keys_disallowed. Se considera terminado cuando la ruta de RFC 8785 lanza JSON::GeneratorError al producirse la colisión, de forma coherente con los demás casos de claves duplicadas.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
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
- Lenguaje dominante
- Ruby
- Estrellas
- 787
- Forks
- 392
- Merge medio
- 6 h 4 min
- PR fusionados (30 d)
- 22
Preparar el entorno
Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de ruby/json
-
Dificultad 4/5 3-5 días Aptitud para principiantes 55/100
Los mantenedores suelen responder en 1 día
-
Dificultad 3/5 1-2 días Aptitud para principiantes 55/100
Los mantenedores suelen responder en 1 día
-
Audit excluded tests on JRuby and address differencesPosiblemente ocupada @ojuschugh1 la tomó hace 5 días. Abierto
Dificultad 4/5 3-5 días Aptitud para principiantes 48/100
ruby/json#1123 · 5 comentarios ·
Los mantenedores suelen responder en 1 día
-
Can `ResumableParser` return whether the last `partial_value` container is completed or not?Abierto
Dificultad 3/5 1-2 días Aptitud para principiantes 55/100
ruby/json#1041 · 7 comentarios ·
Los mantenedores suelen responder en 1 día
-
Output formatting differences between jRuby 10.0.0.1 and Ruby 3.4 when converting Float to JSON.Posiblemente ocupada @headius la tomó hace 459 días. Abiertojruby
ruby/json#817 · 3 comentarios · 1 reacción · 1 asignado ·
Los mantenedores suelen responder en 1 día
Issues similares
-
SecureRandom.alphanumeric can silently return an empty or wrong-length secret instead of raisingAbierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 67/100
ruby/securerandom#92 ·
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100
open-feature/ruby-sdk-contrib#340 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 88/100
zold-io/wts.zold.io#651 ·
Los mantenedores suelen responder en 1 día
-
good first issue help wanted
Dificultad 2/5 1-3 horas Aptitud para principiantes 87/100
erkamyaman/rust-anything#788 ·
Los mantenedores suelen responder en 1 día