All files / framework/rbac PermissionsContext.tsx

82.69% Statements 43/52
76.92% Branches 30/39
75% Functions 12/16
86.96% Lines 40/46

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              1040x 1040x 1040x 1040x   1040x                               1040x             1040x 7947x             1040x                 1040x           17x 102x 102x       1040x   1040x 6x 6x   6x 6x               5x   5x       5x         5x 1x       4x 4x     4x   4x         4x     4x 4x   4x 7x       4x 2x                                 9x   9x 6x         5x     6x            
/*
 * 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, { createContext, useContext, useState, useCallback } from 'react'
import { isEqual, get, omit } from 'lodash-es'
import debounce from 'p-debounce'
import produce from 'immer'
 
import { useGetAccessControlList, PermissionCheck, AccessControl } from 'services/rbac'
 
type Permissions = Map<string, boolean>
 
export interface PermissionRequestOptions {
  skipCache?: boolean
  skipCondition?: (permissionRequest: PermissionCheck) => boolean
}
 
export interface PermissionsContextProps {
  permissions: Permissions
  requestPermission: (permissionRequest?: PermissionCheck, options?: PermissionRequestOptions) => void
  checkPermission: (permissionRequest: PermissionCheck) => boolean
  cancelRequest: (permissionRequest: PermissionCheck) => void
}
 
export const PermissionsContext = createContext<PermissionsContextProps>({
  permissions: new Map<string, boolean>(),
  requestPermission: () => void 0,
  checkPermission: () => false,
  cancelRequest: () => void 0
})
 
export function usePermissionsContext(): PermissionsContextProps {
  return useContext(PermissionsContext)
}
 
interface PermissionsProviderProps {
  debounceWait?: number
}
 
export const keysToCompare = [
  'resourceScope.accountIdentifier',
  'resourceScope.orgIdentifier',
  'resourceScope.projectIdentifier',
  'resourceType',
  'resourceIdentifier',
  'permission'
]
 
export const getStringKeyFromObjectValues = (
  permissionRequest: PermissionCheck,
  keys: string[],
  glue = '/'
): string => {
  // pick specific keys, get their values, and join with a `/`
  return keys
    .map(key => get(permissionRequest, key))
    .filter(value => value)
    .join(glue)
}
 
let pendingRequests: PermissionCheck[] = []
 
export function PermissionsProvider(props: React.PropsWithChildren<PermissionsProviderProps>): React.ReactElement {
  const { debounceWait = 50 } = props
  const [permissions, setPermissions] = useState<Permissions>(new Map<string, boolean>())
 
  const { mutate: getPermissions } = useGetAccessControlList({})
  const debouncedGetPermissions = useCallback(debounce(getPermissions, debounceWait), [getPermissions, debounceWait])
 
  // this function is called from `usePermission` hook for every resource user is interested in
  // collect all requests until `debounceWait` is triggered
  async function requestPermission(
    permissionRequest?: PermissionCheck,
    options?: PermissionRequestOptions
  ): Promise<void> {
    Iif (!permissionRequest) return
 
    const { skipCache = false, skipCondition } = options || {}
 
    // exit early if we already fetched this permission before
    // disabling this will disable caching, because it will make a fresh request and update in the store
    Iif (!skipCache && permissions.has(getStringKeyFromObjectValues(permissionRequest, keysToCompare))) {
      return
    }
 
    // exit early if user has defined a skipCondition and if it returns true
    if (skipCondition && skipCondition(permissionRequest) === true) {
      return
    }
 
    // check if this request is already queued
    Eif (!pendingRequests.find(req => isEqual(req, permissionRequest))) {
      pendingRequests.push(permissionRequest)
    }
 
    try {
      // try to fetch the permissions after waiting for `debounceWait` ms
      const res = await debouncedGetPermissions({
        permissions: pendingRequests
      })
 
      // clear pending requests after API call
      pendingRequests = []
 
      // `p-debounce` package ensure all debounced promises are resolved at this stage
      setPermissions(oldPermissions => {
        return produce(oldPermissions, draft => {
          // find the current request in aggregated response
          const hasAccess = res?.data?.accessControlList?.find((perm: AccessControl) =>
            isEqual(omit(perm, 'permitted'), permissionRequest)
          )?.permitted
 
          // update current request in the map, only if response matches request
          if (typeof hasAccess === 'boolean') {
            draft.set(getStringKeyFromObjectValues(permissionRequest, keysToCompare), hasAccess)
          }
          // if hasAccess is undefined, it means :
          // 1. either we had a race condition, and the response is for a previous request.
          //    in that case, dont overwrite the old data
          // 2. or the request was invalid (permission doesn't exist).
          //    in that case, assume default as false
        })
      })
    } catch (err) {
      // clear pending requests even if api fails
      pendingRequests = []
      if (process.env.NODE_ENV === 'test') throw err
    }
  }
 
  function checkPermission(permissionRequest: PermissionCheck): boolean {
    const permission = permissions.get(getStringKeyFromObjectValues(permissionRequest, keysToCompare))
    // only use map value if it's defined. absence of data doesn't mean permission denied.
    if (typeof permission === 'boolean') return permission
    else return true
  }
 
  function cancelRequest(permissionRequest: PermissionCheck): void {
    // remove any matching requests
    pendingRequests = pendingRequests.filter(req => !isEqual(req, permissionRequest))
  }
 
  return (
    <PermissionsContext.Provider value={{ permissions, requestPermission, checkPermission, cancelRequest }}>
      {props.children}
    </PermissionsContext.Provider>
  )
}