All files / flows update.js

100% Statements 99/99
96.87% Branches 62/64
100% Functions 1/1
100% Lines 98/98

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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 2491x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x   1x     1x               1x 55x   55x 55x 55x 55x   55x 1x               54x             53x 1x             52x         52x 52x 1x               51x 51x 51x 51x   51x 10x             10x 1x             9x 9x 9x     50x 3x 3x     50x 2x 2x     50x 4x 4x   3x 1x   2x 2x       49x 7x 3x   4x 4x       49x 3x 2x   1x 1x           49x 29x 29x 7x           22x 14x 14x 7x                   15x 15x 15x   15x 13x 13x   2x       35x 1x             34x 34x   34x 34x 5x       34x                             33x 33x                 33x 3x       33x 8x                 33x           2x 2x              
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
const { findFlowNameConflict } = require('../utils/nameUniqueness')
const { permissionChecker } = require('../utils/PermissionChecker')
const { validateDescription } = require('../utils/validateDescription')
const { syncFlowSearchIndex } = require('../utils/directorySearchIndex')
const { validateSpace } = require('../utils/validateSpace')
const { validateJoinTargets } = require('../utils/spaceJoin')
const { PUBLIC_SPACE } = require('../utils/publicSpaces')
const { ensureHomePage } = require('../utils/spaceHome')
const { S3Client } = require('@aws-sdk/client-s3')
const { getBrandingKeys, getRemovedKeys, flowKeyGuard, deleteKeys } = require('../utils/s3Cleanup')
 
const client = new DynamoDBClient({})
const ddb = DynamoDBDocumentClient.from(client)
const s3Client = new S3Client({ region: 'eu-central-1' })
 
const FLOWS_TABLE = process.env.FLOWS_TABLE_NAME
 
// CORS headers to include in all responses
const CORS_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers':
    'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token',
  'Access-Control-Allow-Methods': 'OPTIONS,GET,PUT,POST,DELETE'
}
 
