ajv icon indicating copy to clipboard operation
ajv copied to clipboard

Unexpected behavior with removeAdditional and minProperties

Open Vladislao opened this issue 5 months ago • 2 comments

What version of Ajv are you using? Does the issue happen if you use the latest version? [email protected]

Ajv options object

{
  removeAdditional: true
}

JSON Schema

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "additionalProperties": false,
  "minProperties": 1,
  "type": "object",
  "properties": {
    "good": {
      "type": "string"
    }
  },
  "required": []
}

Sample data

{ "bad": "will be removed" }

Your code

const Ajv = require("ajv");
const ajv = new Ajv(options);

const validate = ajv.compile(schema);

console.log(validate(data));
console.log(validate.errors);
console.log(data);

Working code sample: https://runkit.com/vladislao/65c2a14a50acdd0009747ee5

Validation result, data AFTER validation, error messages

true
null
{}

What results did you expect?

The validation is expected to fail given the constraints of minProperties: 1 and additionalProperties: false. While it may be apparent in isolated examples that removing properties can lead to such behavior, the issue becomes less obvious when Ajv is used indirectly, such as in Fastify where Ajv is the default validation tool. This situation can easily lead to errors, allowing empty objects to slip through the validation process and potentially causing unexpected behavior and security issues in applications.

Related to https://github.com/fastify/fastify/issues/5104

Vladislao avatar Feb 06 '24 22:02 Vladislao