All files / roles update.js

98.24% Statements 56/57
90.9% Branches 30/33
100% Functions 1/1
98.24% Lines 56/57

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 1901x 1x 1x 1x 1x 1x 1x   1x 1x     23x 23x 23x 23x 23x   23x 3x                   20x 7x 7x   1x                       19x                   19x 1x                   18x 1x                     17x 17x 17x   17x 9x             9x 2x                   7x 7x 7x     15x 4x 4x 4x     15x   6x 6x   4x 4x 4x     13x 1x                     12x 12x 12x   12x                           12x                 2x     2x 2x                                         1x      
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, UpdateCommand, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { requirePermission } = require('../utils/requirePermission')
const { validateRolePermissions } = require('../utils/validateRolePermissions')
const { validatePermissionFormat } = require('../utils/permissionFormat')
const { permissionChecker } = require('../utils/PermissionChecker')
const { findRoleNameConflict } = require('../utils/nameUniqueness')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
async function updateRoleHandler(event) {
  try {
    const flowId = event.pathParameters?.flowId
    const roleId = event.pathParameters?.roleId
    const body = JSON.parse(event.body || '{}')
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (!userId || !flowId || !roleId) {
      return {
        statusCode: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    if (body.permissions && Array.isArray(body.permissions)) {
      try {
        validatePermissionFormat(body.permissions)
      } catch (error) {
        return {
          statusCode: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({ error: error.message })
        }
      }
    }
 
    // Check role exists and is not a system role
    const existing = await docClient.send(
      new GetCommand({
        TableName: process.env.ROLES_TABLE_NAME,
        Key: {
          PK: `FLOW#${flowId}`,
          SK: `ROLE#${roleId}`
        }
      })
    )
 
    if (!existing.Item) {
      return {
        statusCode: 404,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Role not found' })
      }
    }
 
    if (existing.Item.isSystemRole) {
      return {
        statusCode: 403,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Cannot modify system role' })
      }
    }
 
    // Build update expression
    const updates = []
    const expressionAttributeNames = {}
    const expressionAttributeValues = {}
 
    if (body.name) {
      const nameConflict = await findRoleNameConflict(docClient, {
        tableName: process.env.ROLES_TABLE_NAME,
        flowId,
        name: body.name,
        excludeRoleId: roleId
      })
 
      if (nameConflict) {
        return {
          statusCode: 409,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({ error: 'A role with this name already exists in this flow' })
        }
      }
 
      updates.push('#name = :name')
      expressionAttributeNames['#name'] = 'name'
      expressionAttributeValues[':name'] = body.name
    }
 
    if (body.description !== undefined) {
      updates.push('#description = :description')
      expressionAttributeNames['#description'] = 'description'
      expressionAttributeValues[':description'] = body.description
    }
 
    if (body.permissions && Array.isArray(body.permissions)) {
      // Validate that the creator has all the permissions they're trying to grant
      const creatorResult = await permissionChecker.getUserPermissions(userId, flowId)
      await validateRolePermissions(body.permissions, creatorResult.permissions || [])
 
      updates.push('#permissions = :permissions')
      expressionAttributeNames['#permissions'] = 'permissions'
      expressionAttributeValues[':permissions'] = body.permissions
    }
 
    if (updates.length === 0) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'No fields to update' })
      }
    }
 
    // Always update updatedAt
    updates.push('#updatedAt = :updatedAt')
    expressionAttributeNames['#updatedAt'] = 'updatedAt'
    expressionAttributeValues[':updatedAt'] = new Date().toISOString()
 
    const result = await docClient.send(
      new UpdateCommand({
        TableName: process.env.ROLES_TABLE_NAME,
        Key: {
          PK: `FLOW#${flowId}`,
          SK: `ROLE#${roleId}`
        },
        UpdateExpression: `SET ${updates.join(', ')}`,
        ExpressionAttributeNames: expressionAttributeNames,
        ExpressionAttributeValues: expressionAttributeValues,
        ReturnValues: 'ALL_NEW'
      })
    )
 
    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify(result.Attributes)
    }
  } catch (error) {
    console.error('Error updating role:', error)
 
    // Handle permission validation errors specifically
    Eif (error.message && error.message.includes('permission to grant')) {
      return {
        statusCode: 403,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: error.message })
      }
    }
 
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({ error: 'Internal server error' })
    }
  }
}
 
exports.handler = requirePermission(updateRoleHandler, {
  permission: 'roles:update'
})