sagold / json-schema-library

Customizable and hackable json-validator and json-schema utilities for traversal, data generation and validation
MIT License
164 stars 19 forks source link

Array values mutated during validate when allOf exists #57

Closed xjamundx closed 3 months ago

xjamundx commented 3 months ago

This is a weird one....but....if I freeze an array in the values under certain conditions (you have an array AND allOf must exist), it will throw an error.

const schema = {
  "id": "animals",
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "horse": {
      "type": "string"
    },
    "dog": {
      "type": "string"
    },
    "lizards": {
      "minItems": 3,
      "type": "array",
      "items": {
        "type": "string"
      }
    }
  },
  "allOf": [
    {
      "if": {
        "properties": {
          "horse": {
            "const": ""
          }
        }
      },
      "then": {
        "properties": {
          "dog": {
            "minLength": 1
          }
        }
      }
    }
  ]
};

var Draft07 = new require("json-schema-library").Draft07;
var x = new Draft07(schema);
x.validate({ lizards: Object.freeze([]) });

/**
  * Uncaught TypeError: Cannot add property 0, object is not extensible
  * at Object.array 
  *  (/node_modules/json-schema-library/dist/jsonSchemaLibrary.js:2:53249)
  *     at fr (/node_modules/json-schema-library/dist/jsonSchemaLibrary.js:2:51135)
 **/

And wildly if you don't freeze the array, it just fills it up with an empty string for the number of items are set with minItems. What a good time!

> var a = [];
> var Draft07 = new require("json-schema-library").Draft07;
var x = new Draft07(schema);
x.validate({ lizards: a })
[]
> a
[ '', '', '' ]

I think the error is happening here, but haven't had time to look into it yet: https://github.com/sagold/json-schema-library/blob/b49f741f4163d9e628a8234a12a6708c020b1861/lib/getTemplate.ts#L362

sagold commented 3 months ago

Yes, indeed. getTemplate is used on your input data. With minItems set to 3 it creates data according to your schema. This should not happen on validate.

Which version are you using?

sagold commented 3 months ago

I found the issue in lib/features/allOf.ts. Unsure why this is done. Will fix this.

Thank you so much for the report!

sagold commented 3 months ago

The issue has been fixed with json-schema-library@9.3.2.

Can you verify that this solves your issue?

xjamundx commented 3 months ago

Thank you so much will give this a shot tomorrow 🙏🏻

xjamundx commented 3 months ago

Definitely fixes it, thanks 🙏🏻