All files / modules/35-connectors/components/CreateConnector/HashiCorpVault/views SetupEngine.tsx

84.62% Statements 55/65
42.06% Branches 45/107
66.67% Functions 8/12
84.62% Lines 55/65

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              220x 220x 220x                               220x 220x 220x           220x 220x 220x                           220x 220x   220x             220x                 8x 8x 8x 8x 8x 8x 8x 8x   8x 8x     8x       8x                     8x 2x 1x 1x 1x         8x                                                                                                               8x 3x                     8x 3x                               8x 2x 2x 2x   2x 2x 2x 1x 1x 1x 1x   1x 1x 1x 1x           2x         8x                                                         2x       11x                                                                                                                   220x  
/*
 * Copyright 2022 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Free Trial 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/05/PolyForm-Free-Trial-1.0.0.txt.
 */
 
import React, { useState, useEffect } from 'react'
import * as Yup from 'yup'
import {
  Container,
  Text,
  Formik,
  FormikForm,
  Button,
  Layout,
  FormInput,
  StepProps,
  SelectOption,
  ModalErrorHandler,
  ModalErrorHandlerBinding,
  ButtonVariation,
  shouldShowError
} from '@wings-software/uicore'
import type { IOptionProps } from '@blueprintjs/core'
import { FontVariation, Color } from '@harness/design-system'
import { useStrings } from 'framework/strings'
import {
  StepDetailsProps,
  ConnectorDetailsProps,
  SetupEngineFormData,
  HashiCorpVaultAccessTypes
} from '@connectors/interfaces/ConnectorInterface'
import { setupEngineFormData, buildVaultPayload } from '@connectors/pages/connectors/utils/ConnectorUtils'
import { PageSpinner } from '@common/components'
import {
  useGetMetadata,
  VaultMetadataRequestSpecDTO,
  VaultAppRoleCredentialDTO,
  VaultAuthTokenCredentialDTO,
  VaultMetadataSpecDTO,
  useCreateConnector,
  useUpdateConnector,
  ConnectorRequestBody,
  ConnectorConfigDTO,
  VaultAwsIamRoleCredentialDTO,
  VaultAgentCredentialDTO,
  VaultK8sCredentialDTO
} from 'services/cd-ng'
import { useToaster } from '@common/exports'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
 
const defaultInitialFormData: SetupEngineFormData = {
  secretEngine: '',
  engineType: 'fetch',
  secretEngineName: '',
  secretEngineVersion: 2
}
 
