All files / roles assign.js

100% Statements 57/57
90% Branches 36/40
100% Functions 10/10
100% Lines 52/52

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 2091x           1x 1x 1x 1x   1x 1x     26x 26x 26x 26x 26x   26x 2x                   24x 2x                     22x             21x 4x                   4x 8x 4x   4x   4x 2x                       19x             19x 2x                           17x           17x 1x                     16x                                 15x   15x                 2x 2x                     1x                         75x 17x   14x 14x 4x 4x 14x   4x           4x   4x   4x   2x     2x   2x         1x      
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  UpdateCommand,
  GetCommand,
  QueryCommand
} = require('@aws-sdk/lib-dynamodb')
const { requirePermission } = require('../utils/requirePermission')
const { permissionChecker, scopedEntityId } = require('../utils/PermissionChecker')
const { notifyPermissionsChanged } = require('../utils/permissionsChangedPush')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
async function assignRolesHandler(event) {
  try {
    const flowId = event.pathParameters?.flowId
    const targetUserId = event.pathParameters?.userId
    const body = JSON.parse(event.body || '{}')
    const currentUserId = event.requestContext?.authorizer?.claims?.sub
 
    if (!currentUserId || !flowId || !targetUserId) {
      return {
        statusCode: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    if (!body.roleIds || !Array.isArray(body.roleIds)) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Missing roleIds array' })
      }
    }
 
    // Prevent stripping the flow's system (admin) role from the flow owner
    const flow = await docClient.send(
      new GetCommand({
        TableName: process.env.FLOWS_TABLE_NAME,
        Key: { id: flowId }
      })
    )
 
    if (flow.Item && flow.Item.ownerId === targetUserId) {
      const rolesResult = await docClient.send(
        new QueryCommand({
          TableName: process.env.ROLES_TABLE_NAME,
          KeyConditionExpression: 'PK = :pk AND begins_with(SK, :sk)',
          ExpressionAttributeValues: {
            ':pk': `FLOW#${flowId}`,
            ':sk': 'ROLE#'
          }
        })
      )
      const systemRoleIds = (rolesResult.Items || [])
        .filter((role) => role.isSystemRole)
        .map((role) => role.roleId)
 
      const keepsSystemRole = systemRoleIds.some((roleId) => body.roleIds.includes(roleId))
 
      if (systemRoleIds.length > 0 && !keepsSystemRole) {
        return {
          statusCode: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({ error: 'Owner must keep the system (admin) role' })
        }
      }
    }
 
    // Check target user membership exists
    const membership = await docClient.send(
      new GetCommand({
        TableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
        Key: { userId: targetUserId, flowId }
      })
    )
 
    if (!membership.Item || membership.Item.status !== 'active') {
      return {
        statusCode: 404,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'User is not a member of this flow' })
      }
    }
 
    // A newly assigned role naming a restricted entity can only be handed out by
    // someone who can reach that entity themselves (UC-ENTITY-007.2 AC-9) —
    // otherwise `roles:assign` + `entities-*:*` would let a member assign
    // themselves e.g. the "Salaries — Manager" role.
    const deniedPermission = await findUnassignableRestrictedPermission({
      assignerId: currentUserId,
      flowId,
      currentRoleIds: membership.Item.roleIds || [],
      requestedRoleIds: body.roleIds
    })
    if (deniedPermission) {
      return {
        statusCode: 403,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: `You do not have permission to grant: ${deniedPermission}` })
      }
    }
 
    // Update roles in MEMBERSHIPS_TABLE
    const result = await docClient.send(
      new UpdateCommand({
        TableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
        Key: {
          userId: targetUserId,
          flowId
        },
        UpdateExpression: 'SET roleIds = :roleIds, updatedAt = :updatedAt',
        ExpressionAttributeValues: {
          ':roleIds': body.roleIds,
          ':updatedAt': new Date().toISOString()
        },
        ReturnValues: 'ALL_NEW'
      })
    )
 
    // The member's open sessions reload their permissions right away
    await notifyPermissionsChanged([targetUserId], flowId)
 
    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify(result.Attributes)
    }
  } catch (error) {
    console.error('Error assigning roles:', error)
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({ error: 'Failed to assign roles' })
    }
  }
}
 
const RESTRICTED_PROBE = { visibility: 'restricted' }
 
/**
 * Returns the first permission of a newly added role that names a restricted
 * entity the assigner can't reach, or null. Roles the member already holds are
 * left alone, so removing an unrelated role never trips on them.
 */
async function findUnassignableRestrictedPermission({
  assignerId,
  flowId,
  currentRoleIds,
  requestedRoleIds
}) {
  const addedRoleIds = requestedRoleIds.filter((roleId) => !currentRoleIds.includes(roleId))
  if (addedRoleIds.length === 0) return null
 
  const addedRoles = await permissionChecker.batchGetRoles(addedRoleIds, flowId)
  const entityScoped = addedRoles
    .flatMap((role) => (Array.isArray(role.permissions) ? role.permissions : []))
    .filter((permission) => scopedEntityId(permission))
  if (entityScoped.length === 0) return null
 
  const { permissions: assignerPermissions = [] } = await permissionChecker.getUserPermissions(
    assignerId,
    flowId
  )
  // Only permissions the assigner couldn't grant on a restricted entity need
  // the entity's actual visibility — none at all for a `*:*` holder.
  const unreachableIfRestricted = entityScoped.filter(
    (permission) =>
      !permissionChecker.grantsOnEntity(assignerPermissions, permission, RESTRICTED_PROBE)
  )
  if (unreachableIfRestricted.length === 0) return null
 
  const visibilities = await permissionChecker.getEntitiesVisibility(
    unreachableIfRestricted.map(scopedEntityId)
  )
  return (
    unreachableIfRestricted.find(
      (permission) => visibilities.get(scopedEntityId(permission)) === 'restricted'
    ) || null
  )
}
 
exports.handler = requirePermission(assignRolesHandler, {
  permission: 'roles:assign'
})