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 22813x 13x   13x 13x   13x 13x 13x 13x               52x             82x   82x 82x 3x       79x 79x     79x 77x 66x       13x                                 90x 90x     90x 5x     85x   85x   83x 4x     79x     79x 79x 81x 115x       79x     79x         79x   2x 2x               138x 136x     133x     88x       88x 88x 88x                     216x     216x                 85x                   84x               83x     82x 82x   82x 234x         83x                   83x 83x     82x               82x 82x 83x   82x               86x 86x             85x   2x 2x           13x   13x        
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 MEMBERSHIPS_TABLE = process.env.MEMBERSHIPS_TABLE_NAME || ''
const TENANTS_TABLE = process.env.TENANTS_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, tenantId, requiredPermission) {
    try {
      // Check if user is the owner of the tenant (owners have all permissions)
      const isOwner = await this.isOwner(userId, tenantId)
      if (isOwner) {
        return { hasPermission: true, reason: 'User is tenant owner' }
      }
 
      // Get user's permissions (cached)
      const result = await this.getUserPermissions(userId, tenantId)
      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 tenant (with caching)
   */
  async getUserPermissions(userId, tenantId) {
    const cacheKey = `${userId}:${tenantId}`
    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, tenantId)
 
      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, tenantId)
      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/tenant (call after role changes)
   */
  clearCache(userId, tenantId) {
    Iif (userId && tenantId) {
      this.cache.delete(`${userId}:${tenantId}`)
    } else {
      this.cache.clear()
    }
  }
 
  /**
   * Get user's roles in a tenant from MEMBERSHIPS_TABLE
   * @private
   */
  async getUserRoles(userId, tenantId) {
    const result = await dynamodb.send(
      new GetCommand({
        TableName: MEMBERSHIPS_TABLE,
        Key: {
          userId: userId,
          tenantId: tenantId
        }
      })
    )
 
    return result.Item || null
  }
 
  /**
   * Batch get multiple roles in a single request (fixes N+1 query problem)
   * @private
   */
  async batchGetRoles(roleIds, tenantId) {
    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: `TENANT#${tenantId}`,
        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 tenant
   * @private
   */
  async isOwner(userId, tenantId) {
    try {
      const result = await dynamodb.send(
        new GetCommand({
          TableName: TENANTS_TABLE,
          Key: { id: tenantId }
        })
      )
 
      return result.Item?.ownerId === userId
    } catch (error) {
      console.error('Error checking tenant ownership:', error)
      return false
    }
  }
}
 
// Export singleton instance
const permissionChecker = new PermissionChecker()
 
module.exports = {
  PermissionChecker,
  permissionChecker
}