RFC 8785 canonicalization raises NoMethodError (not JSON::GeneratorError) for colliding mixed-type object keys

未关闭 适合新手
#1,152 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
76/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
ruby
领域
backend, databases

调研方向

从 ext/json/ext/generator/generator.c:1102 开始,结合 lib/json/ext.rb:160-162 和 Ext.coerce_key 阅读 RFC 8785 的键排序路径。使用混合 String 和 Integer 键的示例重现故障,然后查找相关的重复键测试,包括 test_generate_duplicate_keys_disallowed。完成标准是:发生冲突时,RFC 8785 路径会引发 JSON::GeneratorError,与其他重复键情况一致。

由索引模型根据 Issue 内容生成。

描述

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
主要语言
Ruby
星标
787
派生
392
平均合并
6 小时 4 分钟
30 天内合并 PR
22

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

ruby/json 的其他 Issue

查看 ruby/json 的全部 Issue

相似的 Issue

更多 Ruby Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。