Skip to content
This repository was archived by the owner on Nov 8, 2024. It is now read-only.

Commit ecab140

Browse files
fix: adds json schema parsing check during body validation
1 parent 3c0247e commit ecab140

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

lib/units/validateBody.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,27 @@ function getBodyValidator(realType, expectedType) {
148148
return [null, validator[0]];
149149
}
150150

151+
/**
152+
* Parses a given JSON Schema to ensure it's a valid JSON.
153+
* @param {string} schema
154+
*/
155+
const validateJsonSchema = (schema) => {
156+
try {
157+
JSON.parse(schema);
158+
} catch (error) {
159+
throw new Error(`\
160+
Failed to parse a given JSON Schema:
161+
162+
${schema}
163+
164+
Please check if that is a valid JSON and a valid JSON Schema.
165+
166+
Original parsing error:
167+
${error.stack}\
168+
`);
169+
}
170+
};
171+
151172
/**
152173
* Validates given bodies of transaction elements.
153174
* @param {Object<string, any>} expected
@@ -170,6 +191,13 @@ function validateBody(expected, real) {
170191
real.headers && real.headers['content-type'],
171192
'real'
172193
);
194+
195+
// Attempt to parse a given JSON Schema
196+
// in case it's a raw string.
197+
if (typeof expected.bodySchema === 'string') {
198+
validateJsonSchema(expected.bodySchema);
199+
}
200+
173201
const [expectedTypeError, expectedType] = expected.bodySchema
174202
? getBodySchemaType(expected.bodySchema)
175203
: getBodyType(

test/unit/units/validateBody.test.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,4 +444,32 @@ describe('validateBody', () => {
444444
});
445445
});
446446
});
447+
448+
describe('given malformed JSON schema', () => {
449+
const getResult = () =>
450+
validateBody(
451+
{
452+
// Purposely invalid JSON Schema
453+
bodySchema: `
454+
{
455+
"$schema": "http://json-schema.org/draft-04/schema#",
456+
"type": "object",
457+
"properties": {
458+
"href"": {
459+
"type": "string"
460+
}
461+
}
462+
}
463+
}
464+
`
465+
},
466+
{
467+
body: '{ "foo": "bar" }'
468+
}
469+
);
470+
471+
it('must throw with malformed JSON schema error', () => {
472+
expect(getResult).to.throw(/^Failed to parse a given JSON Schema:/g);
473+
});
474+
});
447475
});

0 commit comments

Comments
 (0)