Skip to content

Fix #604: Send custom objects to middleware from security validators #752

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
8 changes: 8 additions & 0 deletions src/framework/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,14 @@ interface ErrorHeaders {
Allow?: string;
}

export class CustomError extends Error {
error!: any;
constructor(error: any) {
super(error.message || "Custom Error");
this.error = error;
}
}

export class HttpError extends Error implements ValidationError {
status!: number;
path?: string;
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as res from './resolvers';
import { OpenApiValidator, OpenApiValidatorOpts } from './openapi.validator';
import { OpenApiSpecLoader } from './framework/openapi.spec.loader';
import {
CustomError,
InternalServerError,
UnsupportedMediaType,
RequestEntityTooLarge,
Expand All @@ -18,6 +19,7 @@ import {
export const resolvers = res;
export const middleware = openapiValidator;
export const error = {
CustomError,
InternalServerError,
UnsupportedMediaType,
RequestEntityTooLarge,
Expand Down
22 changes: 15 additions & 7 deletions src/middlewares/openapi.security.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
OpenApiRequestHandler,
InternalServerError,
HttpError,
CustomError,
} from '../framework/types';

const defaultSecurityHandler = (
Expand All @@ -20,7 +21,7 @@ type SecuritySchemesMap = {
interface SecurityHandlerResult {
success: boolean;
status?: number;
error?: string;
error?: string | Error;
}
export function security(
apiDoc: OpenAPIV3.Document,
Expand Down Expand Up @@ -108,12 +109,19 @@ export function security(
throw firstError;
}
} catch (e) {
const message = e?.error?.message || 'unauthorized';
const err = HttpError.create({
status: e.status,
path: path,
message: message,
});
let err: Error;

// Pass a custom Error instance to next if available
if (e?.error instanceof CustomError) {
err = e.error.error;
} else {
const message = e?.error?.message || 'unauthorized';
err = HttpError.create({
status: e.status,
path: path,
message: message,
});
}
/*const err =
e.status == 500
? new InternalServerError({ path: path, message: message })
Expand Down
22 changes: 22 additions & 0 deletions test/common/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@ import * as OpenApiValidator from '../../src';
import { startServer, routes } from './app.common';
import { OpenApiValidatorOpts } from '../../src/framework/types';

export class JsonResponse {
public status: number;
public message: string;
public data: any;

constructor(status: number, message: string, data: any) {
this.status = status;
this.message = message;
this.data = data;
}
}

export async function createApp(
opts?: OpenApiValidatorOpts,
port = 3000,
Expand All @@ -31,6 +43,16 @@ export async function createApp(

app.use(OpenApiValidator.middleware(opts));

// Add custom error handler
app.use((err, req, res, next) => {
if (err instanceof JsonResponse) {
res.status(err.status);
res.json(JSON.parse(JSON.stringify(err, null, 2)));
} else {
next(err);
}
});

if (useRoutes) {
// register common routes
routes(app);
Expand Down
31 changes: 30 additions & 1 deletion test/security.handlers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import * as path from 'path';
import * as express from 'express';
import { expect } from 'chai';
import * as request from 'supertest';
import { createApp } from './common/app';
import { createApp, JsonResponse } from './common/app';
import {
OpenApiValidatorOpts,
ValidateSecurityOpts,
OpenAPIV3,
CustomError,
} from '../src/framework/types';

// NOTE/TODO: These tests modify eovConf.validateSecurity.handlers
Expand Down Expand Up @@ -67,6 +68,34 @@ describe('security.handlers', () => {
);
}));

it('should return Custom Error for the security validation is provided', async () => {

const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity;
validateSecurity.handlers.ApiKeyAuth = <any>function (req, scopes, schema) {
const jsonResponse = new JsonResponse(418, "Just Kidding", {
data1: true,
data2: "false",
data3: null
});
throw new CustomError(jsonResponse);
};

return request(app)
.get(`${basePath}/api_key`)
.set('X-API-Key', 'test')
.expect(418)
.then((r) => {
const body = r.body;
expect(body.status).to.equal(418);
expect(body.message).to.equal("Just Kidding");
expect(body.data).to.deep.equal({
data1: true,
data2: "false",
data3: null
})
});
});

it('should return 401 if apikey handler returns false', async () => {
const validateSecurity = <ValidateSecurityOpts>eovConf.validateSecurity;
validateSecurity.handlers.ApiKeyAuth = <any>function (req, scopes, schema) {
Expand Down