All files / utils PermissionChecker.js

95.55% Statements 129/135
98% Branches 98/100
100% Functions 26/26
95.12% Lines 117/123

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 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 42880x 80x   80x 80x   80x 80x 80x 80x             817x 817x               329x             80x 80x             2772x 2772x   583x 583x 583x     2189x 2189x 2x 2x   2189x 2189x                       752x           752x 752x   752x 698x     54x                                         827x   827x       807x 14x     793x   792x   21x 21x                 804x   799x     799x 798x 801x 898x       798x                             781x 842x   781x   722x 722x 708x     14x 12x                     42x 42x 42x   58x                   10x                         5x 1x   4x               4x               9x 9x 9x 8x 1x     7x 8x       157x             8x 156x       7x             3021x 3019x   3016x                 149x 149x 8x     141x 141x 5x     136x               3016x   2724x 2724x   2155x     2155x   2724x                             48x 48x 34x       34x 34x   48x                       815x                           813x               818x     817x 817x   817x 1026x         818x                             817x 817x     816x               824x 824x 826x   824x               7x 7x             6x   1x 1x           80x   80x                  
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 ENTITIES_TABLE = process.env.ENTITIES_TABLE_NAME || ''
 
/**
 * The entity id a permission is scoped to (`entities-{id}:…`), or null for a
 * collection-level permission or an `entities-*:…` wildcard.
 */
function scopedEntityId(permission) {
  const match = /^entities-([^:*]+):/.exec(permission || '')
  return match ? match[1] : null
}
 
/**
 * Whether `granted` reaches a restricted entity: only the global `*:*` and a
 * permission naming the entity's id do (UC-ENTITY-007.2 AC-3).
 */
function isExplicitEntityGrant(granted, entityId) {
  return granted === '*:*' || granted.startsWith(`entities-${entityId}:`)
}
 
// Compiled permission regexes, shared across invocations in a warm Lambda container.
// Keyed by pattern (not by the `required` side, which is unbounded/request-specific).
// Bounded to prevent unbounded growth if many distinct permission strings are seen
// over the container's lifetime (e.g. one entry per entity-scoped grant).
const REGEX_CACHE_MAX_SIZE = 1000
const regexCache = new Map()
 
/**
 * Get a compiled regex from cache, building and storing it on a miss.
 * Evicts the least-recently-used entry once the cache is full.
 */
function getCachedRegex(key, build) {
  const cached = regexCache.get(key)
  if (cached) {
    // Move to the end so the LRU order stays accurate.
    regexCache.delete(key)
    regexCache.set(key, cached)
    return cached
  }
 
  const regex = build()
  if (regexCache.size >= REGEX_CACHE_MAX_SIZE) {
    const oldestKey = regexCache.keys().next().value
    regexCache.delete(oldestKey)
  }
  regexCache.set(key, regex)
  return regex
}
 
/**
 * Permission Checker for RBAC system
 * Handles permission validation with wildcard matching
 */
