All files / utils entityDeletionRoleCleanup.js

100% Statements 19/19
80% Branches 8/10
100% Functions 2/2
100% Lines 17/17

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 662x 2x 2x                                     6x               6x 6x   6x 6x 8x 6x   5x 2x 2x 2x     3x                           6x             2x  
const { QueryCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
const { batchDelete } = require('./batchWrite')
const { removeRoleIdsFromMemberships } = require('./membershipRoleCleanup')
 
/**
 * After an entity is deleted, any role permission scoped to it
 * (`entities-{entityId}:...`) becomes a dangling reference — wildcard
 * permissions like `entities-*:read` are untouched since they don't name
 * this entity specifically. For every role in the flow: strips permissions
 * scoped to the deleted entity; if that empties a non-system role, deletes
 * the role and removes it from every membership's roleIds. System roles are
 * protected from deletion elsewhere (see roles/delete.js), so cleanup here
 * only ever strips their permissions, never removes them.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {{ rolesTableName: string, flowMembershipsTableName: string, flowId: string, entityId: string }} params
 */
async function cleanupRolesForDeletedEntity(
  docClient,
  { rolesTableName, flowMembershipsTableName, flowId, entityId }
) {
  const rolesResult = await docClient.send(
    new QueryCommand({
      TableName: rolesTableName,
      IndexName: 'flowIndex',
      KeyConditionExpression: 'flowId = :flowId',
      ExpressionAttributeValues: { ':flowId': flowId }
    })
  )
  const entityScope = `entities-${entityId}`
  const removedRoleIds = []
 
  for (const role of rolesResult.Items || []) {
    const permissions = role.permissions || []
    const remaining = permissions.filter((permission) => permission.split(':')[0] !== entityScope)
    if (remaining.length === permissions.length) continue
 
    if (remaining.length === 0 && !role.isSystemRole) {
      await batchDelete(docClient, rolesTableName, [{ PK: role.PK, SK: role.SK }])
      removedRoleIds.push(role.roleId)
      continue
    }
 
    await docClient.send(
      new UpdateCommand({
        TableName: rolesTableName,
        Key: { PK: role.PK, SK: role.SK },
        UpdateExpression: 'SET #permissions = :permissions, #updatedAt = :updatedAt',
        ExpressionAttributeNames: { '#permissions': 'permissions', '#updatedAt': 'updatedAt' },
        ExpressionAttributeValues: {
          ':permissions': remaining,
          ':updatedAt': new Date().toISOString()
        }
      })
    )
  }
 
  await removeRoleIdsFromMemberships(docClient, {
    flowMembershipsTableName,
    flowId,
    roleIds: removedRoleIds
  })
}
 
module.exports = { cleanupRolesForDeletedEntity }