Merge pull request #328 from arreina/pr/json-nesting-limit

fix(json2): reject documents nested deeper than 512 levels
This commit is contained in:
Alexey
2026-10-03 10:35:04 +03:00
committed by GitHub
2 changed files with 34 additions and 4 deletions
+11 -4
View File
@@ -269,8 +269,11 @@ public:
}
private:
static constexpr std::size_t MaxNestingDepth = 512;
const char* _text;
const char* _end;
std::size_t _depth = 0;
void skip() { while (_text < _end && (*_text == ' ' || *_text == '\t' || *_text == '\n' || *_text == '\r')) ++_text; }
bool literal(const char* word) {
@@ -386,10 +389,12 @@ private:
return true;
}
case '[': {
if (_depth == MaxNestingDepth) return false;
++_text;
++_depth;
SetType(out, TypeArray);
skip();
if (_text < _end && *_text == ']') { ++_text; return true; }
if (_text < _end && *_text == ']') { ++_text; --_depth; return true; }
for (;;) {
Value item{};
Construct(item);
@@ -398,15 +403,17 @@ private:
if (!value(*item.node)) return false;
skip();
if (_text < _end && *_text == ',') { ++_text; continue; }
if (_text < _end && *_text == ']') { ++_text; return true; }
if (_text < _end && *_text == ']') { ++_text; --_depth; return true; }
return false;
}
}
case '{': {
if (_depth == MaxNestingDepth) return false;
++_text;
++_depth;
SetType(out, TypeObject);
skip();
if (_text < _end && *_text == '}') { ++_text; return true; }
if (_text < _end && *_text == '}') { ++_text; --_depth; return true; }
for (;;) {
skip();
std::string key;
@@ -422,7 +429,7 @@ private:
if (!value(*pair.value.node)) return false;
skip();
if (_text < _end && *_text == ',') { ++_text; continue; }
if (_text < _end && *_text == '}') { ++_text; return true; }
if (_text < _end && *_text == '}') { ++_text; --_depth; return true; }
return false;
}
}
+23
View File
@@ -170,6 +170,28 @@ static void ParseAndRoundTrip() {
_ZN3sce4Json5ValueD1Ev(&root);
}
static std::string Nested(std::size_t depth, bool objects) {
std::string text;
for (std::size_t i = 0; i < depth; ++i) text += objects ? "{\"a\":" : "[";
text += "1";
for (std::size_t i = 0; i < depth; ++i) text += objects ? "}" : "]";
return text;
}
static void NestingDepth() {
Value root{};
_ZN3sce4Json5ValueC1Ev(&root);
for (const bool objects : {false, true}) {
const std::string accepted = Nested(512, objects);
Require(_ZN3sce4Json6Parser5parseERNS0_5ValueEPKcm(&root, accepted.c_str(), accepted.size()) == 0);
for (const std::size_t depth : {std::size_t{513}, std::size_t{100000}}) {
const std::string rejected = Nested(depth, objects);
Require(_ZN3sce4Json6Parser5parseERNS0_5ValueEPKcm(&root, rejected.c_str(), rejected.size()) < 0);
}
}
_ZN3sce4Json5ValueD1Ev(&root);
}
static void ObjectsAndArrays() {
Object object{};
_ZN3sce4Json6ObjectC1Ev(&object);
@@ -255,6 +277,7 @@ static void NullAccess() {
int main() {
ParseAndRoundTrip();
NestingDepth();
ObjectsAndArrays();
NullAccess();
}