cdimascio / express-openapi-validator

🦋 Auto-validates api requests, responses, and securities using ExpressJS and an OpenAPI 3.x specification
MIT License
906 stars 205 forks source link

Multiple spec support breaks if validateResponses: true #881

Open fpolowood opened 8 months ago

fpolowood commented 8 months ago

Describe the bug If I turn on validateResponses: true when using multiple specs, it seems to use the first spec for the definition of the components

To Reproduce

Actual behavior

Expected behavior Each spec should be validated against its own schemas

Examples and context v1.yaml

openapi: 3.0.0
info:
  title: v1
  version: 1.0.0
servers:
  - url: http://localhost:3003/v1
paths:
  /products1:
    get:
      description: get all the products
      tags:
        - products
      responses:
        "200":
          description: success
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/Products1"
components:
  schemas:
    Products1:
      type: object
      properties:
        name: 
          type: string

v2.yaml

openapi: 3.0.0
info:
  title: v2
  version: 1.0.0
servers:
  - url: http://localhost:3003/v2
paths:
  /products1:
    get:
      description: get all the products
      tags:
        - products
      responses:
        "200":
          description: success
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/Products1"
  /products2:
    get:
      description: get all the products
      tags:
        - products
      responses:
        "200":
          description: success
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/Products2"
components:
  schemas:
    Products1:
      type: object
      properties:
        name:
         type: string
    Products2:
      type: object
      properties:
        realname: 
          type: string

index.js

const app = require('express')();
const OpenApiValidator = require('express-openapi-validator');

const validateResponses = true;

app.use(OpenApiValidator.middleware({
  apiSpec: './v1.yaml',
  validateRequests: true,
  validateResponses: validateResponses
}));

app.use('/v1/*', (req,res,next)=>{
  res.json([{'name':'OnePiece'}]);
});

app.use(OpenApiValidator.middleware({
  apiSpec: './v2.yaml',
  validateRequests: true,
  validateResponses: validateResponses
}));

app.use('/v2/*', (req,res,next)=>{
  res.json([{'realname': 'OnePiece'}]);
});

app.listen(3003,()=>{
  console.log('listening on port 3003');
});

simple test from curl

% curl http://localhost:3003/v1/products1
[{"name":"OnePiece"}]

% curl http://localhost:3003/v2/products1
[{"realname":"OnePiece"}]

% curl http://localhost:3003/v2/products2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Error: can&#39;t resolve reference #/components/schemas/Products2 from id #<br> &nbsp; &nbsp;at Object.code (/Users/fpw/Projects/tmp/express-openapi-validator-multiple-apis/node_modules/ajv/dist/vocabularies/core/ref.js:21:19)<br> &nbsp; &nbsp;at keywordCode (/Users/fpw/Projects/tmp/express-openapi-validator-multiple-apis/node_modules/ajv/dist/compile/validate/index.js:464:13)<br> &nbsp; &nbsp;at /Users/fpw/Projects/tmp/express-openapi-validator-multiple-apis/node_modules/ajv/dist/compile/validate/index.js:185:25<br> &nbsp; &nbsp;at CodeGen.code (/Users/fpw/Projects/tmp/express-openapi-validator-multiple-apis/node_modules/ajv/dist/compile/codegen/index.js:439:13)<br> &nbsp; &nbsp;at CodeGen.block (/Users/fpw/Projects/tmp/express-openapi-validator-multiple-apis/node_modules/ajv/dist/compile/codegen/index.js:568:18)<br> &nbsp; &nbsp;at schemaKeywords (/Users/fpw/Projects/tmp/express-openapi-validator-multiple-apis/node_modules/ajv/dist/compile/validate/index.js:185:13)<br> &nbsp; &nbsp;at typeAndKeywords (/Users/fpw/Projects/tmp/express-openapi-validator-multiple-apis/node_modules/ajv/dist/compile/validate/index.js:128:5)<br> &nbsp; &nbsp;at subSchemaObjCode (/Users/fpw/Projects/tmp/express-openapi-validator-multiple-apis/node_modules/ajv/dist/compile/validate/index.js:115:5)<br> &nbsp; &nbsp;at subschemaCode (/Users/fpw/Projects/tmp/express-openapi-validator-multiple-apis/node_modules/ajv/dist/compile/validate/index.js:91:13)<br> &nbsp; &nbsp;at KeywordCxt.subschema (/Users/fpw/Projects/tmp/express-openapi-validator-multiple-apis/node_modules/ajv/dist/compile/validate/index.js:438:9)</pre>
</body>
</html>
mzbik commented 7 months ago

I think the problem stems from both validators mung'ing the request.json method which chains validation which is probably not what you want.

ResponseValidator (from metadataMiddleware) will hook the res.json method. First, it does this for v1 and then for v2. Meaning when res.json gets called in the route, it first get the v2 hook for validation which then calls the v1 hook for validation before calling the original. Inefficient, but OK.

metadataMiddleware will set req.openapi to matching schema. In this case, it will set it to the v2 schema.

Then the validators get called via res.json. The v2 ResponseValidator is called, builds/caches the validator and all is good. Then it delegates to the v1 ResponseValidator. This has has ajvBody set up for the v1 apidoc.

However, buildValidators builds contentTypeSchemas from the res.openapi schema (v2!) and then calls ajvBody to compile one of these schemas. Since ajvBody is bound to the v1 schema, this will raise the exception.

I'm thinking the solution is to not double hook res.json. Hook it ONLY if the request has openapi set to the matching apidoc.

An alternative would be to have the validate() lambda (inside the mung call) to check that req.openapi somehow matches the apidoc associated with the schema.

mzbik commented 6 months ago

@fpolowood Please verify on v5.1.6