Skip to content

Rejecting unknown query parameters should be optional #133 #135

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,20 @@ Determines whether the validator should validate requests.

- `true` (**default**) - validate requests.
- `false` - do not validate requests.
- `{ ... }` - validate requests with options

**allowUnknownQueryParameters:**

- `true` - enables unknown/undeclared query parameters to pass validation
- `false` - (**default**) fail validation if an unknown query parameter is present

For example:

```javascript
validateRequests: {
allowUnknownQueryParameters: true
}
```

### ▪️ validateResponses (optional)

Expand All @@ -361,7 +375,7 @@ Determines whether the validator should validate responses. Also accepts respons
- `false` (**default**) - do not validate responses
- `{ ... }` - validate responses with options

**removeAdditional**
**removeAdditional:**

- `"failing"` - additional properties that fail schema validation are automatically removed from the response.

Expand Down
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"ts-log": "^2.1.4"
},
"devDependencies": {
"@types/ajv": "^1.0.0",
"@types/cookie-parser": "^1.4.1",
"@types/express": "^4.17.0",
"@types/mocha": "^5.2.7",
Expand Down
13 changes: 11 additions & 2 deletions src/framework/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Request, Response, NextFunction } from 'express';
import { Logger } from 'ts-log';
import BasePath from './base.path';
import ajv = require('ajv');
export {
OpenAPIFrameworkArgs,
OpenAPIFrameworkConstructorArgs,
Expand All @@ -19,17 +20,25 @@ export type SecurityHandlers = {
) => boolean | Promise<boolean>;
};

export interface RequestValidatorOptions
extends ajv.Options,
ValidateRequestOpts {}

export type ValidateRequestOpts = {
allowUnknownQueryParameters?: boolean;
};

export type ValidateResponseOpts = {
removeAdditional?: string | boolean;
};

export interface OpenApiValidatorOpts {
apiSpec: OpenAPIV3.Document | string;
validateResponses?: boolean | ValidateResponseOpts;
validateRequests?: boolean;
validateRequests?: boolean | ValidateRequestOpts;
securityHandlers?: SecurityHandlers;
coerceTypes?: boolean;
unknownFormats?: string[] | string | boolean;
unknownFormats?: true | string[] | 'ignore';
multerOpts?: {};
}

Expand Down
13 changes: 12 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Application, Response, NextFunction } from 'express';
import { OpenApiContext } from './framework/openapi.context';
import {
OpenApiValidatorOpts,
ValidateRequestOpts,
ValidateResponseOpts,
OpenApiRequest,
OpenApiRequestHandler,
Expand All @@ -29,6 +30,12 @@ export class OpenApiValidator {
};
}

if (options.validateRequests === true) {
options.validateRequests = {
allowUnknownQueryParameters: false,
};
}

this.options = options;
this.context = new OpenApiContext({
apiDoc: options.apiSpec,
Expand Down Expand Up @@ -101,7 +108,10 @@ export class OpenApiValidator {
}

private installRequestValidationMiddleware(): void {
const { coerceTypes, unknownFormats } = this.options;
const { coerceTypes, unknownFormats, validateRequests } = this.options;
const { allowUnknownQueryParameters } = <ValidateRequestOpts>(
validateRequests
);
const requestValidator = new middlewares.RequestValidator(
this.context.apiDoc,
{
Expand All @@ -110,6 +120,7 @@ export class OpenApiValidator {
removeAdditional: false,
useDefaults: true,
unknownFormats,
allowUnknownQueryParameters,
},
);
const requestValidationHandler: OpenApiRequestHandler = (req, res, next) =>
Expand Down
3 changes: 2 additions & 1 deletion src/middlewares/ajv/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import * as Ajv from 'ajv';
import * as draftSchema from 'ajv/lib/refs/json-schema-draft-04.json';
import { formats } from './formats';
import { OpenAPIV3 } from '../../framework/types';
import ajv = require('ajv');

const TYPE_JSON = 'application/json';

export function createRequestAjv(
openApiSpec: OpenAPIV3.Document,
options: any = {},
options: ajv.Options = {},
): Ajv.Ajv {
return createAjv(openApiSpec, options);
}
Expand Down
28 changes: 21 additions & 7 deletions src/middlewares/openapi.request.validator.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as ajv from 'ajv';
import { createRequestAjv } from './ajv';
import {
ContentType,
Expand All @@ -7,7 +8,12 @@ import {
} from './util';
import ono from 'ono';
import { NextFunction, Response } from 'express';
import { OpenAPIV3, OpenApiRequest } from '../framework/types';
import {
OpenAPIV3,
OpenApiRequest,
RequestValidatorOptions,
ValidateRequestOpts,
} from '../framework/types';
import { Ajv } from 'ajv';

const TYPE_JSON = 'application/json';
Expand All @@ -16,10 +22,16 @@ export class RequestValidator {
private _middlewareCache;
private _apiDocs: OpenAPIV3.Document;
private ajv: Ajv;
private _requestOpts: ValidateRequestOpts = {};

constructor(apiDocs: OpenAPIV3.Document, options = {}) {
constructor(
apiDocs: OpenAPIV3.Document,
options: RequestValidatorOptions = {},
) {
this._middlewareCache = {};
this._apiDocs = apiDocs;
this._requestOpts.allowUnknownQueryParameters =
options.allowUnknownQueryParameters;
this.ajv = createRequestAjv(apiDocs, options);
}

Expand Down Expand Up @@ -106,11 +118,13 @@ export class RequestValidator {

const validator = this.ajv.compile(schema);
return (req, res, next) => {
this.rejectUnknownQueryParams(
req.query,
schema.properties.query,
securityQueryParameter,
);
if (!this._requestOpts.allowUnknownQueryParameters) {
this.rejectUnknownQueryParams(
req.query,
schema.properties.query,
securityQueryParameter,
);
}

const shouldUpdatePathParams =
Object.keys(req.openapi.pathParams).length > 0;
Expand Down
3 changes: 2 additions & 1 deletion test/common/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import * as logger from 'morgan';

import { OpenApiValidator } from '../../src';
import { startServer, routes } from './app.common';
import { OpenApiValidatorOpts } from '../../src/framework/types';

export async function createApp(
opts?: any,
opts?: OpenApiValidatorOpts,
port: number = 3000,
customRoutes: (app) => void = () => {},
useRoutes: boolean = true,
Expand Down
54 changes: 54 additions & 0 deletions test/query.params.allow.unknown.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import * as path from 'path';
import * as express from 'express';
import * as request from 'supertest';
import { createApp } from './common/app';

const packageJson = require('../package.json');

describe(packageJson.name, () => {
let app = null;
let basePath = null;

before(async () => {
// Set up the express app
const apiSpec = path.join('test', 'resources', 'query.params.yaml');
app = await createApp(
{ apiSpec, validateRequests: { allowUnknownQueryParameters: true } },
3005,
app =>
app.use(
`${app.basePath}`,
express
.Router()
.post(`/pets/nullable`, (req, res) => res.json(req.body)),
),
);
});

after(() => {
app.server.close();
});

it('should pass if known query params are specified', async () =>
request(app)
.get(`${app.basePath}/pets`)
.query({
tags: 'one,two,three',
limit: 10,
breed: 'german_shepherd',
owner_name: 'carmine',
})
.expect(200));

it('should not fail if unknown query param is specified', async () =>
request(app)
.get(`${app.basePath}/pets`)
.query({
tags: 'one,two,three',
limit: 10,
breed: 'german_shepherd',
owner_name: 'carmine',
unknown_prop: 'test',
})
.expect(200));
});