const SetupEngine: React.FC<StepProps<StepDetailsProps> & ConnectorDetailsProps> = ({
  prevStepData,
  previousStep,
  nextStep,
  onConnectorCreated,
  isEditMode,
  connectorInfo,
  accountId
}) => {
  const { getString } = useStrings()
  const { getRBACErrorMessage } = useRBACError()
  const { showSuccess, showError } = useToaster()
  const [initialValues, setInitialValues] = useState(defaultInitialFormData)
  const [loadingFormData, setLoadingFormData] = useState(isEditMode)
  const [savingDataInProgress, setSavingDataInProgress] = useState<boolean>(false)
  const [secretEngineOptions, setSecretEngineOptions] = useState<SelectOption[]>([])
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding | undefined>()
 
  const { mutate: getMetadata, loading } = useGetMetadata({ queryParams: { accountIdentifier: accountId } })
  const { mutate: createConnector, loading: creating } = useCreateConnector({
    queryParams: { accountIdentifier: accountId }
  })
  const { mutate: updateConnector, loading: updating } = useUpdateConnector({
    queryParams: { accountIdentifier: accountId }
  })
 
  const engineTypeOptions: IOptionProps[] = [
    {
      label: getString('connectors.hashiCorpVault.fetchEngines'),
      value: 'fetch'
    },
    {
      label: getString('connectors.hashiCorpVault.manuallyConfigureEngine'),
      value: 'manual'
    }
  ]
 
  useEffect(() => {
    if (isEditMode && connectorInfo) {
      setupEngineFormData(connectorInfo).then(data => {
        setInitialValues(data as SetupEngineFormData)
        setLoadingFormData(false)
      })
    }
  }, [isEditMode, connectorInfo, accountId])
 
  const handleFetchEngines = async (formData: ConnectorConfigDTO): Promise<void> => {
    try {
      const res = await getMetadata({
        identifier: formData.identifier,
        encryptionType: 'VAULT',
        orgIdentifier: formData.orgIdentifier,
        projectIdentifier: formData.projectIdentifier,
        spec: {
          url: formData.vaultUrl,
          accessType: formData.accessType,
          delegateSelectors: formData.delegateSelectors,
          namespace: formData.namespace,
          spec:
            formData.accessType === HashiCorpVaultAccessTypes.APP_ROLE
              ? ({
                  appRoleId: formData.appRoleId,
                  secretId: formData.secretId?.referenceString
                } as VaultAppRoleCredentialDTO)
              : formData.accessType === HashiCorpVaultAccessTypes.AWS_IAM
              ? ({
                  awsRegion: formData.awsRegion,
                  vaultAwsIamRole: formData.vaultAwsIamRole,
                  xvaultAwsIamServerId: formData.xvaultAwsIamServerId?.referenceString
                } as VaultAwsIamRoleCredentialDTO)
              : formData.accessType === HashiCorpVaultAccessTypes.TOKEN
              ? ({
                  authToken: formData.authToken?.referenceString
                } as VaultAuthTokenCredentialDTO)
              : formData.accessType === HashiCorpVaultAccessTypes.K8s_AUTH
              ? ({
                  vaultK8sAuthRole: formData.vaultK8sAuthRole,
                  serviceAccountTokenPath: formData.serviceAccountTokenPath
                } as VaultK8sCredentialDTO)
              : ({
                  sinkPath: formData.sinkPath
                } as VaultAgentCredentialDTO)
        } as VaultMetadataRequestSpecDTO
      })
 
      setSecretEngineOptions(
        (res.data?.spec as VaultMetadataSpecDTO)?.secretEngines?.map(secretEngine => {
          return {
            label: secretEngine.name || '',
            value: `${secretEngine.name || ''}@@@${secretEngine.version || 2}`
          }
        }) || []
      )
    } catch (err) {
      /* istanbul ignore else */
      //added condition to don't show the toaster if it's an abort error
      Iif (shouldShowError(err)) {
        showError(getRBACErrorMessage(err))
      }
    }
  }
 
  useEffect(() => {
    Iif (
      isEditMode &&
      !loadingFormData &&
      prevStepData &&
      connectorInfo &&
      !connectorInfo.spec.secretEngineManuallyConfigured
    ) {
      handleFetchEngines(prevStepData as ConnectorConfigDTO)
    }
  }, [isEditMode, loadingFormData, prevStepData, connectorInfo])
 
  useEffect(() => {
    Iif (
      isEditMode &&
      !loadingFormData &&
      loading &&
      connectorInfo &&
      !connectorInfo.spec.secretEngineManuallyConfigured
    ) {
      setSecretEngineOptions([
        {
          label: connectorInfo.spec.secretEngineName || '',
          value: `${connectorInfo.spec.secretEngineName || ''}@@@${connectorInfo.spec.secretEngineVersion || 2}`
        }
      ])
    }
  }, [isEditMode, loadingFormData, loading, connectorInfo])
 
  const handleCreateOrEdit = async (formData: SetupEngineFormData): Promise<void> => {
    modalErrorHandler?.hide()
    Eif (prevStepData) {
      const data: ConnectorRequestBody = buildVaultPayload({ ...prevStepData, ...formData })
 
      try {
        setSavingDataInProgress(true)
        if (isEditMode) {
          const response = await updateConnector(data)
          nextStep?.({ ...prevStepData, ...formData })
          onConnectorCreated?.(response.data)
          showSuccess(getString('connectors.updatedSuccessfully'))
        } else {
          const response = await createConnector(data)
          nextStep?.({ ...prevStepData, ...formData })
          onConnectorCreated?.(response.data)
          showSuccess(getString('connectors.createdSuccessfully'))
        }
      } catch (err) {
        /* istanbul ignore next */
        modalErrorHandler?.showDanger(err?.data?.message)
      } finally {
        setSavingDataInProgress(false)
      }
    }
  }
 
  return loadingFormData || savingDataInProgress ? (
    <PageSpinner message={savingDataInProgress ? getString('connectors.hashiCorpVault.saveInProgress') : undefined} />
  ) : (
    <Container padding={{ top: 'medium' }} width="64%">
      <Text font={{ variation: FontVariation.H3 }} padding={{ bottom: 'xlarge' }} color={Color.BLACK}>
        {getString('connectors.hashiCorpVault.setupEngine')}
      </Text>
      <ModalErrorHandler bind={setModalErrorHandler} />
      <Formik<SetupEngineFormData>
        enableReinitialize
        initialValues={initialValues}
        formName="vaultConfigForm"
        validationSchema={Yup.object().shape({
          secretEngineName: Yup.string().when('engineType', {
            is: 'manual',
            then: Yup.string().trim().required(getString('validation.secretEngineName'))
          }),
          secretEngineVersion: Yup.number().when('engineType', {
            is: 'manual',
            then: Yup.number()
              .positive(getString('validation.engineVersionNumber'))
              .required(getString('validation.engineVersion'))
          }),
          secretEngine: Yup.string().when('engineType', {
            is: 'fetch',
            then: Yup.string().trim().required(getString('validation.secretEngine'))
          })
        })}
        onSubmit={formData => {
          handleCreateOrEdit(formData)
        }}
      >
        {formik => {
          return (
            <FormikForm>
              <Container height={490}>
                <FormInput.RadioGroup
                  name="engineType"
                  label={getString('connectors.hashiCorpVault.secretEngine')}
                  radioGroup={{ inline: true }}
                  items={engineTypeOptions}
                />
                {formik.values['engineType'] === 'fetch' ? (
                  <Layout.Horizontal spacing="medium">
                    <FormInput.Select
                      name="secretEngine"
                      items={secretEngineOptions}
                      disabled={secretEngineOptions.length === 0 || loading}
                    />
                    <Button
                      intent="primary"
                      text={getString('connectors.hashiCorpVault.fetchEngines')}
                      onClick={() => handleFetchEngines(prevStepData as ConnectorConfigDTO)}
                      disabled={loading}
                      loading={loading}
                    />
                  </Layout.Horizontal>
                ) : null}
                {formik.values['engineType'] === 'manual' ? (
                  <Layout.Horizontal spacing="medium">
                    <FormInput.Text name="secretEngineName" label={getString('connectors.hashiCorpVault.engineName')} />
                    <FormInput.Text
                      name="secretEngineVersion"
                      label={getString('connectors.hashiCorpVault.engineVersion')}
                    />
                  </Layout.Horizontal>
                ) : null}
              </Container>
              <Layout.Horizontal spacing="medium">
                <Button
                  variation={ButtonVariation.SECONDARY}
                  icon="chevron-left"
                  text={getString('back')}
                  onClick={() => previousStep?.(prevStepData)}
                />
                <Button
                  type="submit"
                  intent="primary"
                  rightIcon="chevron-right"
                  text={getString('saveAndContinue')}
                  disabled={creating || updating}
                />
              </Layout.Horizontal>
            </FormikForm>
          )
        }}
      </Formik>
    </Container>
  )
}
 
export default SetupEngine