Skip to content

Commit

Permalink
fix: adds json schema parsing check during body validation
Browse files Browse the repository at this point in the history
  • Loading branch information
artem-zakharchenko committed Jun 25, 2019
1 parent 2eb036d commit 9af94fa
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/units/validateBody.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,27 @@ function getBodyValidator(realType, expectedType) {
return [null, validator[0]];
}

/**
*
* @param {string} schema
*/
const validateJsonSchema = (schema) => {
try {
JSON.parse(schema);
} catch (error) {
throw new Error(`\
Failed to parse a given JSON Schema:
${schema}
Please check if that is a valid JSON and a valid JSON Schema.
Original parsing error:
${error.stack}\
`);
}
};

/**
* Validates given bodies of transaction elements.
* @param {Object<string, any>} expected
Expand All @@ -170,6 +191,13 @@ function validateBody(expected, real) {
real.headers && real.headers['content-type'],
'real'
);

// Attempt to parse a given JSON Schema
// in case it's a raw string.
if (typeof expected.bodySchema === 'string') {
validateJsonSchema(expected.bodySchema);
}

const [expectedTypeError, expectedType] = expected.bodySchema
? getBodySchemaType(expected.bodySchema)
: getBodyType(
Expand Down
28 changes: 28 additions & 0 deletions test/unit/units/validateBody.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -444,4 +444,32 @@ describe('validateBody', () => {
});
});
});

describe('given malformed JSON schema', () => {
const getResult = () =>
validateBody(
{
// Purposely invalid JSON Schema
bodySchema: `
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"href"": {
"type": "string"
}
}
}
}
`
},
{
body: '{ "foo": "bar" }'
}
);

it('must throw with malformed JSON schema error', () => {
expect(getResult).to.throw(/^Failed to parse a given JSON Schema:/g);
});
});
});

0 comments on commit 9af94fa

Please sign in to comment.