All files / modules/35-connectors/components/CreateConnector/K8sConnector/StepAuth Stepk8ClusterDetails.tsx

98.39% Statements 61/62
78.18% Branches 43/55
100% Functions 23/23
98.39% Lines 61/62

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              220x                         220x 220x 220x     220x 220x           220x 220x 220x 220x 220x                                                                             220x                                                 220x 220x 220x     220x                     220x 35x   33x   14x                     4x             6x                                                                 8x                                 16x                                     1x       220x 34x 32x   32x                     32x                                     32x           48x             48x           48x       48x         48x         48x             48x       48x         48x         48x           48x             48x         32x 32x   32x 22x 10x 10x 10x 10x 10x                 32x 4x     32x                                         39x     78x       1x 1x                                                                                     1x                                     220x  
/*
 * 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 {
  StepProps,
  Layout,
  Text,
  Container,
  FormInput,
  Formik,
  Button,
  SelectOption,
  ButtonVariation,
  PageSpinner,
  ThumbnailSelect
} from '@wings-software/uicore'
import React, { useState, useEffect } from 'react'
import * as Yup from 'yup'
import { FontVariation, Color } from '@harness/design-system'
import type { FormikProps } from 'formik'
import type { ConnectorInfoDTO, ConnectorRequestBody, ConnectorConfigDTO } from 'services/cd-ng'
import SecretInput from '@secrets/components/SecretInput/SecretInput'
import {
  DelegateTypes,
  setupKubFormData,
  DelegateCardInterface
} from '@connectors/pages/connectors/utils/ConnectorUtils'
import type { SecretReferenceInterface } from '@secrets/utils/SecretField'
import { useStrings } from 'framework/strings'
import { AuthTypes } from '@connectors/pages/connectors/utils/ConnectorHelper'
import TextReference, { ValueType, TextReferenceInterface } from '@secrets/components/TextReference/TextReference'
import commonStyles from '@connectors/components/CreateConnector/commonSteps/ConnectorCommonStyles.module.scss'
import css from './Stepk8ClusterDetails.module.scss'
 
interface Stepk8ClusterDetailsProps extends ConnectorInfoDTO {
  name: string
}
 
interface K8ClusterDetailsProps {
  onConnectorCreated: (data?: ConnectorRequestBody) => void | Promise<void>
  hideModal: () => void
  isEditMode: boolean
  setIsEditMode: (val: boolean) => void
  setFormData?: (formData: ConnectorConfigDTO) => void
  connectorInfo: ConnectorInfoDTO | void
  accountId: string
  orgIdentifier: string
  projectIdentifier: string
}
 
interface KubeFormInterface {
  delegateType?: string
  authType: string
  username: TextReferenceInterface | void
  password: SecretReferenceInterface | void
  serviceAccountToken: SecretReferenceInterface | void
  oidcIssuerUrl: string
  oidcUsername: TextReferenceInterface | void
  oidcPassword: SecretReferenceInterface | void
  oidcCleintId: SecretReferenceInterface | void
  oidcCleintSecret: SecretReferenceInterface | void
  oidcScopes: string
  clientKey: SecretReferenceInterface | void
  clientKeyPassphrase: SecretReferenceInterface | void
  clientKeyCertificate: SecretReferenceInterface | void
  clientKeyAlgo: string
  clientKeyCACertificate: SecretReferenceInterface | void
  delegateSelectors: Array<string>
  skipDefaultValidation: boolean
}
 
const defaultInitialFormData: KubeFormInterface = {
  authType: AuthTypes.USER_PASSWORD,
  username: undefined,
  password: undefined,
  serviceAccountToken: undefined,
  oidcIssuerUrl: '',
  oidcUsername: undefined,
  oidcPassword: undefined,
  oidcCleintId: undefined,
  oidcCleintSecret: undefined,
  oidcScopes: '',
  clientKey: undefined,
  clientKeyCertificate: undefined,
  clientKeyPassphrase: undefined,
  clientKeyAlgo: '',
  clientKeyCACertificate: undefined,
  delegateSelectors: [],
  skipDefaultValidation: false
}
 
interface AuthOptionInterface {
  label: string
  value: string
}
 
enum CLIENT_KEY_ALGO {
  RSA = 'RSA',
  EC = 'EC'
}
 
const CLIENT_KEY_ALGO_OPTIONS: SelectOption[] = [
  {
    label: CLIENT_KEY_ALGO.RSA,
    value: CLIENT_KEY_ALGO.RSA
  },
  {
    label: CLIENT_KEY_ALGO.EC,
    value: CLIENT_KEY_ALGO.EC
  }
]
 
const RenderK8AuthForm: React.FC<FormikProps<KubeFormInterface> & { isEditMode: boolean }> = props => {
  const { getString } = useStrings()
 
  switch (props.values.authType) {
    case AuthTypes.USER_PASSWORD:
      return (
        <Container width={'42%'}>
          <TextReference
            name="username"
            stringId="username"
            type={props.values.username ? props.values.username?.type : ValueType.TEXT}
          />
          <SecretInput name={'password'} label={getString('password')} />
        </Container>
      )
    case AuthTypes.SERVICE_ACCOUNT:
      return (
        <Container className={css.formFieldWidth}>
          <SecretInput name={'serviceAccountToken'} label={getString('connectors.k8.serviceAccountToken')} />
          <SecretInput name={'clientKeyCACertificate'} label={getString('connectors.k8.clientKeyCACertificate')} />
        </Container>
      )
    case AuthTypes.OIDC:
      return (
        <>
          <FormInput.Text
            name="oidcIssuerUrl"
            label={getString('connectors.k8.OIDCIssuerUrl')}
            className={css.formFieldWidth}
          />
          <Container flex={{ justifyContent: 'flex-start' }}>
            <Container width={'42%'}>
              <TextReference
                name="oidcUsername"
                stringId="connectors.k8.OIDCUsername"
                type={props.values.oidcUsername ? props.values.oidcUsername.type : ValueType.TEXT}
              />
 
              <SecretInput name={'oidcPassword'} label={getString('connectors.k8.OIDCPassword')} />
            </Container>
 
            <Container width={'42%'} margin={{ top: 'medium', left: 'xxlarge' }}>
              <SecretInput name={'oidcCleintId'} label={getString('connectors.k8.OIDCClientId')} />
              <SecretInput name={'oidcCleintSecret'} label={getString('connectors.k8.clientSecretOptional')} />
            </Container>
          </Container>
 
          <FormInput.Text
            name="oidcScopes"
            label={getString('connectors.k8.OIDCScopes')}
            className={css.formFieldWidth}
          />
        </>
      )
 
    case AuthTypes.CLIENT_KEY_CERT:
      return (
        <>
          <Container flex={{ justifyContent: 'flex-start' }}>
            <Container className={css.formFieldWidth}>
              <SecretInput name={'clientKey'} label={getString('connectors.k8.clientKey')} />
              <SecretInput name={'clientKeyCertificate'} label={getString('connectors.k8.clientCertificate')} />
            </Container>
 
            <Container className={css.formFieldWidth} margin={{ left: 'xxlarge' }}>
              <SecretInput name={'clientKeyPassphrase'} label={getString('connectors.k8.clientKeyPassphrase')} />
              <FormInput.Select
                items={CLIENT_KEY_ALGO_OPTIONS}
                name="clientKeyAlgo"
                label={getString('connectors.k8.clientKeyAlgorithm')}
                value={
                  // If we pass the value as undefined, formik will kick in and value will be updated as per uicore logic
                  // If we've added a custom value, then just add it as a label value pair
                  CLIENT_KEY_ALGO_OPTIONS.find(opt => opt.value === props.values.clientKeyAlgo)
                    ? undefined
                    : { label: props.values.clientKeyAlgo, value: props.values.clientKeyAlgo }
                }
                selectProps={{
                  allowCreatingNewItems: true,
                  inputProps: {
                    placeholder: getString('connectors.k8.clientKeyAlgorithmPlaceholder')
                  }
                }}
              />
            </Container>
          </Container>
          <Container className={css.formFieldWidth}>
            <SecretInput name={'clientKeyCACertificate'} label={getString('connectors.k8.clientKeyCACertificate')} />
          </Container>
        </>
      )
    default:
      return null
  }
}
 
const Stepk8ClusterDetails: React.FC<StepProps<Stepk8ClusterDetailsProps> & K8ClusterDetailsProps> = props => {
  const { accountId, prevStepData, nextStep } = props
  const { getString } = useStrings()
 
  const DelegateCards: DelegateCardInterface[] = [
    {
      type: DelegateTypes.DELEGATE_OUT_CLUSTER,
      info: getString('connectors.k8.delegateOutClusterInfo')
    },
    {
      type: DelegateTypes.DELEGATE_IN_CLUSTER,
      info: getString('connectors.k8.delegateInClusterInfo')
    }
  ]
 
  const authOptions: Array<AuthOptionInterface> = [
    {
      label: getString('usernamePassword'),
      value: AuthTypes.USER_PASSWORD
    },
    {
      label: getString('serviceAccount'),
      value: AuthTypes.SERVICE_ACCOUNT
    },
    {
      label: getString('connectors.k8.authLabels.OIDC'),
      value: AuthTypes.OIDC
    },
    {
      label: getString('connectors.k8.authLabels.clientKeyCertificate'),
      value: AuthTypes.CLIENT_KEY_CERT
    }
  ]
 
  const validationSchema = Yup.object().shape({
    //todo: add validation for delegate
 
    masterUrl: Yup.string()
      .nullable()
      .when('delegateType', {
        is: delegateType => delegateType === DelegateTypes.DELEGATE_OUT_CLUSTER,
        then: Yup.string().required(getString('validation.masterUrl'))
      }),
    delegateType: Yup.string().required(getString('connectors.chooseMethodForK8sConnection')),
    authType: Yup.string()
      .nullable()
      .when('delegateType', {
        is: delegateType => delegateType === DelegateTypes.DELEGATE_OUT_CLUSTER,
        then: Yup.string().required(getString('validation.authType'))
      }),
    username: Yup.string()
      .nullable()
      .when('authType', {
        is: authType => authType === AuthTypes.USER_PASSWORD,
        then: Yup.string().required(getString('validation.username'))
      }),
    password: Yup.object().when('authType', {
      is: authType => authType === AuthTypes.USER_PASSWORD,
      then: Yup.object().required(getString('validation.password')),
      otherwise: Yup.object().nullable()
    }),
    serviceAccountToken: Yup.object().when('authType', {
      is: authType => authType === AuthTypes.SERVICE_ACCOUNT,
      then: Yup.object().required(getString('validation.serviceAccountToken')),
      otherwise: Yup.object().nullable()
    }),
    oidcIssuerUrl: Yup.string().when('authType', {
      is: authType => authType === AuthTypes.OIDC,
      then: Yup.string().required(getString('validation.OIDCIssuerUrl')),
      otherwise: Yup.string().nullable()
    }),
    oidcUsername: Yup.string()
      .nullable()
      .when('authType', {
        is: authType => authType === AuthTypes.OIDC,
        then: Yup.string().required(getString('validation.OIDCUsername'))
      }),
    oidcPassword: Yup.object().when('authType', {
      is: authType => authType === AuthTypes.OIDC,
      then: Yup.object().required(getString('validation.OIDCPassword')),
      otherwise: Yup.object().nullable()
    }),
    oidcCleintId: Yup.object().when('authType', {
      is: authType => authType === AuthTypes.OIDC,
      then: Yup.object().required(getString('validation.OIDCClientId')),
      otherwise: Yup.object().nullable()
    }),
    clientKey: Yup.object().when('authType', {
      is: authType => authType === AuthTypes.CLIENT_KEY_CERT,
      then: Yup.object().required(getString('validation.clientKey')),
      otherwise: Yup.object().nullable()
    }),
 
    clientKeyCertificate: Yup.object().when('authType', {
      is: authType => authType === AuthTypes.CLIENT_KEY_CERT,
      then: Yup.object().required(getString('validation.clientCertificate')),
      otherwise: Yup.object().nullable()
    }),
    clientKeyAlgo: Yup.string()
      .nullable()
      .when('authType', {
        is: authType => authType === AuthTypes.CLIENT_KEY_CERT,
        then: Yup.string().required(getString('connectors.k8.validation.clientKeyAlgo'))
      })
  })
 
  const [initialValues, setInitialValues] = useState(defaultInitialFormData)
  const [loadingConnectorSecrets, setLoadingConnectorSecrets] = useState(true && props.isEditMode)
 
  useEffect(() => {
    if (loadingConnectorSecrets) {
      Eif (props.isEditMode) {
        Eif (props.connectorInfo) {
          setupKubFormData(props.connectorInfo, accountId).then(data => {
            setInitialValues(data as KubeFormInterface)
            setLoadingConnectorSecrets(false)
          })
        } else {
          setLoadingConnectorSecrets(false)
        }
      }
    }
  }, [loadingConnectorSecrets])
 
  const handleSubmit = (formData: ConnectorConfigDTO) => {
    nextStep?.({ ...props.connectorInfo, ...prevStepData, ...formData } as Stepk8ClusterDetailsProps)
  }
 
  return loadingConnectorSecrets ? (
    <PageSpinner />
  ) : (
    <Layout.Vertical spacing="medium" className={css.secondStep}>
      <Text
        font={{ variation: FontVariation.H3 }}
        color={Color.BLACK}
        tooltipProps={{ dataTooltipId: 'K8sConnectorDetails' }}
      >
        {getString('details')}
      </Text>
      <Formik
        initialValues={{
          ...initialValues,
          ...props.prevStepData
        }}
        validationSchema={validationSchema}
        formName="k8ClusterForm"
        onSubmit={handleSubmit}
      >
        {formikProps => (
          <>
            <Container className={css.clusterWrapper}>
              <ThumbnailSelect
                items={DelegateCards.map(card => ({ label: card.info, value: card.type }))}
                name="delegateType"
                size="large"
                onChange={type => {
                  formikProps?.setFieldValue('delegateType', type)
                  formikProps?.setFieldValue(
                    'authType',
                    type === DelegateTypes.DELEGATE_OUT_CLUSTER ? AuthTypes.USER_PASSWORD : ''
                  )
                }}
              />
 
              {DelegateTypes.DELEGATE_OUT_CLUSTER === formikProps.values.delegateType ? (
                <>
                  <FormInput.Text
                    label={getString('connectors.k8.masterUrlLabel')}
                    placeholder={getString('UrlLabel')}
                    name="masterUrl"
                    className={css.formFieldWidth}
                  />
 
                  <Container className={css.authHeaderRow}>
                    <Text
                      font={{ variation: FontVariation.H6 }}
                      inline
                      tooltipProps={{ dataTooltipId: 'K8sAuthenticationTooltip' }}
                    >
                      {getString('authentication')}
                    </Text>
                    <FormInput.Select
                      name="authType"
                      items={authOptions}
                      disabled={false}
                      className={commonStyles.authTypeSelect}
                    />
                  </Container>
 
                  <RenderK8AuthForm {...formikProps} isEditMode={props.isEditMode} />
                </>
              ) : (
                <></>
              )}
            </Container>
            <Layout.Horizontal padding={{ top: 'small' }} spacing="medium">
              <Button
                text={getString('back')}
                icon="chevron-left"
                variation={ButtonVariation.SECONDARY}
                onClick={() => props?.previousStep?.(props?.prevStepData)}
                data-name="k8sBackButton"
              />
              <Button
                type="submit"
                variation={ButtonVariation.PRIMARY}
                text={getString('continue')}
                rightIcon="chevron-right"
                onClick={formikProps.submitForm}
                margin={{ left: 'medium' }}
              />
            </Layout.Horizontal>
          </>
        )}
      </Formik>
    </Layout.Vertical>
  )
}
 
export default Stepk8ClusterDetails