All files / modules/30-secrets/components/SecretInput SecretInput.tsx

95.24% Statements 40/42
80.65% Branches 75/93
100% Functions 7/7
95.24% Lines 40/42

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              283x 283x 283x 283x                 283x 283x 283x 283x 283x         283x 283x 283x 283x 283x 283x 283x                                             283x 358x 333x                       333x 333x   333x       6x                 333x   1x       1x 1x           333x 666x       333x 162x       162x   333x   333x 333x                                 6x 6x 6x                                             1x                                                     283x  
/*
 * 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 from 'react'
import { Link, useParams } from 'react-router-dom'
import { connect, FormikContext } from 'formik'
import {
  Layout,
  Icon,
  Container,
  Text,
  DataTooltipInterface,
  FormikTooltipContext,
  HarnessDocTooltip
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { get, isPlainObject, pick } from 'lodash-es'
import { FormGroup, Intent } from '@blueprintjs/core'
import useCreateOrSelectSecretModal from '@secrets/modals/CreateOrSelectSecretModal/useCreateOrSelectSecretModal'
import useCreateUpdateSecretModal from '@secrets/modals/CreateSecretModal/useCreateUpdateSecretModal'
import type { SecretReference } from '@secrets/components/CreateOrSelectSecret/CreateOrSelectSecret'
import type { SecretIdentifiers } from '@secrets/components/CreateUpdateSecret/CreateUpdateSecret'
import type { SecretResponseWrapper, ResponsePageSecretResponseWrapper, ConnectorInfoDTO } from 'services/cd-ng'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import RbacButton from '@rbac/components/Button/Button'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { useStrings } from 'framework/strings'
import { getReference } from '@common/utils/utils'
import { getScopeFromDTO } from '@common/components/EntityReference/EntityReference'
import css from './SecretInput.module.scss'
 
export interface SecretInputProps {
  name: string
  label?: string
  placeholder?: string
  type?: Exclude<SecretResponseWrapper['secret']['type'], 'SSHKey'>
  onSuccess?: (secret: SecretReference) => void
  secretsListMockData?: ResponsePageSecretResponseWrapper
  /**
   * Used when opening Create/Select/Update Secret modal from the Create Connector modal context
   * to be added as a source_category query param to get a filtered list of secrets/connectors from the BE
   */
  connectorTypeContext?: ConnectorInfoDTO['type']
  allowSelection?: boolean
  privateSecret?: boolean
  tooltipProps?: DataTooltipInterface
}
 
interface FormikSecretInput extends SecretInputProps {
  formik: FormikContext<any>
}
 
const SecretInput: React.FC<FormikSecretInput> = props => {
  const { getString } = useStrings()
  const { accountId } = useParams<AccountPathProps>()
  const {
    formik,
    label,
    name,
    onSuccess,
    type = 'SecretText',
    secretsListMockData,
    placeholder,
    connectorTypeContext,
    allowSelection = true,
    privateSecret
  } = props
  const secretReference = get(formik.values, name)
 
  const { openCreateOrSelectSecretModal } = useCreateOrSelectSecretModal(
    {
      type,
      onSuccess: secret => {
        formik.setFieldValue(name, secret)
        /* istanbul ignore next */
        onSuccess?.(secret)
      },
      secretsListMockData,
      connectorTypeContext: connectorTypeContext
    },
    [name, onSuccess]
  )
  const { openCreateSecretModal } = useCreateUpdateSecretModal({
    onSuccess: formData => {
      const secret: SecretReference = {
        ...pick(formData, 'identifier', 'name', 'orgIdentifier', 'projectIdentifier'),
        referenceString: getReference(getScopeFromDTO(formData), formData.identifier) as string
      }
      formik.setFieldValue(name, secret)
      onSuccess?.(secret)
    },
    connectorTypeContext: connectorTypeContext,
    privateSecret: privateSecret
  })
 
  const errorCheck = (): boolean =>
    ((get(formik?.touched, name) || (formik?.submitCount && formik?.submitCount > 0)) &&
      get(formik?.errors, name) &&
      !isPlainObject(get(formik?.errors, name))) as boolean
 
  const getPlaceHolder = (): string => {
    Iif (placeholder) {
      return placeholder
    }
 
    return allowSelection ? getString('createOrSelectSecret') : getString('secrets.createSecret')
  }
  const tooltipContext = React.useContext(FormikTooltipContext)
  const dataTooltipId =
    props.tooltipProps?.dataTooltipId || (tooltipContext?.formName ? `${tooltipContext?.formName}_${name}` : '')
  return (
    <FormGroup
      helperText={errorCheck() ? get(formik?.errors, name) : null}
      intent={errorCheck() ? Intent.DANGER : Intent.NONE}
    >
      <Layout.Vertical>
        {label ? (
          <label className={'bp3-label'}>
            <HarnessDocTooltip tooltipId={dataTooltipId} labelText={label} />
          </label>
        ) : null}
        <Container flex={{ alignItems: 'center', justifyContent: 'space-between' }} className={css.container}>
          <Link
            to="#"
            className={css.containerLink}
            data-testid={name}
            onClick={e => {
              e.preventDefault()
              Eif (allowSelection) {
                openCreateOrSelectSecretModal()
              } else {
                openCreateSecretModal(type)
              }
            }}
          >
            <Icon size={24} height={12} name={'key-main'} />
            <Text
              color={Color.PRIMARY_7}
              flex={{ alignItems: 'center', justifyContent: 'flex-start', inline: false }}
              padding="small"
              className={css.containerLinkText}
            >
              <div>{secretReference ? getString('secrets.secret.configureSecret') : getPlaceHolder()}</div>
              {secretReference ? <div>{`<${secretReference['name']}>`}</div> : null}
            </Text>
          </Link>
          {secretReference ? (
            <RbacButton
              minimal
              className={css.containerEditBtn}
              data-testid={`${name}-edit`}
              onClick={() =>
                openCreateSecretModal(type, {
                  identifier: secretReference?.['identifier'],
                  projectIdentifier: secretReference?.['projectIdentifier'],
                  orgIdentifier: secretReference?.['orgIdentifier']
                } as SecretIdentifiers)
              }
              permission={{
                permission: PermissionIdentifier.UPDATE_SECRET,
                resource: {
                  resourceType: ResourceType.SECRET,
                  resourceIdentifier: secretReference?.['identifier']
                },
                resourceScope: {
                  accountIdentifier: accountId,
                  projectIdentifier: secretReference?.['projectIdentifier'],
                  orgIdentifier: secretReference?.['orgIdentifier']
                }
              }}
              text={<Icon size={16} name={'edit'} color={Color.PRIMARY_7} />}
            />
          ) : null}
        </Container>
      </Layout.Vertical>
    </FormGroup>
  )
}
 
export default connect<Omit<FormikSecretInput, 'formik'>>(SecretInput)