pub fn validate_json_depth(
json_str: &str,
max_depth: usize,
) -> Result<(), String>Expand description
Validate JSON nesting depth to prevent DoS attacks
§Arguments
json_str- The JSON string to validatemax_depth- Maximum allowed nesting depth (useMAX_JSON_DEPTHfor default)
§Returns
Ok(())if the JSON is valid and within depth limitsErr(String)with error message if validation fails
§Examples
use veracode_platform::json_validator::{validate_json_depth, MAX_JSON_DEPTH};
// Valid JSON within depth limit
let json = r#"{"user": {"profile": {"settings": {"theme": "dark"}}}}"#;
assert!(validate_json_depth(json, MAX_JSON_DEPTH).is_ok());
// Deeply nested JSON should be rejected
let deep_json = (0..50).fold(String::from("{\"a\":"), |acc, _| acc + "{\"a\":")
+ &(0..50).map(|_| "}").collect::<String>();
assert!(validate_json_depth(&deep_json, MAX_JSON_DEPTH).is_err());§Security
This function protects against:
- Stack overflow from recursive parsing
- CPU exhaustion from excessive nesting
- Memory exhaustion from deeply nested structures
§Errors
Returns an error if the JSON is invalid or exceeds the maximum nesting depth. Error messages are sanitized to avoid information disclosure, with detailed errors logged internally for debugging.