All files / utils entityFieldCascadeValidation.js

94.33% Statements 50/53
82.97% Branches 39/47
100% Functions 14/14
100% Lines 44/44

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 1335x     4x               14x 14x 29x 29x             24x 24x 26x 2x 2x   2x 2x 4x 2x       24x         34x 34x 36x 3x 3x   6x 3x 9x 3x       34x             3x   3x 3x 2x   3x 1x                   4x 2x 1x                       1x                         130x 122x     130x 3x     3x 2x                   128x     5x              
const { GetCommand } = require('@aws-sdk/lib-dynamodb')
 
function jsonErrorResponse(body) {
  return {
    statusCode: 400,
    headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
    body: JSON.stringify(body)
  }
}
 
function extractOptionValues(options) {
  Iif (!Array.isArray(options)) return []
  return options
    .map((opt) => (typeof opt === 'string' ? opt : opt?.value))
    .filter((value) => value !== undefined && value !== null && value !== '')
}
 
// Select options that existed in `oldFields` but no longer exist in `newFields`
// (matched by fieldId). A relabeled option (same value, different label) is not
// a removal.
function findRemovedSelectOptions(oldFields, newFields) {
  const removals = []
  for (const newField of newFields) {
    if (newField.type !== 'select') continue
    const oldField = oldFields.find((f) => f.fieldId === newField.fieldId)
    Iif (!oldField || oldField.type !== 'select') continue
 
    const newValues = new Set(extractOptionValues(newField.options))
    for (const value of extractOptionValues(oldField.options)) {
      if (!newValues.has(value)) {
        removals.push({ field: newField, removedValue: value })
      }
    }
  }
  return removals
}
 
// Workflow states that existed in `oldFields` but no longer exist in `newFields`.
function findRemovedWorkflowStates(oldFields, newFields) {
  const removals = []
  for (const newField of newFields) {
    if (newField.type !== 'workflow') continue
    const oldField = oldFields.find((f) => f.fieldId === newField.fieldId)
    Iif (!oldField || oldField.type !== 'workflow' || !oldField.workflowDefinition) continue
 
    const newStateIds = new Set((newField.workflowDefinition?.states || []).map((s) => s.id))
    for (const state of oldField.workflowDefinition.states || []) {
      if (!newStateIds.has(state.id)) {
        removals.push({ field: newField, removedStateId: state.id })
      }
    }
  }
  return removals
}
 
// Every removed workflow state must come with an explicit fallback, chosen by
// the editor up front (see WorkflowEditor.vue), pointing at a state that still
// exists after the edit. This is what makes the migration safe to cascade.
function validateWorkflowStateMigrations(removals, workflowStateMigrations) {
  const migrations = Array.isArray(workflowStateMigrations) ? workflowStateMigrations : []
 
  for (const removal of removals) {
    const migration = migrations.find(
      (m) => m.fieldId === removal.field.fieldId && m.removedStateId === removal.removedStateId
    )
    if (!migration) {
      return {
        valid: false,
        errorResponse: jsonErrorResponse({
          error: 'WORKFLOW_STATE_MIGRATION_REQUIRED',
          fieldId: removal.field.fieldId,
          removedStateId: removal.removedStateId
        })
      }
    }
 
    const newStateIds = (removal.field.workflowDefinition?.states || []).map((s) => s.id)
    if (!newStateIds.includes(migration.fallbackStateId)) {
      return {
        valid: false,
        errorResponse: jsonErrorResponse({
          error: 'INVALID_WORKFLOW_FALLBACK_STATE',
          fieldId: removal.field.fieldId,
          removedStateId: removal.removedStateId,
          fallbackStateId: migration.fallbackStateId
        })
      }
    }
  }
 
  return { valid: true }
}
 
// A mandatory Item Link (entity_ref) field must always resolve to a real value
// after an onDelete cascade — that's only guaranteed for same-flow targets
// (see cascadeItemFieldValue.js). A cross-flow (public entity) target is
// resolved lazily at read time instead, so it can never be required.
async function validateMandatoryCrossFlowReferences(
  fields,
  docClient,
  entitiesTableName,
  ownFlowId
) {
  const mandatoryEntityRefFields = (fields || []).filter(
    (field) => field.type === 'entity_ref' && field.mandatory && field.reference?.entityId
  )
 
  for (const field of mandatoryEntityRefFields) {
    const targetResult = await docClient.send(
      new GetCommand({ TableName: entitiesTableName, Key: { id: field.reference.entityId } })
    )
    if (targetResult.Item && targetResult.Item.flowId !== ownFlowId) {
      return {
        valid: false,
        errorResponse: jsonErrorResponse({
          error: 'MANDATORY_CROSS_FLOW_REFERENCE_NOT_ALLOWED',
          fieldId: field.fieldId
        })
      }
    }
  }
 
  return { valid: true }
}
 
module.exports = {
  extractOptionValues,
  findRemovedSelectOptions,
  findRemovedWorkflowStates,
  validateWorkflowStateMigrations,
  validateMandatoryCrossFlowReferences
}