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

Invalid request validation #70

Open quirinobrizi opened 3 years ago

quirinobrizi commented 3 years ago

I'm getting the following error for request validation:

error while validating request: request should have required property '.headers'

The stack I am using is:

Doing some research I narrowed it down to the following code part of the validate function:

const reqToValidate = {
        ...req,
        cookies: req.cookies
          ? { ...req.cookies, ...req.signedCookies }
          : undefined,
      };

Which compiles to:

const reqToValidate = Object.assign({}, req, { cookies: req.cookies
                    ? Object.assign({}, req.cookies, req.signedCookies) : undefined });

The problem here is express uses accessors get/set for the headers, as a result the property headers is not present as part of reqToValidate.

As a quick fix the issue I implemented the following:

const validator = this.openApiValidator.validate(method, path);
return (req, res, next) => {
    const reqToValidate = Object.assign({}, req, {
        cookies: req.cookies
            ? Object.assign({}, req.cookies, req.signedCookies) : undefined
    });

    if (!reqToValidate.hasOwnProperty('headers')) {
        reqToValidate.headers = req.headers;
    }
    return validator(reqToValidate, res, next);
};

which works pretty well.

Thanks, ~Q

Hilzu commented 3 years ago

This should now be fixed in the latest v0.6.0 release. Is it working for you @quirinobrizi?