All files / utils PermissionChecker.js

93.75% Statements 75/80
91.11% Branches 41/45
100% Functions 11/11
93.15% Lines 68/73

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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 22816x 16x   16x 16x   16x 16x 16x 16x               55x             112x   112x 112x 3x       109x 109x     109x 107x 94x       15x                                 120x 120x     120x 5x     115x   115x   113x 4x     109x     109x 109x 111x 146x       109x     109x         109x   2x 2x               168x 166x     163x     115x       115x 115x 115x                     266x     266x                 115x                   114x               113x     112x 112x   112x 264x         113x                   113x 113x     112x               112x 112x 113x   112x               116x 116x             115x   2x 2x           16x   16x        
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
 
const client = new DynamoDBClient({})
const dynamodb = DynamoDBDocumentClient.from(client)
 
const ROLES_TABLE = process.env.ROLES_TABLE_NAME || ''
const FLOW_MEMBERSHIPS_TABLE = process.env.FLOW_MEMBERSHIPS_TABLE_NAME || ''
const FLOWS_TABLE = process.env.FLOWS_TABLE_NAME || ''
const CACHE_TTL = 5 * 60 * 1000 // 5 minutes
 
/**
 * Permission Checker for RBAC system
 * Handles permission validation with caching and wildcard matching
 */
class PermissionChecker {
  constructor() {
    this.cache = new Map()
  }
 
  /**
   * Check if user has required permission
   */
  async hasPermission(userId, flowId, requiredPermission) {
    try {
      // Check if user is the owner of the flow (owners have all permissions)
      const isOwner = await this.isOwner(userId, flowId)
      if (isOwner) {
        return { hasPermission: true, reason: 'User is flow owner' }
      }
 
      // Get user's permissions (cached)
      const result = await this.getUserPermissions(userId, flowId)
      const permissions = result.permissions || []
 
      // Check each permission
      for (const granted of permissions) {
        if (this.matchesPermission(granted, requiredPermission)) {
          return { hasPermission: true }
        }
      }
 
      return {
        hasPermission: false,
        reason: `User ${userId} lacks permission: ${requiredPermission}`
      }
    } catch (error) {
      console.error('Error checking permission:', error)
      return {
        hasPermission: false,
        error: error.message
      }
    }
  }
 
  /**
   * Get all permissions for a user in a flow (with caching)
   */
  async getUserPermissions(userId, flowId) {
    const cacheKey = `${userId}:${flowId}`
    const cached = this.cache.get(cacheKey)
 
    // Return cached if valid
    if (cached && cached.expiresAt > Date.now()) {
      return { success: true, permissions: cached.permissions }
    }
 
    try {
      // Fetch from database
      const userRoles = await this.getUserRoles(userId, flowId)
 
      if (!userRoles || !userRoles.roleIds || userRoles.roleIds.length === 0) {
        return { success: true, permissions: [] }
      }
 
      const permissionsSet = new Set()
 
      // Use BatchGetItem instead of N sequential queries
      const roles = await this.batchGetRoles(userRoles.roleIds, flowId)
      for (const role of roles) {
        Eif (role.permissions && Array.isArray(role.permissions)) {
          role.permissions.forEach((p) => permissionsSet.add(p))
        }
      }
 
      const permissions = Array.from(permissionsSet)
 
      // Cache result
      this.cache.set(cacheKey, {
        permissions,
        expiresAt: Date.now() + CACHE_TTL
      })
 
      return { success: true, permissions }
    } catch (error) {
      console.error('Error getting user permissions:', error)
      return { success: false, permissions: [], error: error.message }
    }
  }
 
  /**
   * Match wildcard permission against required permission
   */
  matchesPermission(granted, required) {
    if (!granted) return false
    if (!required || required === '') return false // Empty permissions are invalid
 
    // Exact match
    if (granted === required) return true
 
    // Convert wildcard pattern to regex
    const pattern = granted
      .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // Escape special chars
      .replace(/\*/g, '.*') // * matches anything (including colons)
 
    try {
      const regex = new RegExp(`^${pattern}$`)
      return regex.test(required)
    } catch (error) {
      console.error('Error matching permission:', error)
      return false
    }
  }
 
  /**
   * Clear cache for specific user/flow (call after role changes)
   */
  clearCache(userId, flowId) {
    Iif (userId && flowId) {
      this.cache.delete(`${userId}:${flowId}`)
    } else {
      this.cache.clear()
    }
  }
 
  /**
   * Get user's roles in a flow from MEMBERSHIPS_TABLE
   * @private
   */
  async getUserRoles(userId, flowId) {
    const result = await dynamodb.send(
      new GetCommand({
        TableName: FLOW_MEMBERSHIPS_TABLE,
        Key: {
          userId: userId,
          flowId
        }
      })
    )
 
    return result.Item || null
  }
 
  /**
   * Batch get multiple roles in a single request (fixes N+1 query problem)
   * @private
   */
  async batchGetRoles(roleIds, flowId) {
    if (!roleIds || roleIds.length === 0) return []
 
    // DynamoDB BatchGetItem supports max 100 items
    const chunks = this.chunkArray(roleIds, 100)
    const allRoles = []
 
    for (const chunk of chunks) {
      const keys = chunk.map((roleId) => ({
        PK: `FLOW#${flowId}`,
        SK: `ROLE#${roleId}`
      }))
 
      const result = await dynamodb.send(
        new BatchGetCommand({
          RequestItems: {
            [ROLES_TABLE]: {
              Keys: keys
            }
          }
        })
      )
 
      const roles = result.Responses?.[ROLES_TABLE] || []
      allRoles.push(...roles)
    }
 
    return allRoles
  }
 
  /**
   * Split array into chunks of specified size
   * @private
   */
  chunkArray(array, size) {
    const chunks = []
    for (let i = 0; i < array.length; i += size) {
      chunks.push(array.slice(i, i + size))
    }
    return chunks
  }
 
  /**
   * Check if user is the owner of the flow
   * @private
   */
  async isOwner(userId, flowId) {
    try {
      const result = await dynamodb.send(
        new GetCommand({
          TableName: FLOWS_TABLE,
          Key: { id: flowId }
        })
      )
 
      return result.Item?.ownerId === userId
    } catch (error) {
      console.error('Error checking flow ownership:', error)
      return false
    }
  }
}
 
// Export singleton instance
const permissionChecker = new PermissionChecker()
 
module.exports = {
  PermissionChecker,
  permissionChecker
}