From 6fea0d8305034ce3cc61be7a913e9e817e39c960 Mon Sep 17 00:00:00 2001 From: Jason Nah Date: Mon, 1 Aug 2016 22:01:41 +1000 Subject: [PATCH] Add custom error raising. * Function to customise how Boom errors are raised. --- README.md | 6 ++ lib/index.js | 39 +++++++++---- package.json | 4 ++ test/error_func_server.js | 62 ++++++++++++++++++++ test/error_func_test.js | 116 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 217 insertions(+), 10 deletions(-) create mode 100644 test/error_func_server.js create mode 100644 test/error_func_test.js diff --git a/README.md b/README.md index 53c7537..7237d37 100644 --- a/README.md +++ b/README.md @@ -189,6 +189,12 @@ signature `function(decoded, callback)` where: - `responseFunc` - (***optional***) function called to decorate the response with authentication headers before the response headers or payload is written where: - `request` - the request object. - `reply(err, response)`- is called if an error occurred +- `errorFunc` - (***optional*** *defaults to raising the error requested*) function called when an error has been raised. It provides an extension point to allow the host the ability to customise the error messages returned. Passed in object follows the following schema: + - `errorContext.errorType` - ***required*** the `Boom` method to call (eg. unauthorized) + - `errorContext.message` - ***required*** the `message` passed into the `Boom` method call + - `errorContext.schema` - the `schema` passed into the `Boom` method call + - `errorContext.attributes` - the `attributes` passed into the `Boom` method call + - The function is expected to return the modified `errorContext` with all above fields defined. - `urlKey` - (***optional*** *defaults to* `'token'`) - if you prefer to pass your token via url, simply add a `token` url parameter to your request or use a custom parameter by setting `urlKey`. To disable the url parameter set urlKey to `false` or ''. - `cookieKey` - (***optional*** *defaults to* `'token'`) - if you prefer to set your own cookie key or your project has a cookie called `'token'` for another purpose, you can set a custom key for your cookie by setting `options.cookieKey='yourkeyhere'`. To disable cookies set cookieKey to `false` or ''. - `headerKey` - (***optional*** *defaults to* `'authorization'`) - if you want to set a custom key for your header token use the `headerKey` option. To disable header token set headerKey to `false` or ''. diff --git a/lib/index.js b/lib/index.js index e60a3e4..d4d56c1 100644 --- a/lib/index.js +++ b/lib/index.js @@ -23,17 +23,36 @@ internals.implementation = function (server, options) { assert(options, 'options are required for jwt auth scheme'); // pre-auth checks assert(options.validateFunc || options.verifyFunc, 'validateFunc OR verifyFunc function is required!') + var raiseError = function(errorType, message, scheme, attributes) { + if (options.errorFunc && internals.isFunction(options.errorFunc)) { + var errorContext = { + errorType: errorType, + message: message, + scheme: scheme, + attributes: attributes, + }; + errorContext = options.errorFunc(errorContext); + if (errorContext) { + errorType = errorContext.errorType; + message = errorContext.message; + scheme = errorContext.scheme; + attributes = errorContext.attributes; + } + } + return Boom[errorType](message, scheme, attributes); + }; + return { authenticate: function (request, reply) { var token = extract(request, options); // extract token from Header, Cookie or Query param if (!token) { - return reply(Boom.unauthorized(null, 'Token')); + return reply(raiseError('unauthorized', null, 'Token')); } if (!extract.isValid(token)) { // quick check for validity of token format - return reply(Boom.unauthorized('Invalid token format', 'Token')); + return reply(raiseError('unauthorized', 'Invalid token format', 'Token')); } // verification is done later, but we want to avoid decoding if malformed request.auth.token = token; // keep encoded JWT available in the request lifecycle // otherwise use the same key (String) to validate all JWTs @@ -42,7 +61,7 @@ internals.implementation = function (server, options) { decoded = JWT.decode(token, { complete: options.complete || false }); } catch(e) { // request should still FAIL if the token does not decode. - return reply(Boom.unauthorized('Invalid token format', 'Token')); + return reply(raiseError('unauthorized', 'Invalid token format', 'Token')); } if(options.key && typeof options.validateFunc === 'function') { @@ -51,7 +70,7 @@ internals.implementation = function (server, options) { keyFunc(decoded, function (err, key, extraInfo) { if (err) { - return reply(Boom.wrap(err)); + return reply(raiseError('wrap', err)); } if (extraInfo) { request.plugins[pkg.name] = { extraInfo: extraInfo }; @@ -59,15 +78,15 @@ internals.implementation = function (server, options) { var verifyOptions = options.verifyOptions || {}; JWT.verify(token, key, verifyOptions, function (err, decoded) { if (err) { - return reply(Boom.unauthorized('Invalid token', 'Token'), null, { credentials: null }); + return reply(raiseError('unauthorized', 'Invalid token', 'Token'), null, { credentials: null }); } else { // see: http://hapijs.com/tutorials/auth for validateFunc signature options.validateFunc(decoded, request, function (err, valid, credentials) { // bring your own checks if (err) { - return reply(Boom.wrap(err)); + return reply(raiseError('wrap', err)); } else if (!valid) { - return reply(Boom.unauthorized('Invalid credentials', 'Token'), null, { credentials: credentials || decoded }); + return reply(raiseError('unauthorized', 'Invalid credentials', 'Token'), null, { credentials: credentials || decoded }); } else { return reply.continue({ credentials: credentials || decoded, artifacts: token }); @@ -80,10 +99,10 @@ internals.implementation = function (server, options) { else { // see: https://github.com/dwyl/hapi-auth-jwt2/issues/130 options.verifyFunc(decoded, request, function(err, valid, credentials) { if (err) { - return reply(Boom.wrap(err)); + return reply(raiseError('wrap', err)); } else if (!valid) { - return reply(Boom.unauthorized('Invalid credentials', 'Token'), null, { credentials: decoded }); + return reply(raiseError('unauthorized', 'Invalid credentials', 'Token'), null, { credentials: decoded }); } else { return reply.continue({ credentials: credentials, artifacts: token }); } @@ -97,7 +116,7 @@ internals.implementation = function (server, options) { if(options.responseFunc && typeof options.responseFunc === 'function') { options.responseFunc(request, reply, function(err) { if (err) { - return reply(Boom.wrap(err)); + return reply(raiseError('wrap', err)); } else { reply.continue(); diff --git a/package.json b/package.json index 5fad7cb..42800cb 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,10 @@ { "name": "Benjamin Lees", "email": "@benjaminlees " + }, + { + "name": "Jason Nah", + "email": "@jyn " } ], "license": "ISC", diff --git a/test/error_func_server.js b/test/error_func_server.js new file mode 100644 index 0000000..b81de15 --- /dev/null +++ b/test/error_func_server.js @@ -0,0 +1,62 @@ +var Hapi = require('hapi'); +var secret = 'NeverShareYourSecret'; + +// for debug options see: http://hapijs.com/tutorials/logging +var debug; +// debug = { debug: { 'request': ['error', 'uncaught'] } }; +debug = { debug: false }; +var server = new Hapi.Server(debug); +server.connection(); + +var sendToken = function(req, reply) { + return reply(req.auth.token); +}; + +var privado = function(req, reply) { + return reply(req.auth.credentials); +}; + +// defining our own validate function lets us do something +// useful/custom with the decodedToken before reply(ing) +var customVerifyFunc = function (decoded, request, callback) { + if(decoded.error) { + return callback(new Error('customVerify fails!')); + } + else if (decoded.custom_error) { + return callback(new Error(decoded.custom_error)); + } + else if (decoded.some_property) { + return callback(null, true, decoded); + } + else { + return callback(null, false, decoded); + } +}; + +var customErrorFunc = function (errorContext) { + var result = errorContext; + if (errorContext.message.toString().search(/ignore/) >= 0) { + result = null; + } else if (errorContext.errorType === 'unauthorized') { + result.message = "Invalid credentials mate"; + } + return result; +}; + +server.register(require('../'), function () { + + server.auth.strategy('jwt', 'jwt', { + verifyFunc: customVerifyFunc, // no validateFunc or key required. + errorFunc: customErrorFunc + }); + + server.route([ + { method: 'GET', path: '/', handler: sendToken, config: { auth: false } }, + { method: 'GET', path: '/required', handler: privado, config: { auth: { mode: 'required', strategy: 'jwt' } } }, + { method: 'GET', path: '/optional', handler: privado, config: { auth: { mode: 'optional', strategy: 'jwt' } } }, + { method: 'GET', path: '/try', handler: privado, config: { auth: { mode: 'try', strategy: 'jwt' } } } + ]); + +}); + +module.exports = server; diff --git a/test/error_func_test.js b/test/error_func_test.js new file mode 100644 index 0000000..4eff1d1 --- /dev/null +++ b/test/error_func_test.js @@ -0,0 +1,116 @@ +var test = require('tape'); +var JWT = require('jsonwebtoken'); +// var secret = 'NeverShareYourSecret'; + +var server = require('./error_func_server'); // test server which in turn loads our module + +test("Access a route that has no auth strategy", function(t) { + var options = { + method: "GET", + url: "/" + }; + // server.inject lets us simulate an http request + server.inject(options, function(response) { + t.equal(response.statusCode, 200, "GET / still works without token."); + t.end(); + }); +}); + +test("customVerify simulate error condition", function(t) { + var payload = { id: 123, "name": "Charlie", error: true } + var token = JWT.sign(payload, 'SecretDoesNOTGetVerified'); + var options = { + method: "GET", + url: "/required", + headers: { authorization: "Bearer " + token } + }; + // server.inject lets us simulate an http request + server.inject(options, function(response) { + t.equal(response.statusCode, 500, "customVerify force error"); + t.equal(response.result.message, "An internal server error occurred", "GET /required with forced error that has not been customised"); + t.end(); + }); +}); + +test("customVerify simulate error condition but is safely not customised", function(t) { + var payload = { id: 123, "name": "Charlie", custom_error: 'ignore'} + var token = JWT.sign(payload, 'SecretDoesNOTGetVerified'); + var options = { + method: "GET", + url: "/required", + headers: { authorization: "Bearer " + token } + }; + // server.inject lets us simulate an http request + server.inject(options, function(response) { + t.equal(response.statusCode, 500, "customVerify force error"); + t.equal(response.result.message, "An internal server error occurred", "GET /required with forced error that has not been customised"); + t.end(); + }); +}); + +test("customVerify with fail condition", function(t) { + var payload = { id: 123, "name": "Charlie", some_property: false } + var token = JWT.sign(payload, 'SecretDoesNOTGetVerified'); + var options = { + method: "GET", + url: "/required", + headers: { authorization: "Bearer " + token } + }; + // server.inject lets us simulate an http request + server.inject(options, function(response) { + t.equal(response.statusCode, 401, "GET /required with customVerify rejected"); + t.equal(response.result.message, "Invalid credentials mate", "GET /required with customVerify rejected and customised error message"); + t.end(); + }); +}); + +test("Custom Verification in 'try' mode ", function(t) { + var payload = { id: 123, "name": "Charlie", some_property: true } + var token = JWT.sign(payload, 'SecretDoesNOTGetVerified'); + var options = { + method: "GET", + url: "/try", + headers: { authorization: "Bearer " + token } + }; + // server.inject lets us simulate an http request + server.inject(options, function(response) { + t.equal(response.result.id, payload.id, 'Decoded JWT returned by handler'); + t.equal(response.statusCode, 200, "GET /try bypasses verification"); + t.end(); + }); +}); + +test("Custom Verification in 'optional' mode ", function(t) { + var payload = { id: 234, "name": "Oscar", some_property: true } + var token = JWT.sign(payload, 'SecretDoesNOTGetVerified'); + var options = { + method: "GET", + url: "/optional", + headers: { authorization: "Bearer " + token } + }; + // server.inject lets us simulate an http request + server.inject(options, function(response) { + t.equal(response.result.id, payload.id, 'Decoded JWT returned by handler'); + t.equal(response.statusCode, 200, "GET /optional bypasses verification"); + t.end(); + }); +}); + +test("Custom Verification in 'required' mode ", function(t) { + var payload = { id: 345, "name": "Romeo", some_property: true } + var token = JWT.sign(payload, 'AnyStringWillDo'); + var options = { + method: "GET", + url: "/required", + headers: { authorization: "Bearer " + token } + }; + // server.inject lets us simulate an http request + server.inject(options, function(response) { + // console.log(response.result); + var credentials = JSON.parse(JSON.stringify(response.result)); + t.equal(credentials.id, payload.id, 'Decoded JWT is available in handler'); + t.equal(response.statusCode, 200, "GET /required bypasses verification"); + t.end(); + }); +}); +