APIDevTools / swagger-parser

Swagger 2.0 and OpenAPI 3.0 parser/validator
https://apitools.dev/swagger-parser
MIT License
1.09k stars 154 forks source link

Don't allow specify undefined property as required in schema #106

Open ikokostya opened 5 years ago

ikokostya commented 5 years ago

Versions

Code example

API specification:

openapi: '3.0.2'
info:
  version: v1
  title: test
paths:
  /:
    post:
      requestBody:
        required: true
        content:
          'application/json':
            schema:
              type: object
              properties:
                foo:
                  type: string
              required:
                - foo
                - bar # This property is not defined!
              additionalProperties: false
      responses:
        200:
          description: Success
const SwaggerParser = require('swagger-parser');

SwaggerParser.validate('api.yml')
  .then((api) => console.log('done'))
  .catch((err) => console.error(err));

Expected behavior

Validation error: property bar is required, but it's not defined.

Actual behavior

No errors.

JamesMessinger commented 5 years ago

This is a good suggestion for a validation rule. Thanks!

ikokostya commented 5 years ago

Just to be clear, z-schema (JSON schema validation library) doesn't check this too:

const ZSchema = require('z-schema');

const validator = new ZSchema();

const schema = {
    type: 'object',
    properties: {
        foo: {
            type: 'string'
        }
    },
    additionalProperties: false,
    required: ['bar']
};

console.log(validator.validateSchema(schema)); // true
jdegre commented 5 years ago

Just to understanda the issue... why the schema in the OP is supposed to be wrong?? In my view, the schema is correct, and it simply says that property "bar" is required, and must always be present in the response, but the schema does not constrain what type it can take. "bar" can be an integer, a string, an object... whatever.

JamesMessinger commented 5 years ago

Right. It's more of a lint rule than a schema violation

florintene commented 4 years ago

Isn't this kind of error a sign that the specification is incorrect. Trying to understand how can a property can be "required" but not defined in the schema. The swagger 2.0 validation option should treat this case as an error, right ? (validate options - validate.spec:true). The swagger 2.0 validation behaviour is that a validation error as per OP was raised and I think it should be also the behaviour to move forward.

Late edit: Functionality is present in the last version, apollogies for confusion i thought it was removed.

stueynz commented 3 years ago

Fixed in https://github.com/APIDevTools/swagger-parser/pull/179 - All the spec consistency checks were only used to work on Swagger 2.0 specs; All fixed now for OpenAPI v3.0 specs; Might get a chance to look into v3.1 changes later.