All files / entities update.js

92.04% Statements 81/88
88.67% Branches 47/53
50% Functions 1/2
92.04% Lines 81/88

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 2321x 1x 1x 1x   1x 1x   1x 33x 33x 33x 32x   32x 1x                   31x 1x                     30x 3x                         27x             26x 1x                     25x 1x                     24x 24x 24x   24x 6x 6x 6x     24x 2x 2x 2x     24x 3x 3x 3x     24x 5x 5x 1x                     4x 4x 4x     23x       2x 2x 2x     23x 3x   2x 2x   1x 1x 1x       23x 3x   2x 2x   1x 1x 1x       23x                       23x 1x 1x 1x     23x 1x 1x 1x     23x 1x                   22x 22x 22x   22x                     22x                 2x 2x                       1x      
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
const { requirePermission } = require('../utils/requirePermission')
const { RESERVED_ENTITY_IDS } = require('../utils/constants')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const updateEntityHandler = async (event) => {
  try {
    const id = event.pathParameters?.entityId
    const body = JSON.parse(event.body || '{}')
    const tenantId = event.requestContext?.authorizer?.claims?.['custom:tenantId']
 
    if (!tenantId) {
      return {
        statusCode: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Missing tenant context' })
      }
    }
 
    if (!id) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Missing id' })
      }
    }
 
    // Prevent modification of system entities
    if (RESERVED_ENTITY_IDS.includes(id)) {
      return {
        statusCode: 403,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          error: `Cannot modify system entity "${id}". System entities are read-only.`
        })
      }
    }
 
    // Verify entity exists and ownership
    const result = await docClient.send(
      new GetCommand({
        TableName: process.env.TABLE_NAME,
        Key: { id }
      })
    )
 
    if (!result.Item) {
      return {
        statusCode: 404,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Entity not found' })
      }
    }
 
    // Only owner tenant can update
    if (result.Item.tenantId !== tenantId) {
      return {
        statusCode: 403,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Access denied - only owner can update' })
      }
    }
 
    // Build update expression
    const updateExpressions = []
    const expressionAttributeNames = {}
    const expressionAttributeValues = {}
 
    if (body.name !== undefined) {
      updateExpressions.push('#name = :name')
      expressionAttributeNames['#name'] = 'name'
      expressionAttributeValues[':name'] = body.name
    }
 
    if (body.fields !== undefined) {
      updateExpressions.push('#fields = :fields')
      expressionAttributeNames['#fields'] = 'fields'
      expressionAttributeValues[':fields'] = body.fields
    }
 
    if (body.isPublic !== undefined) {
      updateExpressions.push('#isPublic = :isPublic')
      expressionAttributeNames['#isPublic'] = 'isPublic'
      expressionAttributeValues[':isPublic'] = body.isPublic === true ? 'true' : 'false'
    }
 
    if (body.visibility !== undefined) {
      const validVisibilityLevels = ['flow-members', 'restricted', 'public']
      if (!validVisibilityLevels.includes(body.visibility)) {
        return {
          statusCode: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({
            error: `Invalid visibility level. Must be one of: ${validVisibilityLevels.join(', ')}`
          })
        }
      }
      updateExpressions.push('#visibility = :visibility')
      expressionAttributeNames['#visibility'] = 'visibility'
      expressionAttributeValues[':visibility'] = body.visibility
    }
 
    if (
      body.publicPermissions !== undefined &&
      (body.visibility === 'public' || result.Item.visibility === 'public')
    ) {
      updateExpressions.push('#publicPermissions = :publicPermissions')
      expressionAttributeNames['#publicPermissions'] = 'publicPermissions'
      expressionAttributeValues[':publicPermissions'] = body.publicPermissions
    }
 
    if (body.picture !== undefined) {
      if (body.picture === null || body.picture === '') {
        // Remove picture
        updateExpressions.push('REMOVE #picture')
        expressionAttributeNames['#picture'] = 'picture'
      } else {
        updateExpressions.push('#picture = :picture')
        expressionAttributeNames['#picture'] = 'picture'
        expressionAttributeValues[':picture'] = body.picture
      }
    }
 
    if (body.icon !== undefined) {
      if (body.icon === null || body.icon === '') {
        // Remove icon
        updateExpressions.push('REMOVE #icon')
        expressionAttributeNames['#icon'] = 'icon'
      } else {
        updateExpressions.push('#icon = :icon')
        expressionAttributeNames['#icon'] = 'icon'
        expressionAttributeValues[':icon'] = body.icon
      }
    }
 
    Iif (body.description !== undefined) {
      if (body.description === null || body.description === '') {
        // Remove description
        updateExpressions.push('REMOVE #description')
        expressionAttributeNames['#description'] = 'description'
      } else {
        updateExpressions.push('#description = :description')
        expressionAttributeNames['#description'] = 'description'
        expressionAttributeValues[':description'] = body.description
      }
    }
 
    if (body.defaultLanguage !== undefined) {
      updateExpressions.push('#defaultLanguage = :defaultLanguage')
      expressionAttributeNames['#defaultLanguage'] = 'defaultLanguage'
      expressionAttributeValues[':defaultLanguage'] = body.defaultLanguage
    }
 
    if (body.enabledLanguages !== undefined) {
      updateExpressions.push('#enabledLanguages = :enabledLanguages')
      expressionAttributeNames['#enabledLanguages'] = 'enabledLanguages'
      expressionAttributeValues[':enabledLanguages'] = body.enabledLanguages
    }
 
    if (updateExpressions.length === 0) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'No fields to update' })
      }
    }
 
    updateExpressions.push('#updatedAt = :updatedAt')
    expressionAttributeNames['#updatedAt'] = 'updatedAt'
    expressionAttributeValues[':updatedAt'] = new Date().toISOString()
 
    const updateResult = await docClient.send(
      new UpdateCommand({
        TableName: process.env.TABLE_NAME,
        Key: { id },
        UpdateExpression: 'SET ' + updateExpressions.join(', '),
        ExpressionAttributeNames: expressionAttributeNames,
        ExpressionAttributeValues: expressionAttributeValues,
        ReturnValues: 'ALL_NEW'
      })
    )
 
    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify(updateResult.Attributes)
    }
  } catch (error) {
    console.error('Error:', error)
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({ error: 'Failed to update entity' })
    }
  }
}
 
// Wrap with permission check: require 'entity-{id}:update' permission
exports.handler = requirePermission(updateEntityHandler, {
  permission: (event) => `entity-${event.pathParameters?.entityId}:update`
})