All files / utils requirePermission.js

100% Statements 46/46
94.44% Branches 17/18
100% Functions 4/4
100% Lines 46/46

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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 15824x 24x                                                   33x 256x     256x 256x 255x   255x 3x                   252x 13x                       239x 12x   227x       239x       239x 14x 14x                           225x   1x 1x                               5x 5x 5x   5x 1x   4x 1x 1x 1x     3x   3x       3x 2x 2x 2x 2x     1x                 118x   118x 7x 7x 7x 7x     111x     24x          
const { permissionChecker } = require('./PermissionChecker')
const { resolveActiveFlow, NO_ACTIVE_FLOW_ERROR } = require('../shared/activeFlow')
 
/**
 * Middleware to check user permissions before executing Lambda handler
 *
 * @param {Function} handler - The actual Lambda handler function
 * @param {Object} options - Configuration options
 * @param {Function|string} options.permission - Permission string or function that returns permission string
 * @param {Function} [options.resource] - Optional function to extract resource from event (for dynamic permissions)
 * @returns {Function} Wrapped Lambda handler with permission check
 *
 * @example
 * // Static permission
 * exports.handler = requirePermission(async (event) => {
 *   // handler logic
 * }, { permission: 'entities:create' });
 *
 * @example
 * // Dynamic permission based on path parameter
 * exports.handler = requirePermission(async (event) => {
 *   // handler logic
 * }, {
 *   permission: (event) => `entities-${event.pathParameters.id}:read`
 * });
 */
function requirePermission(handler, options) {
  return async (event) => {
    try {
      // Caller from the Cognito authorizer, active flow from X-Flow-Id —
      // verified to be a flow the caller is an active member of
      const userId = event.requestContext?.authorizer?.claims?.sub
      const activeFlow = await resolveActiveFlow(event)
      const flowId = activeFlow?.flowId
 
      if (!userId) {
        return {
          statusCode: 401,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({ error: 'Unauthorized - Missing authentication' })
        }
      }
 
      if (!flowId) {
        return {
          statusCode: 403,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({ error: NO_ACTIVE_FLOW_ERROR })
        }
      }
 
      // Determine required permission
      let requiredPermission
      if (typeof options.permission === 'function') {
        requiredPermission = options.permission(event)
      } else {
        requiredPermission = options.permission
      }
 
      // Check permission
      const result = await permissionChecker.hasPermission(userId, flowId, requiredPermission, {
        membership: activeFlow.membership
      })
 
      if (!result.hasPermission) {
        console.log(`Permission denied: User ${userId} lacks ${requiredPermission}`, result.reason)
        return {
          statusCode: 403,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({
            error: 'Forbidden - Insufficient permissions',
            required: requiredPermission
          })
        }
      }
 
      // Permission granted, execute handler
      return await handler(event)
    } catch (error) {
      console.error('Error in requirePermission middleware:', error)
      return {
        statusCode: 500,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Internal server error' })
      }
    }
  }
}
 
/**
 * Helper to check permission without wrapping (for use inside handlers)
 */
async function checkPermission(event, permission) {
  const userId = event.requestContext?.authorizer?.claims?.sub
  const activeFlow = await resolveActiveFlow(event)
  const flowId = activeFlow?.flowId
 
  if (!userId) {
    throw new Error('Missing authentication context')
  }
  if (!flowId) {
    const error = new Error(NO_ACTIVE_FLOW_ERROR)
    error.statusCode = 403
    throw error
  }
 
  const requiredPermission = typeof permission === 'function' ? permission(event) : permission
 
  const result = await permissionChecker.hasPermission(userId, flowId, requiredPermission, {
    membership: activeFlow.membership
  })
 
  if (!result.hasPermission) {
    const error = new Error('Insufficient permissions')
    error.statusCode = 403
    error.requiredPermission = requiredPermission
    throw error
  }
 
  return true
}
 
/**
 * Like checkPermission, but for callers that have no API-Gateway-shaped
 * `event` (e.g. an SQS-triggered worker) — flowId/userId are passed directly
 * instead of being read from `event.requestContext.authorizer.claims`.
 */
async function checkPermissionDirect(userId, flowId, permission) {
  const result = await permissionChecker.hasPermission(userId, flowId, permission)
 
  if (!result.hasPermission) {
    const error = new Error('Insufficient permissions')
    error.statusCode = 403
    error.requiredPermission = permission
    throw error
  }
 
  return true
}
 
module.exports = {
  requirePermission,
  checkPermission,
  checkPermissionDirect
}