Code Monkey home page Code Monkey logo

oas3-chow-chow's Introduction

oas3-chow-chow

Request and response validator against OpenAPI Specification

Build Status npm

Notes

If you are looking for framework specific middleware, you might want to look at following libraries that use oas3-chow-chow under the hood.

koa-oas3 openapi3-middleware

Installation

$ yarn add oas3-chow-chow
$ # Or
$ npm i oas3-chow-chow

Usage

import ChowChow from "oas3-chow-chow";
import * as fs from "fs";
import * as yaml from "js-yaml";

var doc = yaml.safeLoad(fs.readFileSync("./openapi.yml", "utf8"));
const chow = ChowChow.create(doc);

// For URL: /:pathParam/info?arrParam=x&arrParam=y&other=z
chow.validateRequestByPath(
  // url.pathname,
  "/books/info",
  "POST", {
    path: { pathParam: "books" },
    // query: querystring.parse(url.search.substr(1)),
    query: { arrParam: ["x", "y"], other: "z" },
    // header: req.headers,
    header: { "Content-Type": "application/json" },
    body: { a: 1, b: 2 },
  }
);
chow.validateResponseByPath("/books/info", "POST", {
  header: { "Content-Type": "application/json" },
  body: {
    name: "a nice book",
    author: "me me me"
  }
});

Config

You could optionally provide configs to the constructor

const chow = ChowChow.create(doc, {
  headerAjvOptions: {},
  cookieAjvOptions: {},
  pathAjvOptions: { coerceTypes: true },
  queryAjvOptions: { coerceTypes: 'array' },
  requestBodyAjvOptions: {},
  responseBodyAjvOptions: {},
});
  • headerAjvOptions: Ajv options that pass to header ajv instance
  • cookieAjvOptions: Ajv options that pass to cookie ajv instance
  • pathAjvOptions: Ajv options that pass to path ajv instance, default { coerceTypes: true }
  • queryAjvOptions: Ajv options that pass to query ajv instance, default { coerceTypes: 'array' }
  • requestBodyAjvOptions: Ajv options that pass to request body ajv instance
  • responseBodyAjvOptions: Ajv options that pass to response body ajv instance

Contributors

Pull requests, issues and comments welcome. For pull requests:

  • Add tests for new features and bug fixes
  • Follow the existing style
  • Separate unrelated changes into multiple pull requests
  • See the existing issues for things to start contributing.

For bigger changes, make sure you start a discussion first by creating an issue and explaining the intended change.

Atlassian requires contributors to sign a Contributor License Agreement, known as a CLA. This serves as a record stating that the contributor is entitled to contribute the code/documentation/translation to the project and is willing to have it used in distributions and derivative works (or is willing to transfer ownership).

Prior to accepting your contributions we ask that you please follow the appropriate link below to digitally sign the CLA. The Corporate CLA is for those who are contributing as a member of an organization and the individual CLA is for those contributing as an individual.

oas3-chow-chow's People

Contributors

atlastong avatar crizo23 avatar dependabot[bot] avatar github-actions[bot] avatar jakzo avatar joeyjiron06 avatar krishnagoth avatar lukiano avatar mmalecki avatar nabinked avatar naugtur avatar ngot avatar renovate[bot] avatar rjatkins avatar supertong avatar tagenielsen avatar vvvlasov avatar watiko avatar wjrjerome avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

oas3-chow-chow's Issues

BUG: requestBodyAjvOptions is ignored

The requestBodyAjvOptions are not used when validating requests. They are not passed through to the constructor in CompiledRequestBody.ts, which instead passes an empty object through to the CompiledSchema constructors opts parameter

support wildcard in mediatypes

