All files / utils validateRolePermissions.js

100% Statements 10/10
100% Branches 4/4
100% Functions 1/1
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 351x                             22x 41x   41x 43x 33x 33x       41x 8x         1x      
const { permissionChecker } = require('./PermissionChecker')
 
/**
 * Validate that a user can create/modify a role with the given permissions
 * Prevents privilege escalation by ensuring user has all permissions they're trying to grant
 *
 * This function takes the creator's permissions directly as an array, allowing it to be tested
 * without database dependencies.
 *
 * @param {string[]} newPermissions - Array of permissions in the new/modified role
 * @param {string[]} creatorPermissions - Array of permissions the creator currently has
 * @throws {Error} If creator doesn't have permission to grant any of the requested permissions
 */
async function validateRolePermissions(newPermissions, creatorPermissions) {
  // Validate each permission in the new role
  for (const newPerm of newPermissions) {
    let allowed = false
 
    for (const creatorPerm of creatorPermissions) {
      if (permissionChecker.matchesPermission(creatorPerm, newPerm)) {
        allowed = true
        break
      }
    }
 
    if (!allowed) {
      throw new Error(`You do not have permission to grant: ${newPerm}`)
    }
  }
}
 
module.exports = {
  validateRolePermissions
}