All files / modules/70-pipeline/components/PipelineSteps/Steps StepsValidateUtils.ts

81.68% Statements 156/191
71.49% Branches 163/228
82.35% Functions 42/51
82.87% Lines 150/181

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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569              160x     160x 160x   160x     160x             160x 160x           160x   160x 160x 160x 160x 160x 160x 160x 160x 160x 160x 160x 160x 160x 160x 160x                                                           32x       32x                                                             32x             44x 22x 20x     20x 20x 11x     20x 11x           20x     22x 22x 12x 12x 12x 34x   12x     12x 5x   11x           11x         12x   10x                                                 160x       51x               32x 31x 1x     1x                   59x   31x 28x 27x   1x 4x         28x 28x 16x             74x             74x               16x   16x     16x             16x   12x                   13x 9x 7x     7x                                   7x         4x 4x           8x             1x   1x             160x 58x 52x 3x                       49x                         160x 55x 53x                   28x 28x               4x                                                         160x           55x 614x       614x 44x     614x 55x     614x 32x     614x 32x     614x 13x     614x 55x     614x 55x     614x 50x     614x 28x   614x 51x     614x 186x     614x 4x     614x 231x 231x     231x 32x               32x   32x             614x               614x               160x             55x 55x 55x   55x 55x   55x 55x 614x   569x 569x 4x 4x 3x         565x     81x       55x     160x             23x 252x             23x     160x       165x              
/*
 * Copyright 2022 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import * as yup from 'yup'
import type { StringSchema, Lazy, ArraySchema, Schema } from 'yup'
import type { FormikErrors } from 'formik'
import { getMultiTypeFromValue, MultiTypeInputType, RUNTIME_INPUT_VALUE } from '@wings-software/uicore'
import { get, set, uniq, uniqBy, isEmpty, isUndefined } from 'lodash-es'
import type { UseStringsReturn, StringKeys } from 'framework/strings'
import { getDurationValidationSchema } from '@common/components/MultiTypeDuration/MultiTypeDuration'
import type { ExecutionWrapperConfig, StepElementConfig } from 'services/cd-ng'
import type { K8sDirectInfraYaml } from 'services/ci'
import {
  illegalIdentifiers,
  keyRegexIdentifier,
  portNumberRegex,
  regexIdentifier,
  serviceDependencyIdRegex
} from '@common/utils/StringUtils'
import { StepType } from '@pipeline/components/PipelineSteps/PipelineStepInterface'
import {
  IdentifierSchema,
  IdentifierSchemaWithoutHook,
  NameSchema,
  NameSchemaWithoutHook
} from '@common/utils/Validation'
import { StepViewType } from '@pipeline/components/AbstractSteps/Step'
 
export enum Types {
  Text,
  List,
  Map,
  Identifier,
  Name,
  OutputVariables,
  LimitMemory,
  LimitCPU,
  Timeout,
  Boolean,
  ImagePullPolicy,
  Shell,
  Numeric,
  KeyValue
}
 
interface Field {
  name: string
  type: Types | Types[]
  label?: string
  isRequired?: boolean
  isInputSet?: boolean
  isActive?: boolean
}
 
interface SchemaField {
  name: string
  validationRule: Schema<any>
  isActive?: boolean
}
 
type Dependencies = { [key: string]: any }
 
interface GenerateSchemaDependencies extends Dependencies {
  getString: UseStringsReturn['getString']
}
 
function generateSchemaForIdentifier({
  initialValues,
  steps,
  serviceDependencies,
  getString
}: GenerateSchemaDependencies): StringSchema {
  return (IdentifierSchemaWithoutHook(getString) as StringSchema).test(
    'isStepIdUnique',
    getString('validation.uniqueStepAndServiceDependenciesId'),
    identifier => {
      Eif (isEmpty(initialValues) || (isEmpty(steps) && isEmpty(serviceDependencies))) return true
 
      const stepsAndDependencies: StepElementConfig[] = [...serviceDependencies]
 
      // TODO: Add support for stepGroup
      steps.forEach(({ step, parallel }: ExecutionWrapperConfig) => {
        if (parallel) {
          // TODO: Fix typings
          ;(parallel as any).forEach(({ step: parallelStep }: { step: StepElementConfig }) => {
            stepsAndDependencies.push(parallelStep)
          })
        } else {
          stepsAndDependencies.push(step as StepElementConfig)
        }
      })
 
      const currentStepIndex = stepsAndDependencies.findIndex(step => {
        return step?.identifier === initialValues.identifier
      })
 
      return stepsAndDependencies.every((step, index: number) => {
        // Skip ID validation for the currently opened step (if it was already added)
        if (currentStepIndex === index) return true
 
        return step?.identifier !== identifier
      })
    }
  )
}
 
function generateSchemaForName({ getString }: GenerateSchemaDependencies): StringSchema {
  return NameSchemaWithoutHook(getString) as StringSchema
}
 
function generateSchemaForList(
  { label, isRequired, isInputSet }: Field,
  { getString }: GenerateSchemaDependencies
): Lazy {
  if (isInputSet) {
    return yup.lazy(value => {
      Iif (value === RUNTIME_INPUT_VALUE) {
        return yup.string()
      }
      let schema = yup.array().test('valuesShouldBeUnique', getString('validation.uniqueValues'), list => {
        if (!list) return true
        return uniq(list).length === list.length
      })
 
      if (isRequired && label) {
        schema = schema
          .ensure()
          .compact()
          .min(1, getString('fieldRequired', { field: getString(label as StringKeys) }))
      }
 
      return schema
    })
  } else {
    return yup.lazy(value => {
      if (Array.isArray(value)) {
        let schema = yup.array().test('valuesShouldBeUnique', getString('validation.uniqueValues'), list => {
          Iif (!list) return true
          const listWithoutRuntimeInput = (list as Array<{ id: string; value: string }>).filter(
            item => item?.value !== 'undefined' && item?.value !== RUNTIME_INPUT_VALUE
          )
          return uniqBy(listWithoutRuntimeInput, 'value').length === listWithoutRuntimeInput.length
        })
 
        if (Array.isArray(value) && isRequired && label) {
          schema = schema
            .ensure()
            .compact((val: any) => !val?.value)
            .min(1, getString('fieldRequired', { field: getString(label as StringKeys) }))
            .test(
              'runtimeInputNotSupported',
              getString('pipeline.runtimeInputNotSupported', { field: getString(label as StringKeys) }),
              list =>
                (list as Array<{ id: string; value: string }>).filter(item => item?.value === RUNTIME_INPUT_VALUE)
                  ?.length === 0
            )
        }
 
        return schema
      } else {
        return yup.string()
      }
    })
  }
}
 
// function generateSchemaForSelect(
//   { label, isRequired = false }: Field,
//   { getString }: GenerateSchemaDependencies
// ): StringSchema {
//   return yup.array.test(`${label} is required.`, `${label} is required.`, function (field) {
//     if (!isRequired) {
//       return true
//     }
//     const value = typeof field === 'string' ? field : field?.value
 
//     return !isUndefined(value)
//   })
//   if (!isRequired) {
//     return true
//   }
 
//   return NameSchemaWithoutHook(getString) as StringSchema
// }
 
export function generateSchemaForNumeric(
  { label: labelReference, isRequired }: Field,
  { getString }: GenerateSchemaDependencies
): Lazy {
  return yup.string().test(
    'Must be a number and allows runtimeinput or expression',
    labelReference
      ? getString?.('pipeline.stepCommonFields.validation.mustBeANumber', {
          label: labelReference && getString?.(labelReference as any)
        })
      : getString?.('common.validation.valueMustBeANumber'),
    function (runAsUser) {
      if (!isRequired && isUndefined(runAsUser)) {
        return true
      } else Iif (runAsUser.startsWith('<+')) {
        return true
      }
      return !isNaN(runAsUser)
    }
  )
}
 
function generateSchemaForMap(
  { label, isRequired, isInputSet }: Field,
  { getString }: GenerateSchemaDependencies,
  objectShape?: Schema<unknown>
): Lazy {
  if (isInputSet) {
    // We can't add validation for key uniqueness and key's value
    return yup.mixed().test('validKeys', getString('validation.validKeyRegex'), values => {
      if (!values || getMultiTypeFromValue(values as string) === MultiTypeInputType.RUNTIME) {
        return true
      }
      Eif (typeof values === 'object' && !Array.isArray(values) && values !== null) {
        return Object.keys(values).every(key => keyRegexIdentifier.test(key))
      }
      return true
    })
  } else {
    return yup.lazy(values => {
      if (Array.isArray(values)) {
        let schema = yup
          .array()
          .of(
            objectShape ??
              yup.object().shape(
                {
                  key: yup.string().when('value', {
                    is: val => val?.length,
                    then: yup
                      .string()
                      .matches(keyRegexIdentifier, getString('validation.validKeyRegex'))
                      .required(getString('validation.keyRequired'))
                  }),
                  value: yup.string().when('key', {
                    is: val => val?.length,
                    then: yup.string().required(getString('validation.valueRequired'))
                  })
                },
                [['key', 'value']]
              )
          )
          .test('keysShouldBeUnique', getString('validation.uniqueKeys'), map => {
            Iif (!map) return true
 
            return uniqBy(map, 'key').length === map.length
          })
 
        Iif (Array.isArray(values) && isRequired && label) {
          schema = schema
            .ensure()
            .compact((val: any) => !val?.value)
            .min(1, getString('fieldRequired', { field: getString(label as StringKeys) }))
        }
 
        return schema
      } else {
        return yup.string()
      }
    })
  }
}
 
function generateSchemaForOutputVariables(
  { isInputSet }: Field,
  { getString }: GenerateSchemaDependencies
): ArraySchema<any> | Lazy {
  if (isInputSet) {
    return yup.lazy(value => {
      Iif (value === RUNTIME_INPUT_VALUE) {
        return yup.string()
      }
      return yup
        .array()
        .of(
          yup.lazy(val => {
            if (
              val &&
              Object.prototype.hasOwnProperty.call(val, 'name') &&
              getMultiTypeFromValue((val as { name: string })['name']) === MultiTypeInputType.FIXED
            ) {
              return yup.object().shape({
                name: yup.string().matches(regexIdentifier, getString('validation.validOutputVariableRegex'))
              })
            } else {
              return yup.string()
            }
          })
        )
        .test('valuesShouldBeUnique', getString('validation.uniqueValues'), outputVariables => {
          Eif (!outputVariables) return true
          return uniqBy(outputVariables, 'name').length === outputVariables.length
        })
    })
  } else {
    return yup.lazy(value =>
      Array.isArray(value)
        ? yup
            .array()
            .of(
              yup.object().shape({
                value: yup.lazy(val =>
                  getMultiTypeFromValue(val as string) === MultiTypeInputType.FIXED
                    ? yup.string().matches(regexIdentifier, getString('validation.validOutputVariableRegex'))
                    : yup.string()
                )
              })
            )
            .test('valuesShouldBeUnique', getString('validation.uniqueValues'), outputVariables => {
              Iif (!outputVariables) return true
 
              return uniqBy(outputVariables, 'value').length === outputVariables.length
            })
        : yup.string()
    )
  }
}
 
export function generateSchemaForLimitMemory({ getString, isRequired = false }: GenerateSchemaDependencies): Lazy {
  return yup.lazy(value => {
    if (isRequired) {
      return getMultiTypeFromValue(value as string) === MultiTypeInputType.FIXED
        ? yup
            .string()
            .required()
            // ^$ in the end is to pass empty string because otherwise it will fail
            // .matches(/^\d+$|^\d+(E|P|T|G|M|K|Ei|Pi|Ti|Gi|Mi|Ki)$|^$/, getString('pipeline.stepCommonFields.validation.invalidLimitMemory'))
            .matches(
              /^\d+(\.\d+)?$|^\d+(\.\d+)?(G|M|Gi|Mi)$|^$/,
              getString('pipeline.stepCommonFields.validation.invalidLimitMemory')
            )
        : yup.string().required()
    }
    return getMultiTypeFromValue(value as string) === MultiTypeInputType.FIXED
      ? yup
          .string()
          // ^$ in the end is to pass empty string because otherwise it will fail
          // .matches(/^\d+$|^\d+(E|P|T|G|M|K|Ei|Pi|Ti|Gi|Mi|Ki)$|^$/, getString('pipeline.stepCommonFields.validation.invalidLimitMemory'))
          .matches(
            /^\d+(\.\d+)?$|^\d+(\.\d+)?(G|M|Gi|Mi)$|^$/,
            getString('pipeline.stepCommonFields.validation.invalidLimitMemory')
          )
      : yup.string()
  })
}
 
export function generateSchemaForLimitCPU({ getString }: GenerateSchemaDependencies): Lazy {
  return yup.lazy(value =>
    getMultiTypeFromValue(value as string) === MultiTypeInputType.FIXED
      ? // ^$ in the end is to pass empty string because otherwise it will fail
        yup
          .string()
          .matches(/^\d+(\.\d+)?$|^\d+m$|^$/, getString('pipeline.stepCommonFields.validation.invalidLimitCPU'))
      : yup.string()
  )
}
 
function generateSchemaForBoolean(): Lazy {
  return yup.lazy(value =>
    getMultiTypeFromValue(value as boolean) === MultiTypeInputType.FIXED ? yup.bool() : yup.string()
  )
}
 
function generateSchemaForKeyValue(
  { label, isRequired, isInputSet }: Field,
  { getString }: GenerateSchemaDependencies
): Lazy {
  return generateSchemaForMap(
    { label, isRequired, isInputSet } as Field,
    { getString },
    yup.object().shape(
      {
        key: yup.string().when('value', {
          is: val => val?.length,
          then: yup
            .string()
            .required(getString('validation.keyRequired'))
            .matches(portNumberRegex, getString('pipeline.ci.validations.port'))
        }),
        value: yup.string().when('key', {
          is: val => val?.length,
          then: yup.string().when('value', (value: string) => {
            if (!value) {
              return yup.string().required(getString('validation.valueRequired'))
            }
            if (value !== RUNTIME_INPUT_VALUE) {
              return yup.string().matches(portNumberRegex, getString('pipeline.ci.validations.port'))
            }
          })
        })
      },
      [['key', 'value']]
    )
  )
}
 
export function generateSchemaFields(
  fields: Field[],
  { initialValues, steps, serviceDependencies, getString }: GenerateSchemaDependencies,
  stepViewType: StepViewType,
  buildInfrastructureType?: K8sDirectInfraYaml['type']
): SchemaField[] {
  return fields.map(field => {
    const { name, type, label, isRequired, isActive } = field
 
    let validationRule
 
    if (type === Types.List) {
      validationRule = generateSchemaForList(field, { getString })
    }
 
    if (type === Types.Map) {
      validationRule = generateSchemaForMap(field, { getString })
    }
 
    if (stepViewType !== StepViewType.Template && type === Types.Identifier) {
      validationRule = generateSchemaForIdentifier({ initialValues, steps, serviceDependencies, getString })
    }
 
    if (stepViewType !== StepViewType.Template && type === Types.Name) {
      validationRule = generateSchemaForName({ getString })
    }
 
    if (type === Types.OutputVariables) {
      validationRule = generateSchemaForOutputVariables(field, { getString })
    }
 
    if (type === Types.LimitMemory) {
      validationRule = generateSchemaForLimitMemory({ getString })
    }
 
    if (type === Types.LimitCPU) {
      validationRule = generateSchemaForLimitCPU({ getString })
    }
 
    if (type === Types.Timeout) {
      validationRule = getDurationValidationSchema({ minimum: '10s' })
    }
 
    if (type === Types.Boolean) {
      validationRule = generateSchemaForBoolean()
    }
    if (type === Types.Numeric) {
      validationRule = generateSchemaForNumeric(field, { getString })
    }
 
    if (type === Types.Text) {
      validationRule = yup.string()
    }
 
    if (type === Types.KeyValue) {
      validationRule = generateSchemaForKeyValue(field, { getString })
    }
 
    if ((type === Types.Identifier || type === Types.Name || type === Types.Text) && isRequired && label) {
      Eif (validationRule) {
        validationRule = (validationRule as any).required(
          getString('fieldRequired', { field: getString(label as StringKeys) })
        )
        if (type === Types.Identifier) {
          Iif (buildInfrastructureType === 'VM') {
            validationRule = validationRule.matches(
              serviceDependencyIdRegex,
              getString('pipeline.ci.validations.serviceDependencyIdentifier', {
                regex: serviceDependencyIdRegex.source
              })
            )
          } else {
            validationRule = validationRule.matches(regexIdentifier, getString('validation.validIdRegex'))
          }
          validationRule = validationRule.notOneOf(illegalIdentifiers)
        }
      } else if (stepViewType !== StepViewType.Template && type !== Types.Identifier && type !== Types.Name) {
        validationRule = yup.string().required(getString('fieldRequired', { field: getString(label as StringKeys) }))
      }
    }
 
    Iif (type === Types.Boolean && isRequired && label) {
      validationRule = (validationRule as any).required(
        getString('fieldRequired', {
          field: getString(label as StringKeys)
        })
      )
    }
 
    return {
      name,
      validationRule,
      isActive
    }
  })
}
 
export function validate(
  values: any,
  config: Field[],
  dependencies: GenerateSchemaDependencies,
  stepViewType: StepViewType,
  buildInfrastructureType?: K8sDirectInfraYaml['type']
): FormikErrors<any> {
  const errors = {}
  Eif (isEmpty(dependencies.steps)) {
    dependencies.steps = []
  }
  Eif (isEmpty(dependencies.serviceDependencies)) {
    dependencies.serviceDependencies = []
  }
  const schemaFields = generateSchemaFields(config, dependencies, stepViewType, buildInfrastructureType)
  schemaFields.forEach(({ name, validationRule, isActive = true }) => {
    if (!isActive) return
 
    try {
      if (dependencies.type === StepType.Dependency && name === 'spec.limitMemory') {
        const cpuVal = get(values, 'spec.limitCPU')
        if (cpuVal) {
          generateSchemaForLimitMemory({ getString: dependencies.getString, isRequired: true }).validateSync(
            get(values, name)
          )
        }
      } else {
        validationRule?.validateSync(get(values, name))
      }
    } catch (error) {
      set(errors, name, error.message)
    }
  })
 
  return errors
}
 
export function validateInputSet(
  values: any,
  template: any,
  config: Field[],
  dependencies: GenerateSchemaDependencies,
  stepViewType: StepViewType
): FormikErrors<any> {
  const configWithActiveState = config.map(field => {
    return {
      ...field,
      isInputSet: true,
      isActive: !!get(template, field.name)
    }
  })
 
  return validate(values, configWithActiveState, dependencies, stepViewType)
}
 
export function getNameAndIdentifierSchema(
  getString: UseStringsReturn['getString'],
  stepViewType?: StepViewType
): { [key: string]: yup.Schema<string | undefined> } {
  return stepViewType !== StepViewType.Template
    ? {
        name: NameSchema({ requiredErrorMsg: getString('pipelineSteps.stepNameRequired') }),
        identifier: IdentifierSchema()
      }
    : {}
}