All files / modules/33-auth-settings/modals/SAMLProvider/views SAMLProviderForm.tsx

93.55% Statements 58/62
69.44% Branches 75/108
81.25% Functions 13/16
93.55% Lines 58/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              2x 2x 2x 2x                                   2x 2x   2x 2x 2x 2x 2x 2x   2x             2x 2x               2x           1x   2x                     2x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x                           11x 3x 1x 1x 1x 1x       11x                                             11x 11x           11x           11x 1x     1x 1x         1x 1x           1x             11x     11x                         12x       12x       12x       12x         1x       17x                       1x                                                                                                                                                                                                                                                                                             2x  
/*
 * 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, { useEffect } from 'react'
import { useParams } from 'react-router-dom'
import * as yup from 'yup'
import {
  Layout,
  Heading,
  Formik,
  FormikForm,
  Container,
  FormInput,
  Text,
  Button,
  Checkbox,
  ModalErrorHandler,
  ModalErrorHandlerBinding,
  TextInput,
  ButtonVariation,
  ThumbnailSelect,
  Label,
  Page
} from '@wings-software/uicore'
import { Color, FontVariation } from '@harness/design-system'
import { defaultTo } from 'lodash-es'
import type { ToasterProps } from '@wings-software/uicore/dist/hooks/useToaster/useToaster'
import { useStrings } from 'framework/strings'
import { useToaster } from '@common/components'
import { CopyText } from '@common/components/CopyText/CopyText'
import { useUploadSamlMetaData, useUpdateSamlMetaData, SAMLSettings } from 'services/cd-ng'
import { getSamlEndpoint } from '@auth-settings/constants/utils'
import { useFeatureFlags } from '@common/hooks/useFeatureFlag'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import {
  createFormData,
  FormValues,
  SAMLProviderType,
  Providers,
  getSelectedSAMLProvider
} from '@auth-settings/modals/SAMLProvider/utils'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import css from '../useSAMLProvider.module.scss'
 
interface Props {
  onSubmit?: () => void
  onCancel: () => void
  samlProvider?: SAMLSettings
}
 
const handleSuccess = (
  successCallback: ToasterProps['showSuccess'],
  isCreate: boolean,
  createText: string,
  updateText: string
): void => {
  successCallback(isCreate ? createText : updateText, 5000)
}
const defaultInitialData = {
  displayName: '',
  authorizationEnabled: true,
  groupMembershipAttr: '',
  entityIdEnabled: false,
  entityIdentifier: '',
  enableClientIdAndSecret: false,
  clientSecret: undefined,
  clientId: '',
  samlProviderType: undefined
}
const SAMLProviderForm: React.FC<Props> = ({ onSubmit, onCancel, samlProvider }) => {
  const { getRBACErrorMessage } = useRBACError()
  const { getString } = useStrings()
  const { showSuccess } = useToaster()
  const { AZURE_SAML_150_GROUPS_SUPPORT } = useFeatureFlags()
  const { accountId } = useParams<AccountPathProps>()
  const [initialValues, setInitialValues] = React.useState<FormValues>(defaultInitialData)
  const [initialLoading, setIntitalLoading] = React.useState<boolean>(!!samlProvider)
  const [selected, setSelected] = React.useState<SAMLProviderType>()
  const [modalErrorHandler, setModalErrorHandler] = React.useState<ModalErrorHandlerBinding>()
  const hasSamlProvider = selected || samlProvider
  const setupInitialData = async (): Promise<FormValues> => {
    return {
      displayName: defaultTo(samlProvider?.displayName, ''),
      authorizationEnabled: samlProvider ? !!samlProvider?.authorizationEnabled : true,
      logoutUrl: samlProvider?.logoutUrl,
      groupMembershipAttr: defaultTo(samlProvider?.groupMembershipAttr, ''),
      entityIdEnabled: samlProvider ? !!samlProvider?.entityIdentifier : false,
      entityIdentifier: defaultTo(samlProvider?.entityIdentifier, ''),
      enableClientIdAndSecret: samlProvider ? !!samlProvider?.clientSecret || !!samlProvider?.clientId : false,
      clientSecret: defaultTo(samlProvider?.clientSecret, ''),
      clientId: defaultTo(samlProvider?.clientId, ''),
      samlProviderType:
        samlProvider && samlProvider?.samlProviderType ? (samlProvider?.samlProviderType as Providers) : undefined
    }
  }
  useEffect(() => {
    if (samlProvider) {
      setIntitalLoading(true)
      setupInitialData().then(data => {
        setInitialValues(data)
        setIntitalLoading(false)
      })
    }
  }, [samlProvider])
  const SAMLProviderTypes: SAMLProviderType[] = [
    {
      value: Providers.AZURE,
      label: getString('authSettings.azure'),
      icon: 'service-azure'
    },
    {
      value: Providers.OKTA,
      label: getString('authSettings.okta'),
      icon: 'service-okta'
    },
    {
      value: Providers.ONE_LOGIN,
      label: getString('authSettings.oneLogin'),
      icon: 'service-onelogin'
    },
    {
      value: Providers.OTHER,
      label: getString('common.other'),
      icon: 'main-more'
    }
  ]
 
  const selectedSAMLProvider = getSelectedSAMLProvider(selected, getString)
  const { mutate: uploadSamlSettings, loading: uploadingSamlSettings } = useUploadSamlMetaData({
    queryParams: {
      accountId
    }
  })
 
  const { mutate: updateSamlSettings, loading: updatingSamlSettings } = useUpdateSamlMetaData({
    queryParams: {
      accountId
    }
  })
 
  const handleSubmit = async (values: FormValues): Promise<void> => {
    try {
      let response
 
      Eif (samlProvider) {
        response = await updateSamlSettings(createFormData(values) as any)
      } else {
        response = await uploadSamlSettings(createFormData(values) as any)
      }
 
      Eif (response) {
        handleSuccess(
          showSuccess,
          !samlProvider,
          getString('authSettings.samlProviderAddedSuccessfully'),
          getString('authSettings.samlProviderUpdatedSuccessfully')
        )
        onSubmit?.()
      }
    } catch (e) {
      /* istanbul ignore next */ modalErrorHandler?.showDanger(getRBACErrorMessage(e))
    }
  }
 
  const filesValidation = samlProvider
    ? yup.array()
    : yup.array().required(getString('common.validation.fileIsRequired'))
  return (
    <Layout.Horizontal>
      <Layout.Vertical width={660} padding={{ right: 'xxxlarge' }}>
        {initialLoading ? (
          <Page.Spinner />
        ) : (
          <Formik<FormValues>
            formName="samlProviderForm"
            initialValues={initialValues}
            validationSchema={yup.object().shape({
              displayName: yup.string().trim().required(getString('common.validation.nameIsRequired')),
              files: filesValidation,
              groupMembershipAttr: yup.string().when('authorizationEnabled', {
                is: val => val,
                then: yup.string().trim().required(getString('common.validation.groupAttributeIsRequired'))
              }),
              entityIdentifier: yup.string().when('entityIdEnabled', {
                is: val => val,
                then: yup.string().trim().required(getString('common.validation.entityIdIsRequired'))
              }),
              clientId: yup.string().when('enableClientIdAndSecret', {
                is: val => val,
                then: yup.string().trim().required(getString('common.validation.clientIdIsRequired'))
              }),
              clientSecret: yup.string().when('enableClientIdAndSecret', {
                is: val => val,
                then: yup.string().trim().required(getString('common.validation.clientSecretRequired'))
              })
            })}
            onSubmit={values => {
              handleSubmit({ ...values })
            }}
          >
            {({ values, setFieldValue }) => (
              <FormikForm>
                <Container width={474} margin={{ bottom: 'large' }}>
                  <ModalErrorHandler bind={setModalErrorHandler} />
                  <FormInput.Text name="displayName" label={getString('name')} />
                </Container>
                {!samlProvider && (
                  <Layout.Vertical spacing="small" padding={{ bottom: 'medium' }}>
                    <Label>{getString('authSettings.selectSAMLProvider')}</Label>
                    <ThumbnailSelect
                      name="samlProviderType"
                      items={SAMLProviderTypes}
                      onChange={(value: unknown) => {
                        setSelected(value as SAMLProviderType)
                      }}
                    />
                  </Layout.Vertical>
                )}
                {hasSamlProvider && (
                  <React.Fragment>
                    <Label>
                      {getString('authSettings.enterSAMLEndPoint', {
                        selectedSAMLProvider
                      })}
                    </Label>
                    <TextInput
                      value={getSamlEndpoint(accountId)}
                      rightElement={
                        (
                          <CopyText
                            className={css.copy}
                            iconName="duplicate"
                            textToCopy={getSamlEndpoint(accountId)}
                            iconAlwaysVisible
                          />
                        ) as any
                      }
                      readOnly
                    />
                    <Container margin={{ bottom: 'xxxlarge' }}>
                      <FormInput.FileInput
                        name="files"
                        label={`${getString(
                          samlProvider ? 'authSettings.identityProvider' : 'authSettings.uploadIdentityProvider',
                          {
                            selectedSAMLProvider
                          }
                        )}`}
                        buttonText={getString('upload')}
                        placeholder={getString('authSettings.chooseFile')}
                        multiple
                      />
                      <FormInput.Text name="logoutUrl" label={getString('authSettings.logoutUrl')} />
                    </Container>
                    <Container>
                      <Checkbox
                        name="authorization"
                        label={getString('authSettings.enableAuthorization')}
                        font={{ weight: 'semi-bold' }}
                        color={Color.GREY_600}
                        checked={values.authorizationEnabled}
                        onChange={e => setFieldValue('authorizationEnabled', e.currentTarget.checked)}
                      />
                      {values.authorizationEnabled && (
                        <Container width={300} margin={{ top: 'medium' }}>
                          <FormInput.Text
                            name="groupMembershipAttr"
                            label={getString('authSettings.groupAttributeName')}
                          />
                          {Providers.AZURE === values?.samlProviderType && AZURE_SAML_150_GROUPS_SUPPORT && (
                            <>
                              <Checkbox
                                name="clientIdAndSecret"
                                label={getString('authSettings.enableClientIdAndSecret')}
                                font={{ weight: 'semi-bold' }}
                                color={Color.GREY_600}
                                checked={values.enableClientIdAndSecret}
                                onChange={e => setFieldValue('enableClientIdAndSecret', e.currentTarget.checked)}
                              />
 
                              {Providers.AZURE === values?.samlProviderType && values.enableClientIdAndSecret && (
                                <Container width={300} margin={{ top: 'medium' }}>
                                  <FormInput.Text name="clientId" label={getString('common.clientId')} />
                                  <FormInput.Text
                                    name="clientSecret"
                                    inputGroup={{ type: 'password' }}
                                    label={getString('common.clientSecret')}
                                  />
                                </Container>
                              )}
                            </>
                          )}
                        </Container>
                      )}
                    </Container>
                    <Container margin={{ top: 'large' }}>
                      <Checkbox
                        name="enableEntityId"
                        label={getString('authSettings.enableEntityIdLabel')}
                        font={{ variation: FontVariation.FORM_LABEL }}
                        color={Color.GREY_600}
                        checked={values.entityIdEnabled}
                        onChange={e => setFieldValue('entityIdEnabled', e.currentTarget.checked)}
                      />
                      {values.entityIdEnabled && (
                        <Container width={300} margin={{ top: 'medium' }}>
                          <FormInput.Text name="entityIdentifier" label={getString('authSettings.entityIdLabel')} />
                        </Container>
                      )}
                    </Container>
                  </React.Fragment>
                )}
                <Layout.Horizontal spacing="small" padding={{ top: 'xxxlarge' }}>
                  <Button
                    variation={ButtonVariation.PRIMARY}
                    text={getString(samlProvider ? 'save' : 'add')}
                    type="submit"
                    disabled={uploadingSamlSettings || updatingSamlSettings}
                  />
                  <Button text={getString('cancel')} onClick={onCancel} variation={ButtonVariation.TERTIARY} />
                </Layout.Horizontal>
              </FormikForm>
            )}
          </Formik>
        )}
      </Layout.Vertical>
      <Layout.Vertical width={290} padding={{ left: 'xxxlarge' }} margin={{ bottom: 'large' }} border={{ left: true }}>
        <Heading level={6} color={Color.BLACK} font={{ weight: 'semi-bold' }} margin={{ bottom: 'medium' }}>
          {getString('authSettings.friendlyReminder')}
        </Heading>
        <Text color={Color.GREY_800} font={{ size: 'small' }} margin={{ bottom: 'xxlarge' }} className={css.notes}>
          {getString('authSettings.friendlyReminderDescription')}
        </Text>
        {hasSamlProvider && (
          <React.Fragment>
            <Heading level={6} color={Color.BLACK} font={{ weight: 'semi-bold' }} margin={{ bottom: 'medium' }}>
              {getString('authSettings.enablingAuthorization')}
            </Heading>
            <Text color={Color.GREY_800} font={{ size: 'small' }} margin={{ bottom: 'xxlarge' }} className={css.notes}>
              {getString('authSettings.enablingAuthorizationDescription', {
                selectedSAMLProvider
              })}
            </Text>
            <Heading level={6} color={Color.BLACK} font={{ weight: 'semi-bold' }} margin={{ bottom: 'medium' }}>
              {getString('authSettings.testingSSO')}
            </Heading>
            <Text color={Color.GREY_800} font={{ size: 'small' }} margin={{ bottom: 'xxlarge' }} className={css.notes}>
              {getString('authSettings.testingSSODescription')}
            </Text>
          </React.Fragment>
        )}
      </Layout.Vertical>
    </Layout.Horizontal>
  )
}
 
export default SAMLProviderForm