SunAns
SunAns

Reputation: 313

Ensure scope is not undefined Hapijs

A restricted user could access a route just because there was a code bug where the scope was setting to empty array. How to ensure that the scope in hapijs is never undefined?

const { roles} = require('../permissions');
module.exports = {
    method: 'GET',
    path: '/profile',
    handler: Customer.profile,
    options: {
        tags: ['api'],
        validate: {},
        auth: {
            strategy: 'simple',
            scope: roles.read,
        },
    },
};

The error was that the 'roles' was not de-structered when imported and written as const roles = require('../permissions');

I'm also using Joi. Can that help?

Upvotes: 0

Views: 36

Answers (1)

carpinchosaurio
carpinchosaurio

Reputation: 1216

You can assert that roles variable is not an empty array and your selected role is not an empty string, depending on how many things to assert could be various checks or just one, let's do the former to illustrate.

const { roles } = require('../permissions');
const read_role = roles.read;
assert(read_role, "Read Role must be there"); // Only validate that read_role is not falsy, you can customize it to your needs.

module.exports = {
    method: 'GET',
    path: '/profile',
    handler: Customer.profile,
    options: {
        tags: ['api'],
        validate: {},
        auth: {
            strategy: 'simple',
            scope: read_role,
        },
    },
};

You can also create joi schema to validate the imported roles but essentially you will end up doing something like asserting the roles containing something and that something is what you expect, if that is correct you will continue if not, you don't want to continue registering the route. and the assert from above will do exactly that.

But this looks more like something you need to cover in unit tests.

Upvotes: 1

Related Questions