From 3ac3954feae477a279981ceea47af30d24c0f8ff Mon Sep 17 00:00:00 2001 From: fl0l0u Date: Sun, 15 Nov 2026 17:21:25 +0000 Subject: [PATCH] sample: the schema reaches the converter through the bounded read grammar.cpp guarded the json-schema-to-grammar converter with a depth check -- kMaxSchemaDepth, added because a deeply nested schema crashes the converter -- but it built the tree to measure with Json::parse, the unbounded read. A schema nested past the guard's own reach was already a stack overflow by the time json_depth ran: the check sat after the thing it was written against. The schema is now read with parse_bounded at exactly the depth the check promises, plus a 2^20 value cap, so the refusal fires during the read, before any nested tree exists to be walked, dumped or destroyed. Every current caller already hands over a bounded body, but this entry point does not know that -- it takes a string. --- core/sample/grammar.cpp | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/core/sample/grammar.cpp b/core/sample/grammar.cpp index e7369acc..d3370ab9 100644 --- a/core/sample/grammar.cpp +++ b/core/sample/grammar.cpp @@ -103,7 +103,27 @@ int grammar_from_json_schema(const std::string& schema_json, const std::string& } if (schema_cache().find(schema_json, out_gbnf)) return RAD_OK; try { - const auto schema = Json::parse(schema_json); + /* Read bounded, then read deep: today every caller hands over a dump of an + * already-bounded body tree, but this entry point does not know that -- an + * unbounded read here would hand a hostile producer exactly the crash shape the + * depth check below was written against. The depth bound now fires during the + * read, before any nested tree exists to be dumped or destroyed. */ + bool over = false, deep = false; + const auto schema = Json::parse_bounded(schema_json, 1 << 20, (int)kMaxSchemaDepth, + &over, &deep); + if (deep) { + if (err) *err = "the schema nests more than " + std::to_string(kMaxSchemaDepth) + + " levels deep"; + return RAD_E_INVAL; + } + if (over) { + if (err) *err = "the schema carries more than 2^20 values"; + return RAD_E_INVAL; + } + if (schema.is_discarded()) { + if (err) *err = "the schema is not valid JSON"; + return RAD_E_INVAL; + } if (json_depth(schema) > kMaxSchemaDepth) { if (err) *err = "the schema nests more than " + std::to_string(kMaxSchemaDepth) + " levels deep";