class PermissionChecker {
  /**
   * Check if user has required permission
   */
  async hasPermission(userId, flowId, requiredPermission, options = {}) {
    try {
      // Get user's permissions
      // Note: the flow owner is always assigned the flow's system (admin) role at
      // creation time and can't have it stripped (see roles/assign.js), so owners
      // resolve to full access through the role system itself — no special-casing
      // needed here.
      const result = await this.getUserPermissions(userId, flowId, options.membership)
      const permissions = result.permissions || []
 
      if (await this.permissionsGrant(permissions, requiredPermission, options.entity)) {
        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
   * @param {string} userId
   * @param {string} flowId
   * @param {Object} [membership] - The caller's membership in `flowId` when
   *   already loaded (see shared/activeFlow.js), to skip reading it again
   */
  async getUserPermissions(userId, flowId, membership) {
    try {
      const userRoles =
        membership && membership.userId === userId && membership.flowId === flowId
          ? membership
          : await this.getUserRoles(userId, flowId)
 
      if (!userRoles || !userRoles.roleIds || userRoles.roleIds.length === 0) {
        return { success: true, permissions: [] }
      }
 
      const permissions = await this.getRolesPermissions(userRoles.roleIds, flowId)
 
      return { success: true, permissions }
    } catch (error) {
      console.error('Error getting user permissions:', error)
      return { success: false, permissions: [], error: error.message }
    }
  }
 
  /**
   * Resolve a set of roleIds into the union of their permissions.
   * Shared by membership-based (JWT) and key-based (API key) resolution.
   */
  async getRolesPermissions(roleIds, flowId) {
    if (!roleIds || roleIds.length === 0) return []
 
    const permissionsSet = new Set()
 
    // Use BatchGetItem instead of N sequential queries
    const roles = await this.batchGetRoles(roleIds, flowId)
    for (const role of roles) {
      if (role.permissions && Array.isArray(role.permissions)) {
        role.permissions.forEach((p) => permissionsSet.add(p))
      }
    }
 
    return Array.from(permissionsSet)
  }
 
  /**
   * Whether a resolved permission set grants `required`, honoring restricted
   * entities (UC-ENTITY-007.2 AC-3): when `required` is scoped to one entity and
   * only a wildcard or shorthand matches it, the entity must not be restricted.
   * Its visibility is read only in that case — `*:*` holders and explicit
   * grants never pay the extra GetItem. Pass `entity` when the caller already
   * loaded it.
   * @param {string[]} permissions
   * @param {string} required
   * @param {{ visibility?: string } | null} [entity]
   */
  async permissionsGrant(permissions, required, entity) {
    const matching = (permissions || []).filter((granted) =>
      this.matchesPermission(granted, required)
    )
    if (matching.length === 0) return false
 
    const entityId = scopedEntityId(required)
    if (!entityId || matching.some((granted) => isExplicitEntityGrant(granted, entityId))) {
      return true
    }
 
    const target = entity === undefined ? await this.getEntityVisibility(entityId) : entity
    return target?.visibility !== 'restricted'
  }
 
  /**
   * Synchronous counterpart of permissionsGrant for callers that already hold
   * the entity (e.g. filtering a list in memory).
   * @param {string[]} permissions
   * @param {string} required
   * @param {{ visibility?: string } | null} entity
   */
  grantsOnEntity(permissions, required, entity) {
    const entityId = scopedEntityId(required)
    const restricted = entity?.visibility === 'restricted' && entityId
    return (permissions || []).some(
      (granted) =>
        this.matchesPermission(granted, required) &&
        (!restricted || isExplicitEntityGrant(granted, entityId))
    )
  }
 
  /**
   * Whether `permissions` read both `entity` and its items — what copying an
   * entity out (export, fork) needs on a restricted one.
   */
  grantsEntityAndItemsRead(permissions, entity) {
    return (
      this.grantsOnEntity(permissions, `entities-${entity.id}:read`, entity) &&
      this.grantsOnEntity(permissions, `entities-${entity.id}:items:read`, entity)
    )
  }
 
  /**
   * Read only the visibility of one entity. Throws when ENTITIES_TABLE_NAME is
   * not configured, so a Lambda missing that wiring fails closed (403) rather
   * than silently treating every entity as unrestricted.
   * @private
   */
  async getEntityVisibility(entityId) {
    if (!ENTITIES_TABLE) {
      throw new Error('ENTITIES_TABLE_NAME is required to check restricted entities')
    }
    const result = await dynamodb.send(
      new GetCommand({
        TableName: ENTITIES_TABLE,
        Key: { id: entityId },
        ProjectionExpression: 'id, #visibility',
        ExpressionAttributeNames: { '#visibility': 'visibility' }
      })
    )
    return result.Item || null
  }
 
  /**
   * Batch counterpart of getEntityVisibility: a Map of entityId → visibility
   * for the entities that exist.
   */
  async getEntitiesVisibility(entityIds) {
    const visibilities = new Map()
    const ids = [...new Set(entityIds)]
    if (ids.length === 0) return visibilities
    if (!ENTITIES_TABLE) {
      throw new Error('ENTITIES_TABLE_NAME is required to check restricted entities')
    }
 
    for (const chunk of this.chunkArray(ids, 100)) {
      const result = await dynamodb.send(
        new BatchGetCommand({
          RequestItems: {
            [ENTITIES_TABLE]: {
              Keys: chunk.map((id) => ({ id })),
              ProjectionExpression: 'id, #visibility',
              ExpressionAttributeNames: { '#visibility': 'visibility' }
            }
          }
        })
      )
      for (const item of result.Responses?.[ENTITIES_TABLE] || []) {
        visibilities.set(item.id, item.visibility)
      }
    }
 
    return visibilities
  }
 
  /**
   * Match wildcard permission against required permission
   */
  matchesPermission(granted, required) {
    if (!granted) return false
    if (!required || required === '') return false // Empty permissions are invalid
 
    if (this.matchesPattern(granted, required)) return true
 
    // Flat shorthand: a bare `items:<action>` or `entities:<action>` permission also
    // grants the entity-scoped equivalent for ANY single entity (`entities-{id}:items:<action>` /
    // `entities-{id}:<action>`). This lets API keys/roles be granted broadly with the same
    // short strings the UI has always offered, while an explicit `entities-{id}:...` grant
    // remains available whenever precision (restricting to one entity) is needed.
    // The two shorthands never leak into each other's scope: `items:read` only ever matches
    // the `:items:` form, `entities:read` only ever matches the bare (non-`:items:`) form.
    const itemsAction = /^items:(.+)$/.exec(granted)
    if (itemsAction && this.matchesEntityScoped('items', itemsAction[1], required)) {
      return true
    }
 
    const entitiesAction = /^entities:(.+)$/.exec(granted)
    if (entitiesAction && this.matchesEntityScoped(null, entitiesAction[1], required)) {
      return true
    }
 
    return false
  }
 
  /**
   * Test a single wildcard pattern against a required permission (no shorthand expansion)
   * @private
   */
  matchesPattern(pattern, required) {
    if (pattern === required) return true
 
    try {
      const regex = getCachedRegex(`p:${pattern}`, () => {
        // Convert wildcard pattern to regex
        const regexSource = pattern
          .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // Escape special chars
          .replace(/\*/g, '.*') // * matches anything (including colons)
        return new RegExp(`^${regexSource}$`)
      })
      return regex.test(required)
    } catch (error) {
      console.error('Error matching permission:', error)
      return false
    }
  }
 
  /**
   * Test whether `required` is the entity-scoped form of a flat shorthand action, for
   * exactly one entity ID segment. Unlike `matchesPattern`, the entity ID placeholder here
   * never matches colons, so e.g. the `entities` shorthand (resource=null) can't accidentally
   * swallow a `:items:` segment and match an `entities-{id}:items:<action>` requirement.
   * @private
   */
  matchesEntityScoped(resource, action, required) {
    try {
      const regex = getCachedRegex(`e:${resource || ''}:${action}`, () => {
        const actionPattern = action
          .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // Escape special chars
          .replace(/\*/g, '.*') // * within the action may still match anything
 
        const middle = resource ? `:${resource}:` : ':'
        return new RegExp(`^entities-[^:]+${middle}${actionPattern}$`)
      })
      return regex.test(required)
    } catch (error) {
      console.error('Error matching permission:', error)
      return false
    }
  }
 
  /**
   * 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
        },
        // Role assignment must take effect immediately (no re-login) — an eventually
        // consistent read can still return the pre-update roleIds right after a role
        // change, causing a spurious 403 on the very next request.
        ConsistentRead: true
      })
    )
 
    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,
              // A role (e.g. the system/admin role seeded at flow creation) must be
              // visible to permission checks immediately — an eventually consistent
              // read can otherwise miss a role written moments earlier, causing a
              // spurious permission denial right after flow creation or role changes.
              ConsistentRead: true
            }
          }
        })
      )
 
      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,
  scopedEntityId,
  isExplicitEntityGrant,
  // Exposed for tests only
  regexCache,
  REGEX_CACHE_MAX_SIZE
}