Hilzu / express-openapi-validate

Express middleware to validate requests based on an OpenAPI 3 document
Apache License 2.0
75 stars 12 forks source link

Extra query parameters don't give an error #56

Open blaisn opened 5 years ago

blaisn commented 5 years ago

Hello, It seems that we are unable to detect extra parameters in the query of a request. For example: GET /pets?foo=bar passes without error even if the parameter "foo" is not defined in my OAS 3 spec. Is it normal behavior? Is there any option to set in the library or ajv in order to get a sort of "additionalProperties : false" for the query parameters? Thanks

irky commented 4 years ago

Hello,

I have noticed that only the query parameters marked as required are validated. For example let's say I have some optional parameter:

paths:
  /things/{namespace}:
    get:
      parameters:
        - $ref: '#/components/parameters/namespace'
        - name: foo
          required: false
          in: query
          schema:
            $ref: '#/components/schemas/foo'

When I do GET /things/test_namespace?bla=something validation passes, but changing required to true makes it fail with code 400 (expected behavior).

In parameters.js file you can see the code:

function buildSchema(parameterObjects) {
    const schema = { query: {}, headers: {}, params: {}, cookies: {} };
    parameterObjects.forEach(parameterObject => {
        const location = parameterObject.in;
        const name = location === "header"
            ? parameterObject.name.toLowerCase()
            : parameterObject.name;
        const parameterSchema = {
            type: "object",
            properties: {
                [name]: parameterObject.schema,
            },
        };
        if (parameterObject.required) {
            parameterSchema.required = [name];
        }
        lodash_1.default.mergeWith(schema[parameterLocationToRequestField(location)], parameterSchema, concatArraysCustomizer);
    });
    return schema;
}

As I checked the if statement is responsible for this behavior. I did a quick test and when you comment out the condition the optional parameter will also be validated. Of course I assume this condition is there for a reason and solution for the problem will be more sophisticated.

        //if (parameterObject.required) {
            parameterSchema.required = [name];
        //}

In my opinion the optional parameters should also be validated, as we don't want to accept anything sent with GET request. At least the other framework for validation express-openapi-validator I used before verified that.