All files / modules/30-secrets/modals/CreateSSHCredModal/views StepAuthentication.tsx

92.5% Statements 37/40
67.78% Branches 61/90
85.71% Functions 6/7
92.5% Lines 37/40

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              233x 233x                     233x 233x 233x   233x     233x 233x 233x   233x                                         233x           4x 4x 4x 4x 4x     4x         4x 4x   4x 1x 1x 1x   1x                                     1x 1x 1x 1x 1x           4x               8x         8x                         4x                 1x 1x                                 14x                                               233x  
/*
 * Copyright 2021 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 React, { useState } from 'react'
import {
  StepProps,
  Container,
  Formik,
  FormikForm,
  Button,
  Text,
  ModalErrorHandler,
  ModalErrorHandlerBinding,
  Layout
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useParams } from 'react-router-dom'
import * as Yup from 'yup'
 
import { SecretRequestWrapper, usePostSecret, SSHAuthDTO, usePutSecret, SecretDTOV2 } from 'services/cd-ng'
import type { KerberosConfigDTO, SSHConfigDTO, SSHKeySpecDTO } from 'services/cd-ng'
import type { SecretReference } from '@secrets/components/CreateOrSelectSecret/CreateOrSelectSecret'
import SSHAuthFormFields from '@secrets/components/SSHAuthFormFields/SSHAuthFormFields'
import { buildAuthConfig } from '@secrets/utils/SSHAuthUtils'
import { useToaster } from '@common/exports'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useStrings } from 'framework/strings'
import type { SSHCredSharedObj } from '../CreateSSHCredWizard'
 
export interface SSHConfigFormData {
  authScheme: SSHAuthDTO['type']
  credentialType: SSHConfigDTO['credentialType']
  tgtGenerationMethod: KerberosConfigDTO['tgtGenerationMethod'] | 'None'
  userName: string
  port: number
  key?: SecretReference
  principal: string
  realm: string
  keyPath: string
  encryptedPassphrase?: SecretReference
  password?: SecretReference
}
 
interface StepAuthenticationProps {
  onSuccess?: (secret: SecretDTOV2) => void
}
 
const StepAuthentication: React.FC<StepProps<SSHCredSharedObj> & StepAuthenticationProps & SSHCredSharedObj> = ({
  prevStepData,
  nextStep,
  previousStep,
  onSuccess
}) => {
  const { accountId, orgIdentifier, projectIdentifier } = useParams<ProjectPathProps>()
  const [saving, setSaving] = useState(false)
  const { getString } = useStrings()
  const { showSuccess } = useToaster()
  const { mutate: createSecret } = usePostSecret({
    queryParams: { accountIdentifier: accountId, orgIdentifier, projectIdentifier }
  })
  const { mutate: editSecret } = usePutSecret({
    identifier: prevStepData?.detailsData?.identifier || '',
    queryParams: { accountIdentifier: accountId, projectIdentifier, orgIdentifier }
  })
 
  const isEdit = prevStepData?.isEdit
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding>()
 
  const handleSubmit = async (formData: SSHConfigFormData): Promise<void> => {
    setSaving(true)
    try {
      const authConfig = buildAuthConfig(formData)
      // build final data to submit
      const dataToSubmit: SecretRequestWrapper = {
        secret: {
          type: 'SSHKey',
          name: prevStepData?.detailsData?.name as string,
          identifier: prevStepData?.detailsData?.identifier as string,
          description: prevStepData?.detailsData?.description,
          tags: prevStepData?.detailsData?.tags,
          projectIdentifier,
          orgIdentifier,
          spec: {
            auth: {
              type: formData.authScheme,
              spec: authConfig
            },
            port: formData.port
          } as SSHKeySpecDTO
        }
      }
      // finally create the connector
      isEdit ? await editSecret(dataToSubmit) : await createSecret(dataToSubmit)
      setSaving(false)
      isEdit ? showSuccess(getString('ssh.editmessageSuccess')) : showSuccess(getString('ssh.createmessageSuccess'))
      onSuccess?.(dataToSubmit.secret)
      nextStep?.({ ...prevStepData, authData: formData, isEdit: true })
    } catch (err) {
      setSaving(false)
      modalErrorHandler?.show(err.data)
    }
  }
  const validationSchema = Yup.object().shape({
    port: Yup.number().required(getString('common.smtp.portRequired')),
    userName: Yup.string().when('authScheme', {
      is: 'SSH',
      then: Yup.string().trim().required(getString('secrets.createSSHCredWizard.validateUsername'))
    }),
    keyPath: Yup.string().when(['authScheme', 'credentialType', 'tgtGenerationMethod'], {
      is: (authScheme, credentialType, tgtGenerationMethod) =>
        (authScheme === 'SSH' && credentialType == 'KeyPath') ||
        (authScheme === 'Kerberos' && tgtGenerationMethod == 'KeyTabFilePath'),
      then: Yup.string().trim().required(getString('secrets.createSSHCredWizard.validateKeypath'))
    }),
    key: Yup.object().when(['authScheme', 'credentialType'], {
      is: (authScheme, credentialType) => authScheme === 'SSH' && credentialType == 'KeyReference',
      then: Yup.object().required(getString('secrets.createSSHCredWizard.validateSshKey'))
    }),
    principal: Yup.string().when('authScheme', {
      is: 'Kerberos',
      then: Yup.string().trim().required(getString('secrets.createSSHCredWizard.validatePrincipal'))
    }),
    realm: Yup.string().when('authScheme', {
      is: 'Kerberos',
      then: Yup.string().trim().required(getString('secrets.createSSHCredWizard.validateRealm'))
    })
  })
 
  return (
    <>
      <ModalErrorHandler bind={setModalErrorHandler} />
      <Container padding="small" width={400} style={{ minHeight: '500px' }}>
        <Text margin={{ bottom: 'xlarge' }} font={{ size: 'medium' }} color={Color.BLACK}>
          {getString('secrets.createSSHCredWizard.titleAuth')}
        </Text>
        <Formik<SSHConfigFormData>
          onSubmit={formData => {
            modalErrorHandler?.hide()
            handleSubmit(formData)
          }}
          formName="stepAuthenticationForm"
          validationSchema={validationSchema}
          initialValues={{
            authScheme: 'SSH',
            credentialType: 'KeyReference',
            tgtGenerationMethod: 'None',
            userName: '',
            principal: '',
            realm: '',
            keyPath: '',
            port: 22,
            ...prevStepData?.authData
          }}
        >
          {formik => {
            return (
              <FormikForm>
                <SSHAuthFormFields formik={formik} secretName={prevStepData?.detailsData?.name} />
                <Layout.Horizontal spacing="small">
                  <Button
                    text={getString('back')}
                    onClick={() => previousStep?.({ ...prevStepData, authData: formik.values })}
                  />
                  <Button
                    type="submit"
                    intent="primary"
                    text={saving ? getString('secrets.createSSHCredWizard.btnSaving') : getString('saveAndContinue')}
                    disabled={saving}
                  />
                </Layout.Horizontal>
              </FormikForm>
            )
          }}
        </Formik>
      </Container>
    </>
  )
}
 
export default StepAuthentication