Expand description
Parse JSON while blocking prototype-poisoning keys.
This crate parses untrusted JSON and detects two key patterns that pollute a JavaScript object’s prototype once the parsed value is copied, merged, or iterated:
- a key literally named
__proto__ - a key named
constructorwhose value is an object that contains aprototypekey (aconstructor.prototypenesting)
For each pattern you choose an Action: error out, remove the key, or
ignore it and behave like a plain JSON parse. A safe flag turns any
detected violation into Ok(None) instead of an error.
The parsed value is a serde_json::Value. In a Value tree __proto__
and constructor are ordinary map keys, so the danger is latent rather than
immediate. The job here is to detect, remove, or reject those keys before the
value reaches code that would treat them as a prototype.
§Quick start
use secure_json_parse::{parse, Action, Options, Error};
// Default options error on a forbidden key.
let err = parse(r#"{"__proto__": {"x": 7}}"#, &Options::default());
assert!(matches!(err, Err(Error::ForbiddenProperty)));
// Remove the key instead.
let opts = Options::default().proto_action(Action::Remove);
let value = parse(r#"{"a": 5, "__proto__": {"x": 7}}"#, &opts).unwrap().unwrap();
assert_eq!(value, serde_json::json!({"a": 5}));§Safe parsing
safe_parse folds every outcome into one three-valued result:
use secure_json_parse::{safe_parse, SafeOutcome};
// Clean input parses to a value.
assert!(matches!(safe_parse(r#"{"a": 1}"#), SafeOutcome::Value(_)));
// A forbidden key yields Violation.
assert!(matches!(safe_parse(r#"{"__proto__": {}}"#), SafeOutcome::Violation));
// Malformed JSON yields Malformed.
assert!(matches!(safe_parse(r#"{"a": "#), SafeOutcome::Malformed));Structs§
- Options
- Configuration for
parse,parse_bytes, andscan.
Enums§
- Action
- What to do when a forbidden key is found.
- Error
- Why a parse failed.
- Safe
Outcome - The three outcomes of
safe_parse.
Functions§
- parse
- Parse JSON text and apply prototype-poisoning checks.
- parse_
bytes - Parse JSON bytes and apply prototype-poisoning checks.
- safe_
parse - Parse JSON text and fold every outcome into a
SafeOutcome. - safe_
parse_ bytes - Parse JSON bytes and fold every outcome into a
SafeOutcome. - scan
- Walk a parsed value and apply the prototype-poisoning checks.