diff --git a/core/engine/src/builtins/json/mod.rs b/core/engine/src/builtins/json/mod.rs index b7549f4c442..df6e469b0ee 100644 --- a/core/engine/src/builtins/json/mod.rs +++ b/core/engine/src/builtins/json/mod.rs @@ -873,11 +873,7 @@ impl Json { // a. Let isArray be ? IsArray(value). // b. If isArray is true, return ? SerializeJSONArray(state, value). // c. Return ? SerializeJSONObject(state, value). - return if obj.is_array_abstract()? { - Ok(Some(Self::serialize_json_array(state, &obj, context)?)) - } else { - Ok(Some(Self::serialize_json_object(state, &obj, context)?)) - }; + return Ok(Some(Self::serialize_json_nested(state, &obj, context)?)); } // 12. Return undefined. @@ -953,6 +949,33 @@ impl Json { js_string!(&product[..]) } + /// Serializes a nested object or array, counting the descent as host recursion. + /// + /// `SerializeJSONObject` and `SerializeJSONArray` recurse natively, one native frame per + /// level of nesting, so without this the depth is bounded only by the native stack and a + /// deeply nested value aborts the process instead of reporting the configured recursion + /// limit. + fn serialize_json_nested( + state: &mut StateRecord, + value: &JsObject, + context: &mut Context, + ) -> JsResult { + context.vm.host_call_depth += 1; + let result = context + .check_runtime_limits() + .and_then(|()| value.is_array_abstract()) + .and_then(|is_array| { + if is_array { + Self::serialize_json_array(state, value, context) + } else { + Self::serialize_json_object(state, value, context) + } + }); + context.vm.host_call_depth = context.vm.host_call_depth.saturating_sub(1); + + result + } + /// `25.5.2.4 SerializeJSONObject ( state, value )` /// /// More information: diff --git a/core/engine/src/builtins/json/tests.rs b/core/engine/src/builtins/json/tests.rs index 86965b950ee..9bc98f64f53 100644 --- a/core/engine/src/builtins/json/tests.rs +++ b/core/engine/src/builtins/json/tests.rs @@ -1,7 +1,9 @@ use boa_macros::js_str; use indoc::indoc; -use crate::{JsNativeErrorKind, JsValue, TestAction, js_string, run_test_actions}; +use crate::{ + JsNativeErrorKind, JsValue, TestAction, error::RuntimeLimitError, js_string, run_test_actions, +}; #[test] fn json_sanity() { @@ -362,3 +364,48 @@ fn json_stringify_cyclic_nested_object_throws_type_error() { "cyclic object value", )]); } + +#[test] +fn json_stringify_deep_nesting_reports_the_recursion_limit() { + run_test_actions([ + TestAction::inspect_context(|context| { + context.runtime_limits_mut().set_recursion_limit(64); + }), + TestAction::run(indoc! {r#" + function nestObjects(depth) { + const root = {}; + let node = root; + for (let i = 0; i < depth; i++) { + node.a = {}; + node = node.a; + } + return root; + } + + function nestArrays(depth) { + const root = []; + let node = root; + for (let i = 0; i < depth; i++) { + node[0] = []; + node = node[0]; + } + return root; + } + "#}), + // Nesting within the limit is unaffected. + TestAction::assert_eq( + "JSON.stringify(nestObjects(4))", + js_string!(r#"{"a":{"a":{"a":{"a":{}}}}}"#), + ), + TestAction::assert_eq("JSON.stringify(nestArrays(3))", js_string!("[[[[]]]]")), + // Deeper nesting reports the limit instead of exhausting the native stack. + TestAction::assert_runtime_limit_error( + "JSON.stringify(nestObjects(200))", + RuntimeLimitError::Recursion, + ), + TestAction::assert_runtime_limit_error( + "JSON.stringify(nestArrays(200))", + RuntimeLimitError::Recursion, + ), + ]); +} diff --git a/core/engine/src/value/conversions/serde_json.rs b/core/engine/src/value/conversions/serde_json.rs index 10259bbdcf5..c73ac595f31 100644 --- a/core/engine/src/value/conversions/serde_json.rs +++ b/core/engine/src/value/conversions/serde_json.rs @@ -118,10 +118,35 @@ impl JsValue { self.to_json_inner(context, &mut seen_objects) } + /// Counts one level of the conversion as host recursion before converting an object. + /// + /// The conversion recurses natively through nested objects and arrays, one native frame per + /// level, so without this the depth is bounded only by the native stack and a deeply nested + /// value aborts the process instead of reporting the configured recursion limit. Only objects + /// recurse, so only they are counted, which keeps the depth in step with + /// `SerializeJSONNested` and leaves a primitive leaf costing nothing. fn to_json_inner( &self, context: &mut Context, seen_objects: &mut HashSet, + ) -> JsResult> { + if !self.is_object() { + return self.to_json_variant(context, seen_objects); + } + + context.vm.host_call_depth += 1; + let result = context + .check_runtime_limits() + .and_then(|()| self.to_json_variant(context, seen_objects)); + context.vm.host_call_depth = context.vm.host_call_depth.saturating_sub(1); + + result + } + + fn to_json_variant( + &self, + context: &mut Context, + seen_objects: &mut HashSet, ) -> JsResult> { match self.variant() { JsVariant::Null => Ok(Some(Value::Null)), @@ -215,6 +240,32 @@ mod tests { Context, JsObject, JsValue, TestAction, js_string, object::JsArray, run_test_actions, }; + #[test] + fn to_json_deep_nesting_reports_the_recursion_limit() { + run_test_actions([ + TestAction::run(indoc! {r#" + var root = {}; + var node = root; + for (var i = 0; i < 200; i++) { + node.a = {}; + node = node.a; + } + "#}), + TestAction::inspect_context(|context| { + context.runtime_limits_mut().set_recursion_limit(64); + + let global = context.global_object(); + let root = global.get(js_string!("root"), context).unwrap(); + let error = root.to_json(context).unwrap_err(); + + assert!( + error.to_string().contains("recursive calls"), + "expected the recursion limit, got {error}" + ); + }), + ]); + } + #[test] fn json_conversions() { const DATA: &str = indoc! {r#"