All files / roles update.js

97.91% Statements 47/48
92% Branches 23/25
100% Functions 1/1
97.91% Lines 47/48

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 1551x 1x 1x 1x 1x   1x 1x     16x 16x 16x 16x 16x   16x 3x                     13x                   13x 1x                   12x 1x                     11x 11x 11x   11x 5x 5x 5x     11x 3x 3x 3x     11x   5x 5x   3x 3x 3x     9x 1x                     8x 8x 8x   8x                           8x                 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 { permissionChecker } = require('../utils/PermissionChecker')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
async function updateRoleHandler(event) {
  try {
    const tenantId = event.pathParameters?.tenantId
    const roleId = event.pathParameters?.roleId
    const body = JSON.parse(event.body || '{}')
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (!userId || !tenantId || !roleId) {
      return {
        statusCode: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    // Check role exists and is not a system role
    const existing = await docClient.send(
      new GetCommand({
        TableName: process.env.ROLES_TABLE_NAME,
        Key: {
          PK: `TENANT#${tenantId}`,
          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) {
      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 creatorPermissions = await permissionChecker.getUserPermissions(userId, tenantId)
      await validateRolePermissions(body.permissions, creatorPermissions)
 
      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: `TENANT#${tenantId}`,
          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'
})