All files / modules/75-ce/components/COGatewayAccess helper.ts

84.14% Statements 122/145
49.14% Branches 286/582
79.49% Functions 31/39
80.67% Lines 96/119

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 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458              6x   6x                           6x                   6x 9x             38x 9x     6x 1x   1x                           1x 1x       1x     1x     6x 9x 9x 2x   9x     6x                               6x                       6x                           6x               6x         57x                                               6x             55x 55x                                   6x                                             6x       4x 4x                                     6x       61x 61x 57x                           4x 4x                     61x     6x       61x       61x 57x     57x       61x     6x       61x         61x 3x 3x 3x   58x     58x   61x     6x       13x 13x           13x 1x             13x           13x     6x 12x 12x 12x 12x 12x       12x     6x 12x     6x     24x                       6x 12x 24x       6x       32x                       6x         2x 2x           6x         2x 2x           6x           2x 2x 1x     1x 1x     1x     1x 1x     1x 1x     1x                             2x    
/*
 * Copyright 2022 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 { isEmpty as _isEmpty, defaultTo as _defaultTo } from 'lodash-es'
import type { SelectOption } from '@wings-software/uicore'
import { Utils } from '@ce/common/Utils'
import type {
  AccessPoint,
  AccessPointCore,
  AccessPointResourcesQueryParams,
  ALBAccessPointCore,
  AzureAccessPointCore,
  FirewallRule,
  ListAccessPointsQueryParams,
  NetworkSecurityGroup,
  TargetGroupMinimal,
  PortConfig,
  GCPAccessPointCore
} from 'services/lw'
import { portProtocolMap } from '@ce/constants'
import type {
  BaseFetchDetails,
  ConnectionMetadata,
  GatewayDetails,
  GetInitialAccessPointDetails,
  GetInitialAzureAccessPoint,
  RuleCreationParams
} from '../COCreateGateway/models'
 
export const getSelectedTabId = (accessDetails: ConnectionMetadata): string => {
  const accessDetailsToTabIdMap: Record<string, string> = {
    dnsLink: 'dns',
    ssh: 'ssh',
    ipaddress: 'ip',
    rdp: 'rdp',
    backgroundTasks: 'bg'
  }
  const key = Object.entries(accessDetails).find(([, d]) => d.selected)?.[0]
  return key ? accessDetailsToTabIdMap[key] : ''
}
 
export const getValidStatusForDnsLink = (gatewayDetails: GatewayDetails): boolean => {
  let validStatus = true
  // check for custom domains validation
  Iif (gatewayDetails.customDomains?.length) {
    validStatus = gatewayDetails.customDomains.every(url =>
      url.match(
        /((https?):\/\/)?(www.)?[a-z0-9-]+(\.[a-z]{2,}){1,3}(#?\/?[a-zA-Z0-9#-]+)*\/?(\?[a-zA-Z0-9-_]+=[a-zA-Z0-9-%]+&?)?$/
      )
    )
    if (
      !gatewayDetails.routing.custom_domain_providers?.others &&
      !gatewayDetails.routing.custom_domain_providers?.route53?.hosted_zone_id
    ) {
      validStatus = false
    }
  }
  // checck for valid access point selected
  Eif (_isEmpty(gatewayDetails.accessPointID)) {
    validStatus = false
  }
 
  // check for routing ports
  Iif (validStatus && _isEmpty(gatewayDetails.routing.container_svc) && _isEmpty(gatewayDetails.routing.ports)) {
    validStatus = false
  }
  return validStatus
}
 
export const getHelpText = (selectedTabId: string) => {
  let helpTextBase = 'setup-access'
  if (selectedTabId !== '') {
    helpTextBase = `${helpTextBase}-${selectedTabId}`
  }
  return helpTextBase
}
 
export const getDummySupportedResourceFromAG = (ag: AccessPoint): AccessPointCore => {
  return {
    type: 'app_gateway',
    details: {
      fe_ip_id: ag.metadata?.fe_ip_id,
      id: ag.id,
      name: ag.name,
      region: ag.region,
      resource_group: ag.metadata?.resource_group,
      size: ag.metadata?.size,
      subnet_id: ag.metadata?.subnet_id,
      vpc: ag.vpc
    }
  }
}
 
export const getDummySupportedResourceFromALB = (alb: AccessPoint): AccessPointCore => {
  return {
    type: 'alb',
    details: {
      albARN: alb.metadata?.albArn,
      name: alb.name,
      security_groups: alb.security_groups,
      vpc: alb.vpc
    }
  }
}
 
export const getDummyGcpSupportedResourceFromLb = (lb: AccessPoint): AccessPointCore => {
  return {
    type: 'envoy',
    details: {
      id: lb.id,
      name: lb.name,
      security_groups: lb.metadata?.security_groups,
      subnet: lb.metadata?.subnet_name,
      vpc: lb.vpc,
      zone: lb.metadata?.zone
    }
  }
}
 
export const getDummyResource = (data: AccessPoint, { isAwsProvider, isAzureProvider }: RuleCreationParams) => {
  return isAwsProvider
    ? getDummySupportedResourceFromALB(data)
    : isAzureProvider
    ? getDummySupportedResourceFromAG(data)
    : getDummyGcpSupportedResourceFromLb(data)
}
 
export const getInitialAccessPointDetails = ({
  gatewayDetails,
  accountId,
  projectId,
  orgId
}: GetInitialAccessPointDetails): AccessPoint => ({
  cloud_account_id: gatewayDetails.cloudAccount.id,
  account_id: accountId,
  project_id: projectId,
  org_id: orgId,
  metadata: {
    security_groups: [],
    dns: {}
  },
  type: gatewayDetails.provider.value,
  region: gatewayDetails.selectedInstances?.length
    ? gatewayDetails.selectedInstances[0].region
    : !_isEmpty(gatewayDetails.routing?.instance?.scale_group?.region)
    ? gatewayDetails.routing?.instance?.scale_group?.region
    : !_isEmpty(gatewayDetails.routing.container_svc)
    ? gatewayDetails.routing.container_svc?.region
    : '',
  vpc: gatewayDetails.selectedInstances?.length
    ? gatewayDetails.selectedInstances[0].vpc
    : !_isEmpty(gatewayDetails.routing?.instance?.scale_group?.target_groups)
    ? (gatewayDetails.routing?.instance?.scale_group?.target_groups as TargetGroupMinimal[])[0].vpc
    : ''
})
 
export const createApDetailsFromLoadBalancer = ({
  lbDetails,
  gatewayDetails,
  accountId,
  projectId,
  orgId
}: GetInitialAccessPointDetails): AccessPoint => {
  const initialAccessPointDetails = getInitialAccessPointDetails({ gatewayDetails, accountId, projectId, orgId })
  return {
    ...initialAccessPointDetails,
    name: lbDetails?.details?.name,
    ...((lbDetails?.details as ALBAccessPointCore)?.vpc && {
      vpc: (lbDetails?.details as ALBAccessPointCore).vpc
    }),
    metadata: {
      ...initialAccessPointDetails.metadata,
      ...((lbDetails?.details as ALBAccessPointCore)?.security_groups && {
        security_groups: (lbDetails?.details as ALBAccessPointCore).security_groups
      }),
      ...((lbDetails?.details as ALBAccessPointCore)?.albARN && {
        albArn: (lbDetails?.details as ALBAccessPointCore).albARN
      })
    }
  }
}
 
export const getGcpApFromLoadBalancer = (gatewayDetails: GatewayDetails, accountId: string, lb?: AccessPointCore) => {
  const region = _defaultTo(
    gatewayDetails.routing?.instance?.scale_group?.region,
    gatewayDetails.selectedInstances?.[0]?.region
  )
  const zone = _defaultTo(
    gatewayDetails.routing?.instance?.scale_group?.availability_zones?.[0],
    gatewayDetails.selectedInstances?.[0]?.metadata?.availabilityZone
  )
  return {
    cloud_account_id: gatewayDetails.cloudAccount.id,
    account_id: accountId,
    region: _defaultTo(region, ''),
    vpc: (lb?.details as GCPAccessPointCore)?.vpc,
    type: gatewayDetails.provider.value,
    metadata: {
      zone: _defaultTo(zone, ''),
      security_groups: (lb?.details as GCPAccessPointCore)?.security_groups,
      subnet: (lb?.details as GCPAccessPointCore)?.subnet
    }
  }
}
 
export const createAzureAppGatewayFromLoadBalancer = (
  { gatewayDetails, accountId, projectId, orgId, lbDetails }: GetInitialAzureAccessPoint,
  isCreateMode: boolean
): AccessPoint => {
  const details = Utils.getConditionalResult(isCreateMode, {}, lbDetails as AzureAccessPointCore)
  return {
    cloud_account_id: gatewayDetails.cloudAccount.id,
    account_id: accountId,
    project_id: projectId,
    org_id: orgId,
    region: details?.region,
    vpc: details?.vpc,
    name: details?.name,
    type: gatewayDetails.provider.value,
    metadata: {
      app_gateway_id: details?.id,
      fe_ip_id: details?.fe_ip_id,
      resource_group: details?.resource_group,
      size: details?.size,
      subnet_id: details?.subnet_id
    }
  }
}
 
export const getLoadBalancerToEdit = (
  { gatewayDetails, accountId, projectId, orgId, lbDetails }: GetInitialAccessPointDetails,
  { isAwsProvider, isAzureProvider, isCreateMode, isGcpProvider }: RuleCreationParams
) => {
  let lb: AccessPoint = {}
  if (isAwsProvider) {
    lb = isCreateMode
      ? getInitialAccessPointDetails({
          gatewayDetails: gatewayDetails,
          accountId,
          projectId,
          orgId
        })
      : createApDetailsFromLoadBalancer({
          lbDetails,
          gatewayDetails: gatewayDetails,
          accountId,
          projectId,
          orgId
        })
  } else Eif (isAzureProvider) {
    lb = createAzureAppGatewayFromLoadBalancer(
      {
        gatewayDetails: gatewayDetails,
        accountId,
        lbDetails: lbDetails?.details as AzureAccessPointCore
      },
      _defaultTo(isCreateMode, false)
    )
  } else if (isGcpProvider) {
    lb = getGcpApFromLoadBalancer(gatewayDetails, accountId, lbDetails)
  }
  return lb
}
 
export const getAccessPointFetchQueryParams = (
  { gatewayDetails, accountId }: BaseFetchDetails,
  isAwsProvider: boolean
): ListAccessPointsQueryParams => {
  const params: ListAccessPointsQueryParams = {
    cloud_account_id: gatewayDetails.cloudAccount.id,
    accountIdentifier: accountId
  }
  if (isAwsProvider) {
    params.region = gatewayDetails.selectedInstances?.length
      ? gatewayDetails.selectedInstances[0].region
      : gatewayDetails.routing.instance.scale_group?.region || ''
    params.vpc = gatewayDetails.selectedInstances?.length
      ? gatewayDetails.selectedInstances[0].vpc
      : gatewayDetails.routing.instance.scale_group?.target_groups?.[0]?.vpc || ''
  }
  return params
}
 
export const getSupportedResourcesQueryParams = ({
  gatewayDetails,
  accountId
}: BaseFetchDetails): AccessPointResourcesQueryParams => {
  const params: AccessPointResourcesQueryParams = {
    cloud_account_id: gatewayDetails.cloudAccount.id,
    accountIdentifier: accountId,
    region: ''
  }
  if (!_isEmpty(gatewayDetails.routing.container_svc)) {
    params.region = _defaultTo(gatewayDetails.routing.container_svc?.region, '')
    params.cluster = _defaultTo(gatewayDetails.routing.container_svc?.cluster, '')
    params.service = _defaultTo(gatewayDetails.routing.container_svc?.service, '')
  } else {
    params.region = gatewayDetails.selectedInstances?.length
      ? gatewayDetails.selectedInstances[0].region
      : _defaultTo(gatewayDetails.routing.instance.scale_group?.region, '')
    params.resource_group_name = gatewayDetails.selectedInstances[0]?.metadata?.resourceGroup
  }
  return params
}
 
export const getSecurityGroupsBodyText = (
  gatewayDetails: GatewayDetails,
  { isAzureProvider, isGcpProvider }: RuleCreationParams
): string => {
  const hasInstances = !_isEmpty(gatewayDetails.selectedInstances)
  let text = `id = ['${Utils.getConditionalResult(
    hasInstances,
    gatewayDetails.selectedInstances?.[0]?.id,
    ''
  )}']\nregions = ['${Utils.getConditionalResult(hasInstances, gatewayDetails.selectedInstances?.[0]?.region, '')}']`
 
  if (isAzureProvider) {
    text += `\nresource_groups=['${Utils.getConditionalResult(
      hasInstances,
      gatewayDetails.selectedInstances?.[0]?.metadata?.resourceGroup,
      ''
    )}']`
  }
 
  Iif (isGcpProvider) {
    text += `\nzones=['${_defaultTo(
      gatewayDetails.selectedInstances?.[0]?.metadata?.availabilityZone,
      ''
    )}']\nname='${_defaultTo(gatewayDetails.selectedInstances?.[0]?.name, '')}'`
  }
  return text
}
 
export const getAllInboundRules = (groups: Array<NetworkSecurityGroup[]>) => {
  const rules: FirewallRule[] = []
  groups.forEach(g => {
    g.forEach(s => {
      s.inbound_rules?.forEach(r => {
        rules.push(r)
      })
    })
  })
  return rules
}
 
export const getDefinedInboundRules = (rules: FirewallRule[]) => {
  return rules.filter(r => !(r.protocol === '-1' || r.from === '*'))
}
 
export const getPortConfig = (
  { from, to, protocol }: { from: number; to: number; protocol: string } = { from: 80, to: 80, protocol: 'http' }
): PortConfig => {
  return {
    protocol: protocol,
    port: from,
    action: 'forward',
    target_protocol: protocol,
    target_port: to,
    server_name: '',
    redirect_url: '',
    routing_rules: []
  }
}
 
export const getDefaultPortConfigs = (): PortConfig[] => {
  return Object.entries(portProtocolMap).map(([port, protocol]) =>
    getPortConfig({ from: Number(port), to: Number(port), protocol })
  )
}
 
export const getApSelectionList = (
  apCoreResponseList: AccessPointCore[],
  { isAwsProvider, isAzureProvider, isGcpProvider }: RuleCreationParams
): SelectOption[] => {
  return _defaultTo(apCoreResponseList, []).map(_ap => ({
    label: _ap.details?.name as string,
    value: isAwsProvider
      ? ((_ap.details as ALBAccessPointCore)?.albARN as string)
      : isAzureProvider
      ? ((_ap.details as AzureAccessPointCore).id as string)
      : isGcpProvider
      ? ((_ap.details as GCPAccessPointCore).id as string)
      : ''
  }))
}
 
export const getMatchingLoadBalancer = (
  selectedItem: SelectOption,
  apCoreResponseList: AccessPointCore[],
  { isAwsProvider }: RuleCreationParams
): AccessPointCore | undefined => {
  return apCoreResponseList?.find(_lb =>
    isAwsProvider
      ? selectedItem.value === (_lb.details as ALBAccessPointCore)?.albARN
      : selectedItem.value === (_lb.details as AzureAccessPointCore)?.id
  )
}
 
export const getLinkedAccessPoint = (
  accessPoints: AccessPoint[],
  isAwsProvider: boolean,
  matchedLb?: AccessPointCore
): AccessPoint | undefined => {
  return accessPoints?.find(_ap =>
    isAwsProvider
      ? _ap.metadata?.albArn === (matchedLb?.details as ALBAccessPointCore)?.albARN
      : (_ap.metadata?.app_gateway_id || _ap.id) === (matchedLb?.details as AzureAccessPointCore)?.id
  )
}
 
export const isValidLoadBalancer = (
  lb: AccessPointCore,
  accessPoints: AccessPoint[],
  savedAccessPoint: AccessPoint | undefined,
  { isAwsProvider, isAzureProvider, isGcpProvider }: RuleCreationParams
) => {
  let isValid = false
  if (isAwsProvider) {
    isValid = Boolean(
      lb &&
        accessPoints
          ?.map(_ap => _ap.metadata?.albArn)
          ?.filter(_i => _i)
          ?.includes((lb.details as ALBAccessPointCore)?.albARN)
    )
    Iif (!isValid) {
      isValid = Boolean(lb && savedAccessPoint?.metadata?.albArn === (lb.details as ALBAccessPointCore)?.albARN)
    }
  } else Eif (isAzureProvider) {
    isValid = Boolean(
      lb &&
        accessPoints
          ?.map(_ap => Utils.getConditionalResult(_ap.status === 'submitted', _ap.id, _ap.metadata?.app_gateway_id))
          .filter(_i => _i)
          .includes((lb.details as AzureAccessPointCore).id)
    )
    Iif (!isValid) {
      isValid = Boolean(lb && savedAccessPoint?.metadata?.app_gateway_id === (lb.details as AzureAccessPointCore)?.id)
    }
  } else if (isGcpProvider) {
    isValid = Boolean(
      lb &&
        accessPoints
          ?.map(_ap => _ap.id)
          .filter(_i => _i)
          .includes((lb.details as GCPAccessPointCore).id)
    )
    if (!isValid) {
      isValid = Boolean(lb && savedAccessPoint?.id === (lb.details as GCPAccessPointCore)?.id)
    }
  }
  return isValid
}