All files / modules/33-auth-settings/pages/Configuration/SAMLProvider SAMLProvider.tsx

75.32% Statements 58/77
50% Branches 32/64
69.23% Functions 9/13
75.32% Lines 58/77

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              2x 2x 2x 2x                       2x 2x 2x 2x     2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x                   2x             17x 17x 17x 17x 17x 17x 17x 22x     17x         17x 1x     17x             17x             17x           17x             17x 6x     17x                           1x 1x 1x 1x 1x 1x                 17x                                                   17x 6x           17x                                     2x 1x 1x   1x 1x 1x                 17x                                                                                                                             1x                                                         2x                         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, { Dispatch, SetStateAction } from 'react'
import cx from 'classnames'
import { useParams } from 'react-router-dom'
import {
  Radio,
  Container,
  Collapse,
  Card,
  Text,
  Button,
  Popover,
  ButtonVariation,
  Utils,
  useConfirmationDialog
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { Menu, MenuItem } from '@blueprintjs/core'
import { useToaster } from '@common/components'
import { useStrings } from 'framework/strings'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import type { AuthenticationSettingsResponse, SAMLSettings } from 'services/cd-ng'
import { useDeleteSamlMetaData, useUpdateAuthMechanism, useGetSamlLoginTest } from 'services/cd-ng'
import { AuthenticationMechanisms } from '@auth-settings/constants/utils'
import { useSAMLProviderModal } from '@auth-settings/modals/SAMLProvider/useSAMLProvider'
import RbacMenuItem from '@rbac/components/MenuItem/MenuItem'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import type { PermissionRequest } from '@auth-settings/pages/Configuration/Configuration'
import { useFeature } from '@common/hooks/useFeatures'
import { FeatureIdentifier } from 'framework/featureStore/FeatureIdentifier'
import { FeatureWarningTooltip } from '@common/components/FeatureWarning/FeatureWarningWithTooltip'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import css from './SAMLProvider.module.scss'
import cssConfiguration from '@auth-settings/pages/Configuration/Configuration.module.scss'
 
interface Props {
  authSettings: AuthenticationSettingsResponse
  refetchAuthSettings: () => void
  permissionRequest: PermissionRequest
  canEdit: boolean
  setUpdating: Dispatch<SetStateAction<boolean>>
}
 
const SAMLProvider: React.FC<Props> = ({
  authSettings,
  refetchAuthSettings,
  permissionRequest,
  canEdit,
  setUpdating
}) => {
  const { getRBACErrorMessage } = useRBACError()
  const { getString } = useStrings()
  const { showSuccess, showError } = useToaster()
  const { accountId } = useParams<AccountPathProps>()
  const [childWindow, setChildWindow] = React.useState<Window | null>(null)
  const samlEnabled = authSettings.authenticationMechanism === AuthenticationMechanisms.SAML
  const samlSettings = authSettings.ngAuthSettings?.find(
    settings => settings.settingsType === AuthenticationMechanisms.SAML
  ) as SAMLSettings | undefined
 
  const { enabled: featureEnabled } = useFeature({
    featureRequest: {
      featureName: FeatureIdentifier.SAML_SUPPORT
    }
  })
  const onSuccess = (): void => {
    refetchAuthSettings()
  }
 
  const { openSAMlProvider } = useSAMLProviderModal({ onSuccess })
 
  const {
    data: samlLoginTestData,
    loading: fetchingSamlLoginTestData,
    error: samlLoginTestDataError,
    refetch: getSamlLoginTestData
  } = useGetSamlLoginTest({
    queryParams: {
      accountId: accountId
    },
    lazy: true
  })
 
  const { mutate: deleteSamlSettings, loading: deletingSamlSettings } = useDeleteSamlMetaData({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const { mutate: updateAuthMechanismToSaml, loading: updatingAuthMechanismToSaml } = useUpdateAuthMechanism({
    queryParams: {
      accountIdentifier: accountId,
      authenticationMechanism: AuthenticationMechanisms.SAML
    }
  })
 
  React.useEffect(() => {
    setUpdating(updatingAuthMechanismToSaml || deletingSamlSettings)
  }, [updatingAuthMechanismToSaml, deletingSamlSettings, setUpdating])
 
  const { openDialog: confirmSamlSettingsDelete } = useConfirmationDialog({
    titleText: getString('authSettings.deleteSamlProvider'),
    contentText: (
      <React.Fragment>
        <span>{getString('authSettings.deleteSamlProviderDescription')} </span>
        <Text inline font={{ weight: 'bold' }} color={Color.GREY_800}>
          {samlSettings?.displayName}
        </Text>
        ?
      </React.Fragment>
    ),
    confirmButtonText: getString('confirm'),
    cancelButtonText: getString('cancel'),
    onCloseDialog: async isConfirmed => {
      /* istanbul ignore else */ if (isConfirmed) {
        try {
          const deleted = await deleteSamlSettings('' as any)
          /* istanbul ignore else */ if (deleted) {
            refetchAuthSettings()
            showSuccess(getString('authSettings.samlProviderDeleted'), 5000)
          }
        } catch (e) {
          /* istanbul ignore next */ showError(getRBACErrorMessage(e), 5000)
        }
      }
    }
  })
 
  const testSamlProvider = async (): Promise<void> => {
    if (samlLoginTestData?.resource?.ssorequest?.idpRedirectUrl) {
      localStorage.setItem('samlTestResponse', 'testing')
      const win = window.open(samlLoginTestData.resource.ssorequest.idpRedirectUrl)
      const localStorageUpdate = (): void => {
        const samlTestResponse = localStorage.getItem('samlTestResponse')
        /* istanbul ignore else */ Iif (samlTestResponse === 'true' || samlTestResponse === 'false') {
          if (samlTestResponse === 'true') {
            showSuccess(getString('authSettings.samlTestSuccessful'), 5000)
          } else {
            showError(getString('authSettings.samlTestFailed'), 5000)
          }
          win?.close()
          setChildWindow(null)
          localStorage.removeItem('samlTestResponse')
          window.removeEventListener('storage', localStorageUpdate)
        }
      }
      window.addEventListener('storage', localStorageUpdate)
      win?.focus()
      setChildWindow(win)
    } else {
      /* istanbul ignore next */ showError(samlLoginTestDataError?.message, 5000)
    }
  }
 
  React.useEffect(() => {
    /* istanbul ignore else */ Iif (samlLoginTestData || samlLoginTestDataError) {
      testSamlProvider()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [samlLoginTestData, samlLoginTestDataError])
 
  const { openDialog: enableSamlProvide } = useConfirmationDialog({
    titleText: getString('authSettings.enableSamlProvider'),
    contentText: getString('authSettings.enableSamlProviderDescription'),
    confirmButtonText: getString('confirm'),
    customButtons: (
      <Container flex width="100%">
        <Button
          className={css.leftMarginAuto}
          variation={ButtonVariation.SECONDARY}
          text={getString('test')}
          disabled={!!childWindow || fetchingSamlLoginTestData}
          onClick={() => {
            getSamlLoginTestData()
          }}
        />
      </Container>
    ),
    cancelButtonText: getString('cancel'),
    onCloseDialog: async isConfirmed => {
      if (isConfirmed) {
        try {
          const response = await updateAuthMechanismToSaml(undefined)
 
          /* istanbul ignore else */ if (response) {
            refetchAuthSettings()
            showSuccess(getString('authSettings.samlLoginEnabled'), 5000)
          }
        } catch (e) {
          /* istanbul ignore next */ showError(getRBACErrorMessage(e), 5000)
        }
      }
    }
  })
 
  return (
    <Container margin="xlarge" background={Color.WHITE}>
      {samlSettings ? (
        <Collapse
          isOpen={samlEnabled && featureEnabled}
          collapseHeaderClassName={cx(cssConfiguration.collapseHeaderClassName, cssConfiguration.height60)}
          collapseClassName={cssConfiguration.collapseClassName}
          collapsedIcon="main-chevron-down"
          expandedIcon="main-chevron-up"
          heading={
            <Utils.WrapOptionalTooltip
              tooltip={
                !featureEnabled ? <FeatureWarningTooltip featureName={FeatureIdentifier.SAML_SUPPORT} /> : undefined
              }
            >
              <Container margin={{ left: 'xlarge' }}>
                <Radio
                  checked={samlEnabled}
                  font={{ weight: 'bold', size: 'normal' }}
                  color={Color.GREY_900}
                  label={getString('authSettings.loginViaSAML')}
                  onChange={enableSamlProvide}
                  disabled={!featureEnabled || !canEdit || updatingAuthMechanismToSaml}
                />
              </Container>
            </Utils.WrapOptionalTooltip>
          }
        >
          <Container padding={{ bottom: 'large' }}>
            <Card className={css.card}>
              <Container margin={{ left: 'xlarge' }}>
                <Radio font={{ weight: 'bold', size: 'normal' }} checked={samlEnabled} readOnly />
              </Container>
              <Text color={Color.GREY_800} font={{ weight: 'bold' }} width="30%">
                {samlSettings.displayName}
              </Text>
              <Text color={Color.GREY_800} width="70%">
                {samlSettings.authorizationEnabled ? (
                  <span>
                    {getString('authSettings.authorizationEnabledFor')}
                    <Text font={{ weight: 'semi-bold' }} color={Color.GREY_800} inline>
                      {samlSettings.groupMembershipAttr}
                    </Text>
                  </span>
                ) : (
                  getString('authSettings.authorizationNotEnabled')
                )}
              </Text>
              <Button
                text={getString('test')}
                variation={ButtonVariation.SECONDARY}
                disabled={!!childWindow || fetchingSamlLoginTestData}
                onClick={() => {
                  getSamlLoginTestData()
                }}
              />
              <Popover
                interactionKind="click"
                position="left-top"
                content={
                  <Menu>
                    <MenuItem
                      text={getString('edit')}
                      onClick={() => openSAMlProvider(samlSettings)}
                      disabled={!canEdit}
                    />
                    <RbacMenuItem
                      text={getString('delete')}
                      onClick={confirmSamlSettingsDelete}
                      permission={{
                        ...permissionRequest,
                        permission: PermissionIdentifier.DELETE_AUTHSETTING
                      }}
                      disabled={deletingSamlSettings}
                    />
                  </Menu>
                }
              >
                <Button minimal icon="Options" data-testid="provider-button" variation={ButtonVariation.ICON} />
              </Popover>
            </Card>
          </Container>
        </Collapse>
      ) : (
        <Utils.WrapOptionalTooltip
          tooltip={!featureEnabled ? <FeatureWarningTooltip featureName={FeatureIdentifier.SAML_SUPPORT} /> : undefined}
        >
          <Card className={css.cardWithRadioBtn}>
            <Container margin={{ left: 'xlarge', top: 'xsmall' }}>
              <Radio
                checked={samlEnabled}
                font={{ weight: 'semi-bold', size: 'normal' }}
                onClick={() => openSAMlProvider()}
                color={Color.PRIMARY_7}
                label={getString('authSettings.plusSAMLProvider')}
                disabled={!featureEnabled || !canEdit}
              />
            </Container>
          </Card>
        </Utils.WrapOptionalTooltip>
      )}
    </Container>
  )
}
 
export default SAMLProvider