Skip to content

Commit a29fcdc

Browse files
committed
Add depth validation to Jruby and TruffleRuby implementations
1 parent de993aa commit a29fcdc

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

java/src/json/ext/GeneratorState.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -484,9 +484,12 @@ public RubyInteger depth_get(ThreadContext context) {
484484
}
485485

486486
@JRubyMethod(name="depth=")
487-
public IRubyObject depth_set(IRubyObject vDepth) {
487+
public IRubyObject depth_set(ThreadContext context, IRubyObject vDepth) {
488488
checkFrozen();
489489
depth = RubyNumeric.fix2int(vDepth);
490+
if (depth < 0) {
491+
throw context.runtime.newArgumentError("depth must be >= 0 (got: " + depth + ")");
492+
}
490493
return vDepth;
491494
}
492495

@@ -557,6 +560,9 @@ public IRubyObject _configure(ThreadContext context, IRubyObject vOpts) {
557560
bufferInitialLength = opts.getInt("buffer_initial_length", DEFAULT_BUFFER_INITIAL_LENGTH);
558561

559562
depth = opts.getInt("depth", 0);
563+
if (depth < 0) {
564+
throw context.runtime.newArgumentError("depth must be >= 0 (got: " + depth + ")");
565+
}
560566

561567
if (opts.hasKey("allow_duplicate_key")) {
562568
this.allowDuplicateKey = opts.getBool("allow_duplicate_key", false);

lib/json/truffle_ruby/generator.rb

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,14 @@ def buffer_initial_length=(length)
211211

212212
# This integer returns the current depth data structure nesting in the
213213
# generated JSON.
214-
attr_accessor :depth
214+
attr_reader :depth
215+
216+
def depth=(depth)
217+
if depth.negative?
218+
raise ArgumentError, "depth must be >= 0 (got #{depth})"
219+
end
220+
@depth = depth
221+
end
215222

216223
def check_max_nesting # :nodoc:
217224
return if @max_nesting.zero?
@@ -260,6 +267,11 @@ def configure(opts)
260267
else
261268
raise TypeError, "can't convert #{opts.class} into Hash"
262269
end
270+
271+
if opts[:depth]&.negative?
272+
raise ArgumentError, "depth must be >= 0 (got #{opts[:depth]})"
273+
end
274+
263275
opts.each do |key, value|
264276
instance_variable_set "@#{key}", value
265277
end

0 commit comments

Comments
 (0)