All files / modules/20-rbac/utils utils.tsx

75.47% Statements 80/106
54.35% Branches 50/92
80% Functions 16/20
72.53% Lines 66/91

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              446x   446x                   446x           446x 446x       446x         446x 446x   446x 446x 446x 446x     446x 446x 446x     446x 46x                       46x       446x 446x 446x 446x 446x 446x                       446x               1x                           1x       446x     4449x 4254x             446x       33x             33x             446x       9x   9x                                           446x         9x     9x       9x   9x                                                                                 446x 135x 92x   43x   446x 32x     446x               446x 4x   4x                                     446x                                       446x             1579x                         1579x 24x           1555x                       1555x     446x 36x     446x                               446x 53x   53x 25x     28x        
/*
 * 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 React, { ReactNode } from 'react'
import type { IconName, ModalErrorHandlerBinding, SelectOption } from '@wings-software/uicore'
import { defaultTo, pick } from 'lodash-es'
import type { StringsMap } from 'stringTypes'
import type {
  AccessControlCheckError,
  RoleAssignmentMetadataDTO,
  UserMetadataDTO,
  Scope as CDScope,
  UserGroupDTO,
  Failure
} from 'services/cd-ng'
import { Scope } from '@common/interfaces/SecretsInterface'
import type {
  Assignment,
  RoleOption,
  ResourceGroupOption
} from '@rbac/modals/RoleAssignmentModal/views/UserRoleAssigment'
import { RbacResourceGroupTypes } from '@rbac/constants/utils'
import RBACTooltip from '@rbac/components/RBACTooltip/RBACTooltip'
import type { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import type { FeatureRequest } from 'framework/featureStore/featureStoreUtil'
import type { PermissionsRequest } from '@rbac/hooks/usePermission'
import { FeatureWarningTooltip } from '@common/components/FeatureWarning/FeatureWarningWithTooltip'
import type { StringKeys, UseStringsReturn } from 'framework/strings'
import type { ProjectSelectOption } from '@audit-trail/components/FilterDrawer/FilterDrawer'
import type { RbacMenuItemProps } from '@rbac/components/MenuItem/MenuItem'
 
export const DEFAULT_RG = '_all_resources_including_child_scopes'
export const PROJECT_DEFAULT_RG = '_all_project_level_resources'
 
export enum PrincipalType {
  USER = 'USER',
  USER_GROUP = 'USER_GROUP',
  SERVICE = 'SERVICE_ACCOUNT'
}
 
export enum SelectionType {
  ALL = 'ALL',
  SPECIFIED = 'SPECIFIED'
}
 
export const getRoleIcon = (roleIdentifier: string): IconName => {
  switch (roleIdentifier) {
    case '_account_viewer':
    case '_organization_viewer':
    case '_project_viewer':
      return 'viewerRole'
    case '_account_admin':
    case '_organization_admin':
    case '_project_admin':
      return 'adminRole'
    case '_pipeline_executor':
      return 'pipeline-executor'
    default:
      return 'customRole'
  }
}
 
export enum InvitationStatus {
  USER_INVITED_SUCCESSFULLY = 'USER_INVITED_SUCCESSFULLY',
  USER_ADDED_SUCCESSFULLY = 'USER_ADDED_SUCCESSFULLY',
  USER_ALREADY_ADDED = 'USER_ALREADY_ADDED',
  USER_ALREADY_INVITED = 'USER_ALREADY_INVITED',
  FAIL = 'FAIL'
}
 
interface HandleInvitationResponse {
  responseType: InvitationStatus
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string
  showSuccess: (message: string | ReactNode, timeout?: number, key?: string) => void
  modalErrorHandler?: ModalErrorHandlerBinding
  onSubmit?: () => void
  onUserAdded?: () => void
}
 
export const handleInvitationResponse = ({
  responseType,
  getString,
  showSuccess,
  modalErrorHandler,
  onSubmit,
  onUserAdded
}: HandleInvitationResponse): void => {
  switch (responseType) {
    case InvitationStatus.USER_INVITED_SUCCESSFULLY: {
      onSubmit?.()
      return showSuccess(getString('rbac.usersPage.invitationSuccess'))
    }
    case InvitationStatus.USER_ADDED_SUCCESSFULLY: {
      onUserAdded?.()
      return showSuccess(getString('rbac.usersPage.userAddedSuccess'))
    }
    case InvitationStatus.USER_ALREADY_ADDED:
      return showSuccess(getString('rbac.usersPage.userAlreadyAdded'))
    case InvitationStatus.USER_ALREADY_INVITED:
      return showSuccess(getString('rbac.usersPage.userAlreadyInvited'))
    default:
      return modalErrorHandler?.showDanger(getString('rbac.usersPage.invitationError'))
  }
}
 
export const getPermissionRequestFromProps = (
  permission?: RbacMenuItemProps['permission']
): PermissionsRequest | undefined => {
  if (permission) {
    return {
      ...pick(permission, ['resourceScope', 'resource', 'options']),
      permissions: [permission.permission]
    } as PermissionsRequest
  }
}
 
export const getScopeBasedDefaultResourceGroup = (
  scope: Scope,
  getString: UseStringsReturn['getString']
): SelectOption => {
  switch (scope) {
    case Scope.PROJECT:
      return {
        label: getString('rbac.allProjectResources'),
        value: '_all_project_level_resources'
      }
    default:
      return {
        label: getString('rbac.allResourcesIncludingChildScopes'),
        value: DEFAULT_RG
      }
  }
}
 
export const getScopeLevelManagedResourceGroup = (
  scope: Scope,
  getString: UseStringsReturn['getString']
): SelectOption => {
  switch (scope) {
    case Scope.ACCOUNT:
      return {
        label: getString('rbac.allAccountResources'),
        value: '_all_account_level_resources'
      }
    case Scope.ORG:
      return {
        label: getString('rbac.allOrgResources'),
        value: '_all_organization_level_resources'
      }
    case Scope.PROJECT:
      return {
        label: getString('rbac.allProjectResources'),
        value: '_all_project_level_resources'
      }
    default:
      return {
        label: getString('rbac.allResources'),
        value: '_all_resources'
      }
  }
}
 
export const getScopeBasedDefaultAssignment = (
  scope: Scope,
  getString: UseStringsReturn['getString'],
  isCommunity: boolean
): Assignment[] => {
  Iif (isCommunity) {
    return []
  } else {
    const resourceGroup: ResourceGroupOption = {
      managedRoleAssignment: true,
      ...getScopeLevelManagedResourceGroup(scope, getString)
    }
    switch (scope) {
      case Scope.ACCOUNT:
        return [
          {
            role: {
              label: getString('common.accViewer'),
              value: '_account_viewer',
              managed: true,
              managedRoleAssignment: true
            },
            resourceGroup
          }
        ]
      case Scope.ORG:
        return [
          {
            role: {
              label: getString('common.orgViewer'),
              value: '_organization_viewer',
              managed: true,
              managedRoleAssignment: true
            },
            resourceGroup
          }
        ]
      case Scope.PROJECT:
        return [
          {
            role: {
              label: getString('common.projectViewer'),
              value: '_project_viewer',
              managed: true,
              managedRoleAssignment: true
            },
            resourceGroup
          }
        ]
      default:
        return []
    }
  }
}
 
export const isAssignmentFieldDisabled = (value: RoleOption | ResourceGroupOption): boolean => {
  if (value.assignmentIdentifier || value.managedRoleAssignment) {
    return true
  }
  return false
}
export const isDynamicResourceSelector = (value: string | string[]): boolean => {
  return value === RbacResourceGroupTypes.DYNAMIC_RESOURCE_SELECTOR
}
 
export const isScopeResourceSelector = (value: string): boolean => {
  return value === RbacResourceGroupTypes.SCOPE_RESOURCE_SELECTOR
}
 
export interface ErrorHandlerProps {
  data: Failure | AccessControlCheckError | Error
}
 
export const getAssignments = (roleBindings: RoleAssignmentMetadataDTO[]): Assignment[] => {
  return (
    roleBindings?.map(roleAssignment => {
      return {
        role: {
          label: roleAssignment.roleName,
          value: roleAssignment.roleIdentifier,
          managed: roleAssignment.managedRole,
          assignmentIdentifier: roleAssignment.identifier,
          managedRoleAssignment: roleAssignment.managedRoleAssignment
        },
        resourceGroup: {
          label: roleAssignment.resourceGroupName || '',
          value: roleAssignment.resourceGroupIdentifier || '',
          managedRoleAssignment: roleAssignment.managedRoleAssignment,
          assignmentIdentifier: roleAssignment.identifier
        }
      }
    }) || []
  )
}
 
export const isNewRoleAssignment = (assignment: Assignment): boolean => {
  return !(assignment.role.assignmentIdentifier || assignment.resourceGroup.assignmentIdentifier)
}
 
interface FeatureProps {
  featureRequest: FeatureRequest
  isPermissionPrioritized?: boolean
}
 
interface TooltipProps {
  permissionRequest?: Omit<PermissionsRequest, 'permissions'> & { permission: PermissionIdentifier }
  featureProps?: FeatureProps
  canDoAction: boolean
  featureEnabled: boolean
}
 
interface TooltipReturn {
  tooltip?: React.ReactElement
}
 
export function getTooltip({
  permissionRequest,
  featureProps,
  canDoAction,
  featureEnabled
}: TooltipProps): TooltipReturn {
  // if permission check override the priorirty
  Iif (featureProps?.isPermissionPrioritized && permissionRequest && !canDoAction) {
    return {
      tooltip: (
        <RBACTooltip
          permission={permissionRequest.permission}
          resourceType={permissionRequest.resource.resourceType}
          resourceScope={permissionRequest.resourceScope}
        />
      )
    }
  }
 
  // feature check by default take priority
  if (featureProps?.featureRequest && !featureEnabled) {
    return {
      tooltip: <FeatureWarningTooltip featureName={featureProps?.featureRequest.featureName} />
    }
  }
 
  // permission check
  Iif (permissionRequest && !canDoAction) {
    return {
      tooltip: (
        <RBACTooltip
          permission={permissionRequest.permission}
          resourceType={permissionRequest.resource.resourceType}
          resourceScope={permissionRequest.resourceScope}
        />
      )
    }
  }
 
  return {}
}
 
export const getUserName = (user: UserMetadataDTO): string => {
  return defaultTo(user.name, user.email)
}
 
export const generateScopeList = (org: string, projects: ProjectSelectOption[], accountId: string): CDScope[] => {
  if (projects.length > 0) {
    return projects.map(project => ({
      accountIdentifier: accountId,
      orgIdentifier: project.orgIdentifier,
      projectIdentifier: project.value as string
    }))
  }
  return [
    {
      accountIdentifier: accountId,
      orgIdentifier: org as string
    }
  ]
}
 
export const getUserGroupActionTooltipText = (userGroup: UserGroupDTO): StringKeys | undefined => {
  const { ssoLinked, externallyManaged } = userGroup
 
  if (ssoLinked) {
    return 'rbac.userDetails.linkToSSOProviderModal.btnDisabledTooltipText'
  }
 
  Iif (externallyManaged) {
    return 'rbac.unableToEditSCIMMembership'
  }
}