In CompiledRequestBody, the media types are stored as keys of compiledSchemas, meaning only exact matches are supported.
If the key is image/*, then image/jpeg should match it, unless there's also a specific image/jpeg schema defined.
In addition, / should match all content types not matched by more specific schemas. This includes requests sent without any content type.
I don't know if there's a way to specifically match requests without a content-type set.

Pattern validation not applied to individual values in case of comma separated query params

Steps to recreate the issue

  1. Change query.json /pets petId parameter like below
    {
    "name": "petId",
    "in": "query",
    "required": true,
    "description": "The id of the pet to retrieve",
    "schema": {
    "type": "array",
    "items": {
    "type": "string",
    "pattern": "^[A-Z0-9]+-[0-9]{4}"
    }
    }
    }
  2. change the test case should coerce query parameter to an array in query.spec.ts as below

it('should coerce query parameter to an array', () => {
const queryMeta = {
method: 'get',
query: {
petId:'ACD-2016,ACD-213'
}
};
expect(chowchow.validateRequest('/pets', queryMeta)).toEqual(expect.objectContaining({
query: {
petId: ['ACD-2016,ACD-213']
}
}));
expect(queryMeta.query.petId).toEqual('ACD-2016,ACD-213');
});

As the string ACD-213 is not matching the pattern it should fail but it doesn't
image

Type definition error in ChowErrorMeta

I got an array of object (refer below) for the rawErrors property in ChowErrorMeta when validating the request body using the koa-oas3 middleware.

Received:

[ { start: { line: 2, column: 9, offset: 10 },
    end: { line: 2, column: 19, offset: 20 },
    error: '/id: type should be integer',
    path: '/id' } ]

However, the type of rawErrors property defined in ChowErrorMeta is expecting an array of string instead.

rawErrors?: string[];

Is there anyway that this can be fix?

Thanks.

Feature: ability to identify the endpoint by operationId instead of path+method in validateResponse

When verifying responses path doesn't need to be the basis for validation.
operationId would work better as means to identify which part of the definition to use for verification in tests or anything that runs the validation on responses it got from the server. Path might not be known/available. It might also be harder to obtain in some cases.

Would it be possible to add a validateResponse copy where operationId is used instead of path as the identification?

Support for AJV version 7 and newer JSON schema drafts?

This would allow for compatibility with newer JSON schema draft-06/07/2019-09

I don't know how backwards compatible this would be. Just wondering if it's been considered to keep this library relevant and future-proof.

The one breaking change I see is: the support for JSON-Schema draft-04 is removed - if you have schemas using “id” attributes you have to replace them with “$id” (or continue using Ajv v6 that will be supported until 02/28/2021).

readOnly not working as expected

When adding readonly: true to a schema, an error is thrown by oas3-chow-chow:

'TypeError: Cannot read properties of undefined (reading 'schemaContext')\n    
at Ajv.validate (<path>/node_modules/oas3-chow-chow/src/compiler/CompiledSchema.ts:22:8)\n    
at CompiledSchema.validate [as validator] (eval at localCompile (<path>/node_modules/ajv/lib/compile/index.js:120:26), <anonymous>:3:1785)\n    
at CompiledSchema.validate (<path>/node_modules/oas3-c…edPath.validateRequest (<path>/node_modules/oas3-chow-chow/src/compiler/CompiledPath.ts:49:34)\n   

I believe it's somewhere in this code, but I'm not sure what the code is doing.
I see the code comment "Remove unsupported additional OpenAPI keywords." and what looks to be a redefining of the validation function?

thanks

make use of ajv removeAdditional option

Hi, thanks for sharing this. We were looking for something that would help us to validate with oas3 and this is very helpful.

It would be very useful for us, if we could also make use of the removeAdditional option from ajv. So ajv would filter out inputs/outputs that are not in schema. Is that something you would consider to add to this package? It would probably make sense to have that option separately for headers/cookies/payload/output.

Response validation should support responses without any content type

On https://github.com/atlassian/oas3-chow-chow/blob/master/src/compiler/CompiledResponse.ts#L27

    const contentType = CompiledMediaType.extractMediaType(response.header['content-type']);
    if (contentType && this.content[contentType]) {
      return this.content[contentType].validate(response.body);
    } else {
      throw new ChowError('Unsupported Response Media Type', { in: 'response' })
    }

if contentType is not set, it should just return, instead of throwing an error.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Are serialized path parameters supported

Hi,

Thank you for a great library!

I am getting an error when running validation on an incoming request which has an serialized object as a path parameter.

    "/item/{myId}": {
        "delete": {
            "parameters": [
                {
                    "name": "myId",
                    "in": "path",
                    "required": true,
                    "explode": true,
                    "style": "simple",
                    "schema": {
                        "$ref": "#/components/schemas/MyId"
                    }
                }
            ],
            "responses": {
                "200": {
                    "$ref": "#/components/responses/Success"
                },
                "default": {
                    "$ref": "#/components/responses/Error"
                }
            }
        }

Where MyId is defined as:

{
    "type": "object",
    "properties": {
        "namespace": {
            "type": "string",
            "require": true
        },
        "instance": {
            "type": "string",
            "require": true
        }
    }
}

Doing a DELETE request to /item/namespace=MyNS,instance=MyId gives me:

{
  "message": "RequestValidationError",
  "meta": {
    "in": "path",
    "rawErrors": [
      {
        "start": {
          "line": 2,
          "column": 16,
          "offset": 17
        },
        "end": {
          "line": 2,
          "column": 65,
          "offset": 66
        },
        "error": "/myId: type should be object",
        "path": "/myId"
      }
    ]
  }
}

So I am wondering if serialized parameters are supported?

Thank you
Mattias

Add support uppercase wildcard character X in response code

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#responsesObject

To define a range of response codes, this field MAY contain the uppercase wildcard character X. For example, 2XX represents all response codes between [200-299]. Only the following range definitions are allowed: 1XX, 2XX, 3XX, 4XX, and 5XX. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code.

Consider a config option to bypass better-ajv-errors

I would like to propose bypassing better-ajv-errors using a config option.
Why: AJV can return multiple errors during validation. better-ajv-errors attempts to return "better" errors but in our experience, the chosen errors it chooses to return are not the best, when the full list of errors returned by AJV would be better.
Would the project contributors be open to this?

support for nullable

Are there plans to support oas3 specifics? Unfortunately they are not following json schema standard so there are some subtle differences. Particularly having issue with nullable:

user:
  type: object
  nullable: true

It does not get translated to the form ajv (json schema standard) understand.

validateResponseByOperationId calls validateRequest

file src/index.ts
inside function validateResponseByOperationId is
return compiledOperation.validateRequest(response);

instead of
return compiledOperation.validateResponse(response);

I would create a PR but I am not signing CLA.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm @types/xregexp Unavailable

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency @changesets/cli to v2.27.7
  • chore(deps): update dependency ts-jest to v29.2.4
  • fix(deps): update dependency ajv to v8.17.1
  • fix(deps): update dependency ajv-formats to v3
  • 🔐 Create all rate-limited PRs at once 🔐

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v2
  • actions/setup-node v1
.github/workflows/release.yml
  • actions/checkout v2
  • actions/setup-node v2
  • changesets/action v1
npm
package.json
  • @apidevtools/json-schema-ref-parser ^11.1.0
  • ajv ^8.12.0
  • ajv-formats ^2.1.1
  • better-ajv-errors 1.2.0
  • oas-validator ^5.0.8
  • openapi3-ts ^1.3.0
  • xregexp ^4.2.4
  • @changesets/cli 2.26.2
  • @types/jest 29.5.4
  • @types/node 18.17.11
  • @types/xregexp 3.0.30
  • babel-core 6.26.3
  • babel-jest ^29.7.0
  • jest ^29.7.0
  • prettier 2.2.1
  • ts-jest ^29.1.1
  • typescript 5.2.2

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.