All files / modules/35-connectors/components/CreateConnector/CEAzureConnector/Steps/CreateServicePrincipal CreateServicePrincipal.tsx

88.89% Statements 48/54
63.16% Branches 48/76
83.33% Functions 5/6
88.89% Lines 48/54

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              219x 219x 219x 219x                   219x 219x 219x 219x 219x 219x 219x   219x               219x 4x 3x 3x 3x 3x 3x 3x   3x 3x   3x   3x 1x 1x 1x 1x                         1x       1x       1x               3x 3x 1x     3x 3x 3x   3x 3x                                     3x 3x                             3x                       3x                   3x                               1x                 219x 9x                     219x  
/*
 * 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, { useEffect, useState } from 'react'
import { pick } from 'lodash-es'
import { useParams } from 'react-router-dom'
import {
  Button,
  Heading,
  Layout,
  Text,
  StepProps,
  Container,
  ModalErrorHandler,
  ModalErrorHandlerBinding
} from '@wings-software/uicore'
import { useStrings } from 'framework/strings'
import { useCreateConnector, useUpdateConnector, Failure } from 'services/cd-ng'
import { useAzureappclientid } from 'services/ce/index'
import CopyToClipboard from '@common/components/CopyToClipBoard/CopyToClipBoard'
import { CE_AZURE_CONNECTOR_CREATION_EVENTS } from '@connectors/trackingConstants'
import { useStepLoadTelemetry } from '@connectors/common/useTrackStepLoad/useStepLoadTelemetry'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import type { CEAzureDTO } from '../Overview/AzureConnectorOverview'
import css from '../../CreateCeAzureConnector_new.module.scss'
 
type ConnectorPayload = Omit<CEAzureDTO, 'existingBillingExports' | 'hasBilling' | 'isEditMode'>
interface CommandsProps {
  command: string
  comment: string
}
 
const CreateServicePrincipal: React.FC<StepProps<CEAzureDTO>> = (props): JSX.Element => {
  const { getString } = useStrings()
  const { getRBACErrorMessage } = useRBACError()
  const [appId, setAppId] = useState('')
  const [isSaving, setIsSaving] = useState(false)
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding | undefined>()
  const { prevStepData, previousStep, nextStep } = props
  const { accountId } = useParams<{ accountId: string }>()
 
  const { mutate: createConnector } = useCreateConnector({ queryParams: { accountIdentifier: accountId } })
  const { mutate: updateConnector } = useUpdateConnector({ queryParams: { accountIdentifier: accountId } })
 
  useStepLoadTelemetry(CE_AZURE_CONNECTOR_CREATION_EVENTS.LOAD_SERVICE_PRINCIPAL)
 
  const saveAndContinue = async () => {
    setIsSaving(true)
    try {
      Eif (prevStepData) {
        const payload: ConnectorPayload = {
          ...pick(prevStepData, [
            'name',
            'description',
            'identifier',
            'orgIdentifier',
            'projectIdentifier',
            'tags',
            'type',
            'spec'
          ])
        }
 
        const response = await (prevStepData.isEditMode
          ? updateConnector({ connector: payload })
          : createConnector({ connector: payload }))
 
        Iif ('SUCCESS' !== response.status) {
          throw response as Failure
        }
 
        nextStep?.(prevStepData)
      }
    } catch (e) {
      modalErrorHandler?.showDanger(getRBACErrorMessage(e))
      setIsSaving(false)
    }
  }
 
  const { data, loading } = useAzureappclientid({})
  useEffect(() => {
    'SUCCESS' === data?.status && setAppId(data?.data || '')
  }, [loading])
 
  let commands = []
  const featuresEnabled = prevStepData?.spec?.featuresEnabled || []
  const subscriptionId = prevStepData?.spec?.subscriptionId || '<insert_subscriptionId>'
  const storageAccountName =
    prevStepData?.spec?.billingExportSpec?.storageAccountName || '<insert_storage_account_name>'
  const ENABLED = {
    BILLING: featuresEnabled.includes('BILLING'),
    VISIBILITY: featuresEnabled.includes('VISIBILITY'),
    OPTIMIZATION: featuresEnabled.includes('OPTIMIZATION')
  }
 
  // Keeping these commands as comment for reference purpose
  //
  // # 1. Register the Harness app
  // az ad sp create --id <id_of_the_service_principal_from_BE_api>
  //
  // # 2. Role assignment for enabling CCM Billing + Visibility
  // SCOPE=`az storage account show --name <storage account name from previous screen> --query "id" | xargs`
  // az role assignment create --assignee <id_of_the_service_principal_from_api> --role 'Storage Blob Data Reader' --scope $SCOPE
  //
  // # 3. Role assignment for enabling CCM Optimisation
  // az role assignment create --assignee <id_of_the_service_principal_from_api> --role 'Contributor' --scope /subscriptions/<subscription id from screen 1>
 
  // If only BILLING is selected, we need to show 1 and 2.
  Eif (ENABLED.BILLING || ENABLED.VISIBILITY) {
    commands.push(
      <Commands comment={'# Register the Harness app'} command={`az ad sp create --id ${appId}`} />,
      <Commands
        comment={'# Role assignment for enabling CCM Billing and Visibility'}
        command={`SCOPE=\`az storage account show --name ${storageAccountName} --query "id" | xargs\``}
      />,
      <Commands
        comment={'# Assign role to the app on the scope fetched above'}
        command={`az role assignment create --assignee ${appId}  --role 'Storage Blob Data Reader' --scope $SCOPE`}
      />
    )
  }
 
  // If BILLING and OPTIMIZATION are selected, we need to show 1, 2, and 3.
  // 1 & 2 are added from above
  Iif (ENABLED.BILLING && ENABLED.OPTIMIZATION) {
    commands.push(
      <Commands
        comment={'# Role assignment for enabling CCM Optimisation'}
        command={`az role assignment create --assignee ${appId} --role 'Contributor' --scope /subscriptions/${subscriptionId}`}
      />
    )
  }
 
  // If only OPTIMIZATION is selected (BILLING was pre existing),
  // we need to show only this command, which is number 3. (As our app is already registered)
  // It doesn't matter if the VISIBILITY is also selected with OPTIMIZATION
  Iif (!ENABLED.BILLING && ENABLED.OPTIMIZATION) {
    commands = [
      <Commands
        key={'opt'}
        comment={'# Role assignment for enabling CCM Optimisation'}
        command={`az role assignment create --assignee ${appId} --role 'Contributor' --scope /subscriptions/${subscriptionId}`}
      />
    ]
  }
 
  return (
    <Layout.Vertical spacing="large" className={css.stepContainer}>
      <ModalErrorHandler bind={setModalErrorHandler} />
      <Heading color="grey800" level={2} style={{ fontSize: 20 }}>
        {getString('connectors.ceAzure.servicePrincipal.heading')}
      </Heading>
      <Text>{getString('connectors.ceAzure.servicePrincipal.subHeading')}</Text>
      <Container className={css.commandsContainer}>{commands}</Container>
      <Layout.Horizontal spacing="medium" className={css.continueAndPreviousBtns}>
        <Button text="Previous" icon="chevron-left" onClick={() => previousStep?.(prevStepData)} />
        <Button
          type="submit"
          intent="primary"
          rightIcon="chevron-right"
          loading={isSaving}
          disabled={isSaving}
          onClick={() => saveAndContinue()}
        >
          {getString('continue')}
        </Button>
      </Layout.Horizontal>
    </Layout.Vertical>
  )
}
 
const Commands = ({ command, comment }: CommandsProps) => {
  return (
    <Container style={{ marginBottom: 20 }}>
      <Text>{comment}</Text>
      <Container className={css.command}>
        <pre>{command}</pre>
        <CopyToClipboard showFeedback content={command} iconSize={16} />
      </Container>
    </Container>
  )
}
 
export default CreateServicePrincipal