acornejo/jjv

Unknown type causes exception

Closed this issue · 2 comments

An exception is thrown when a type is misspelled on row 350 of jjv.js:

       if (!env.fieldType[schema.type](prop))

Some kind of check that fieldType has such a property might work?

It can easily be triggered like this:

         errors = env.addSchema('x', {
            type: 'object',
            properties: {
               y: {
                  type: 'not known'
               }
            },
            required: [ 'y']
         });
         errors = env.validate('x', {y : 7});

This fix works fine for me, but I'm not sure if the schema error should be reported differently:

@@ -347,7 +347,7 @@
       if (typeof schema.type === 'string') {
         if (options.useCoerce && env.coerceType.hasOwnProperty(schema.type))
           prop = object[name] = env.coerceType[schema.type](prop);
-        if (!env.fieldType[schema.type](prop))
+        if (!env.fieldType.hasOwnProperty(schema.type) || !env.fieldType[schema.type](prop))
           return {'type': schema.type};
       } else {
         malformed = true;

JJV is for catching validation errors of the data, not of the schema. In the case you describe, it is the the schema which is invalid.

There are lots of corrupt schema's that will cause exceptions.

To give you a more serious example, imagine this schema:

{
   allOf: {
       length: 1/0
   }
}

JJV will assume allOf is an array of infinite size, and will attempt to check if each of the entries. Even if we add a hasOwnProperty everywhere it will still go in an infinite loop. We would also have to add checks for the length too, which make sure its positive and not infinite.

There are hundreds of cases like these. To make JJV robust against all of these possibilities would require adding a lot of extra checks which would make it a lot slower.

More importantly, this is not the right way to do things. If you want to deal with user generated (i.e. untrusted) schemas, then the way to do it is to first validate the schema against the json-schema, and then use it.

i.e.:

var jsonSchema = require('json-draft4.json'); // download this from a trusted source so that you know its valid
var userSchema = require('potentially-bad-schema'); // some arbitrary schema
env.addSchema('json-schema', jsonSchema);

if (!env.validate('json-schema', userSchema)) {
   env.addSchema('x', userSchema);
else {
   console.log('User schema is not a valid draft4 json schema');
}

Thanks, validating the schema seems a better approach than adding a lot of error handling to the validation. I'll do that.