open-api icon indicating copy to clipboard operation
open-api copied to clipboard

openapi-request-validator does not validate parameters with external $ref schema

Open mschnee opened this issue 6 years ago • 1 comments

Parameters with a $ref that are defined in externalSchemas, that have custom validation, aren't validated, because openapi-jsonschema-parameters is stripping the $ref.

const someGetter = (req, res) => { res.send(200) }
someGetter.apiDoc = {
parameters: [
      {
        required: true,
        name: 'company_id',
        in: 'path',
        schema: {
          $ref: 'http://my.example.com/schema#definitions/SomeEnum'
        }
      }
    ],
}

Background:

I am using typescript-json-schema to turn my typescript interface definitions into a compiled jsonschema as part of a prebuild task. I am parsing the definitions and supplying them to openapi through the externalSchemas property. I am also adding custom customFormats functions.

One of the things I am trying to validate is a path parameter that should match an enum string. This string is used in lots of places and I would rather maintain a single typescript enum definition, and not a typescript file and also an openapi document (in fact I want to leave it as clean as possible)

openapi-request-validator passes the schema over to openapi-jsonschema-parameters, which strips the $ref.

The easiest hack to 'fix' this is to change copyValidationKeywords to the following

function copyValidationKeywords(src) {
  const dst = {};
+ if (src.$ref) {
+   return {
+     $ref: src.$ref
+   };
+ }
+
  for (let i = 0, keys = Object.keys(src), len = keys.length; i < len; i++) {
    const keyword = keys[i];

    if (
      VALIDATION_KEYWORDS.indexOf(keyword) > -1 ||
      keyword.slice(0, 2) === 'x-'
    ) {
      dst[keyword] = src[keyword];
    }
  }
  return dst;
}

While this works for my immediate need, I am not yet familiar enough with the open-api monorepo to know the actual scope of this change (validate externally-referenced paramaters), or how to create unit tests to cover it.

mschnee avatar May 29 '19 01:05 mschnee

please submit a PR with test cases that prove this doesn't happen

jsdevel avatar May 29 '19 16:05 jsdevel