exports.handler = async (event) => {
  console.log('Update Flow Event:', JSON.stringify(event, null, 2))
 
  try {
    const flowId = event.pathParameters?.flowId
    const userId = event.requestContext.authorizer.claims.sub
    const body = JSON.parse(event.body || '{}')
 
    if (!flowId) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Flow ID is required' })
      }
    }
 
    // Fetch the flow
    const getFlowResult = await ddb.send(
      new GetCommand({
        TableName: FLOWS_TABLE,
        Key: { id: flowId }
      })
    )
 
    if (!getFlowResult.Item) {
      return {
        statusCode: 404,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Flow not found' })
      }
    }
 
    const flow = getFlowResult.Item
 
    // The flow owner is always assigned the flow's admin role (*:*) at creation
    // time and can't have it stripped, so this permission check is the only
    // authorization gate — no separate ownerId comparison is needed.
    const permissionResult = await permissionChecker.hasPermission(userId, flowId, 'flows:update')
    if (!permissionResult.hasPermission) {
      return {
        statusCode: 403,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'You do not have permission to update this flow' })
      }
    }
 
    // Build update expression
    const updateExpressions = []
    const removeExpressions = []
    const expressionAttributeNames = {}
    const expressionAttributeValues = {}
 
    if (body.name) {
      const nameConflict = await findFlowNameConflict(ddb, {
        tableName: FLOWS_TABLE,
        ownerId: flow.ownerId,
        name: body.name,
        excludeFlowId: flowId
      })
 
      if (nameConflict) {
        return {
          statusCode: 409,
          headers: CORS_HEADERS,
          body: JSON.stringify({ error: 'A flow with this name already exists' })
        }
      }
 
      updateExpressions.push('#name = :name')
      expressionAttributeNames['#name'] = 'name'
      expressionAttributeValues[':name'] = body.name
    }
 
    if (body.defaultLanguage) {
      updateExpressions.push('defaultLanguage = :defaultLanguage')
      expressionAttributeValues[':defaultLanguage'] = body.defaultLanguage
    }
 
    if (body.enabledLanguages) {
      updateExpressions.push('enabledLanguages = :enabledLanguages')
      expressionAttributeValues[':enabledLanguages'] = body.enabledLanguages
    }
 
    if (body.description !== undefined) {
      const descriptionValidation = validateDescription(body.description)
      if (!descriptionValidation.valid) return descriptionValidation.errorResponse
 
      if (body.description === null || body.description === '') {
        removeExpressions.push('description')
      } else {
        updateExpressions.push('description = :description')
        expressionAttributeValues[':description'] = body.description
      }
    }
 
    if (body.picture !== undefined) {
      if (body.picture === null || body.picture === '') {
        removeExpressions.push('picture')
      } else {
        updateExpressions.push('picture = :picture')
        expressionAttributeValues[':picture'] = body.picture
      }
    }
 
    if (body.icon !== undefined) {
      if (body.icon === null || body.icon === '') {
        removeExpressions.push('icon')
      } else {
        updateExpressions.push('icon = :icon')
        expressionAttributeValues[':icon'] = body.icon
      }
    }
 
    // The public space is replaced as a whole: the settings form always sends
    // both the published switch and the full theme.
    if (body.space !== undefined) {
      const spaceValidation = validateSpace(body.space)
      if (!spaceValidation.valid) {
        return {
          statusCode: 400,
          headers: CORS_HEADERS,
          body: JSON.stringify({ error: spaceValidation.error })
        }
      }
      if (spaceValidation.value.join) {
        const joinValidation = await validateJoinTargets(ddb, flowId, spaceValidation.value.join)
        if (!joinValidation.valid) {
          return {
            statusCode: 400,
            headers: CORS_HEADERS,
            body: JSON.stringify({
              error: joinValidation.error,
              ...(joinValidation.fieldId && { fieldId: joinValidation.fieldId })
            })
          }
        }
      }
      updateExpressions.push('#space = :space')
      expressionAttributeNames['#space'] = 'space'
      expressionAttributeValues[':space'] = spaceValidation.value
      // The sparse index of the published spaces, for the sitemap (UC-SPACE-021.1)
      if (spaceValidation.value.enabled === true) {
        updateExpressions.push('publicSpace = :publicSpace')
        expressionAttributeValues[':publicSpace'] = PUBLIC_SPACE
      } else {
        removeExpressions.push('publicSpace')
      }
    }
 
    if (updateExpressions.length === 0 && removeExpressions.length === 0) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'No fields to update' })
      }
    }
 
    updateExpressions.push('updatedAt = :updatedAt')
    expressionAttributeValues[':updatedAt'] = new Date().toISOString()
 
    let updateExpression = `SET ${updateExpressions.join(', ')}`
    if (removeExpressions.length > 0) {
      updateExpression += ` REMOVE ${removeExpressions.join(', ')}`
    }
 
    // Update the flow
    const result = await ddb.send(
      new UpdateCommand({
        TableName: FLOWS_TABLE,
        Key: { id: flowId },
        UpdateExpression: updateExpression,
        ExpressionAttributeNames:
          Object.keys(expressionAttributeNames).length > 0 ? expressionAttributeNames : undefined,
        ExpressionAttributeValues: expressionAttributeValues,
        ReturnValues: 'ALL_NEW'
      })
    )
 
    // A replaced or cleared picture/icon is now unreferenced: delete it. Only when
    // DynamoDB returned the new row, so an absent Attributes can never make the
    // current picture look "removed".
    Eif (result.Attributes) {
      await deleteKeys(
        s3Client,
        process.env.ATTACHMENTS_BUCKET_NAME,
        getRemovedKeys(getBrandingKeys(flow), getBrandingKeys(result.Attributes)),
        flowKeyGuard(flowId)
      )
    }
 
    // A space published without a home page gets one (best effort, never throws)
    if (body.space !== undefined && result.Attributes?.space?.enabled === true) {
      await ensureHomePage(ddb, result.Attributes, userId)
    }
 
    // Best-effort: keep the renamed flow searchable (admin). Never throws.
    if (body.name) {
      await syncFlowSearchIndex(
        ddb,
        process.env.FIELD_VALUE_INDEX_TABLE_NAME,
        flowId,
        flow,
        result.Attributes
      )
    }
 
    return {
      statusCode: 200,
      headers: CORS_HEADERS,
      body: JSON.stringify(result.Attributes)
    }
  } catch (error) {
    console.error('Error updating flow:', error)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Failed to update flow', details: error.message })
    }
  }
}