Skip to content

Commit 5fa9cc7

Browse files
authored
handle case when tojson throws an error (#134)
* handle case when tojson throws * return invalid object instead of null * add logs
1 parent d98b1da commit 5fa9cc7

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

src/convert.cpp

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,13 @@ ddwaf_object* to_ddwaf_object_array(
3939
if (!ignoreToJSON) {
4040
Napi::Value toJSON = arr.Get("toJSON");
4141
if (toJSON.IsFunction()) {
42-
return to_ddwaf_object(object, env, toJSON.As<Napi::Function>().Call(arr, {}), depth, lim, true, stack, metrics);
42+
Napi::Value toJSONResult = toJSON.As<Napi::Function>().Call(arr, {});
43+
if (env.IsExceptionPending()) {
44+
mlog("Exception pending");
45+
env.GetAndClearPendingException();
46+
return ddwaf_object_invalid(object);
47+
}
48+
return to_ddwaf_object(object, env, toJSONResult, depth, lim, true, stack, metrics);
4349
}
4450
}
4551

@@ -88,7 +94,13 @@ ddwaf_object* to_ddwaf_object_object(
8894
if (!ignoreToJSON) {
8995
Napi::Value toJSON = obj.Get("toJSON");
9096
if (toJSON.IsFunction()) {
91-
return to_ddwaf_object(object, env, toJSON.As<Napi::Function>().Call(obj, {}), depth, lim, true, stack, metrics);
97+
Napi::Value toJSONResult = toJSON.As<Napi::Function>().Call(obj, {});
98+
if (env.IsExceptionPending()) {
99+
mlog("Exception pending");
100+
env.GetAndClearPendingException();
101+
return ddwaf_object_invalid(object);
102+
}
103+
return to_ddwaf_object(object, env, toJSONResult, depth, lim, true, stack, metrics);
92104
}
93105
}
94106

test/index.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1303,6 +1303,37 @@ describe('limit tests', () => {
13031303
})
13041304
})
13051305

1306+
it('should handle toJSON errors gracefully with invalid fallback', () => {
1307+
const body = {
1308+
a: {
1309+
toJSON: function () {
1310+
throw new Error('error')
1311+
}
1312+
},
1313+
c: 'c'
1314+
}
1315+
1316+
const waf = new DDWAF(processor)
1317+
const context = waf.createContext()
1318+
const result = context.run({
1319+
persistent: {
1320+
'server.request.body': body,
1321+
'waf.context.processor': {
1322+
'extract-schema': true
1323+
}
1324+
}
1325+
}, TIMEOUT)
1326+
1327+
assert.deepStrictEqual(result.derivatives, {
1328+
'server.request.body.schema': [
1329+
{
1330+
a: [0],
1331+
c: [8]
1332+
}
1333+
]
1334+
})
1335+
})
1336+
13061337
it('should truncate string values exceeding maximum length', () => {
13071338
const waf = new DDWAF(rules)
13081339

0 commit comments

Comments
 (0)