functions/roleManagement/roleAssignments/Test-AzurePIMroleAssignment.ps1

function Test-AzurePIMroleAssignment
{
    <#
        .SYNOPSIS
            Test desired configuration against a Tenant.
        .DESCRIPTION
            Compare current configuration of a resource type with the desired configuration.
            Return a result object with the required changes and actions.
    #>

    [CmdletBinding()]
    Param (
        [System.Management.Automation.PSCmdlet]
        $Cmdlet = $PSCmdlet
    )
    
    begin
    {
        $resourceName = "roleAssignments"
        Test-AzureConnection
        $secureStringToken = (Get-AzAccessToken -AsSecureString -ResourceUrl $script:apiBaseUrl).Token
        $token = [System.Net.NetworkCredential]::new('', $secureStringToken).Password
        $tenant = Get-AzTenant -TenantId (Get-AzContext).Tenant.Id
    }
    process
    {
        $definitions = $script:desiredConfiguration[$resourceName]

        foreach ($definition in $definitions) {
            foreach ($property in $definition.Properties()) {
                if ($definition.$property.GetType().Name -eq "String") {
                    $definition.$property = Resolve-String -Text $definition.$property
                }
            }

            $result = @{
                Tenant = $tenant.Name
                TenantId = $tenant.Id
                ResourceType = 'roleAssignment'
                ResourceName = "$($definition.principalReference)_$($definition.roleReference)_$($definition.scopeReference)"
                DesiredConfiguration = $definition
            }
            
            try {

                $subscriptionId = Resolve-Subscription -InputReference $definition.subscriptionReference
                $roleDefinitionId = Resolve-AzureRoleDefinition -InputReference $definition.roleReference -SubscriptionId $subscriptionId.trimStart("/") -SearchInDesiredConfiguration
                switch ($definition.principalType) {
                    "group" {$principalId=Resolve-Group -InputReference $definition.principalReference}
                    "user"  {$principalId=Resolve-User -InputReference $definition.principalReference}
                }

                switch ($definition.scopeType) {
                    "subscription" {$scopeId = $subscriptionId}
                    "resourceGroup" {$scopeId = Resolve-ResourceGroup -InputReference $definition.scopeReference -SubscriptionId $subscriptionId}
                    "resource" {$scopeId = $subscriptionId + $definition.scopeReference}
                }

                switch ($definition.type) {
                    "eligible" {
                        try {
                            $resource = @()
                            $resource += (Invoke-RestMethod -Method GET -Uri ("$($script:apiBaseUrl)$($scopeId)/providers/Microsoft.Authorization/roleEligibilitySchedules?`$filter=principalId eq '{0}'&api-version=2020-10-01-preview" -f $principalId) -Headers @{"Authorization"="Bearer $($token)"}).value | Where-Object {$_.properties.roleDefinitionId -eq $roleDefinitionId -and $_.properties.scope -eq $scopeId}
                        }
                        catch {
                            $resource = @()
                        }
                    }
                    
                    "active" {
                        try {
                            $resource = @()
                            $resource += (Invoke-RestMethod -Method GET -Uri ("$($script:apiBaseUrl)$($scopeId.TrimStart("/"))/providers/Microsoft.Authorization/roleAssignments?`$filter=principalId eq '{0}'&api-version=2020-10-01-preview" -f $principalId) -Headers @{"Authorization"="Bearer $($token)"}).value | Where-Object {$_.properties.roleDefinitionId -eq $roleDefinitionId -and $_.properties.scope -eq $scopeId}
                        }
                        catch {
                            $resource = @()
                        }
                    }
                }
            }
            catch {
                Write-PSFMessage -Level Warning -String 'AzurePIM.Error.QueryWithFilterFailed' -StringValues $filter -Tag 'failed'
                $exception = New-Object System.Data.DataException("Query with filter $filter against Microsoft Graph failed. Error: $_")
                $errorID = 'QueryWithFilterFailed'
                $category = [System.Management.Automation.ErrorCategory]::NotSpecified
                $recordObject = New-Object System.Management.Automation.ErrorRecord($exception, $errorID, $category, $Cmdlet)
                $cmdlet.ThrowTerminatingError($recordObject)
            }
            
            switch ($resource.Count) {
                0 {
                    if ($definition.present) {                    
                        $result = New-TestResult @result -ActionType "Create"
                    }
                    else {                    
                        $result = New-TestResult @result -ActionType "NoActionRequired"
                    }
                }
                1 {
                    $result["AzureResource"] = $resource
                    if ($definition.present) {
                        $changes = @()
                        if ($definition.type -eq "eligible") {
                            foreach ($property in ($definition.Properties() | Where-Object {$_ -notin "displayName", "present", "sourceConfig"})) {
                                $change = [PSCustomObject] @{
                                    Property = $property                                        
                                    Actions = $null
                                }
                                switch ($property) {
                                    "startDateTime" {
                                        if ((New-TimeSpan -Start $resource.properties.startDateTime -End $definition.startDateTime).TotalDays -ge 1) {
                                            $change.Actions = @{"Set" = $definition.$property}
                                        }
                                    }
                                    
                                    "endDateTime" {
                                        if ($definition.expirationType -eq "AfterDateTime") {
                                            if ($definition.endDateTime -ne $resource.properties.endDateTime) {
                                                $change.Actions = @{"Set" = $definition.$property}
                                            }
                                        }
                                    }

                                    "expirationType" {
                                        if ($definition.expirationType -eq "noExpiration" -and $resource.properties.endDateTime) {
                                            $change.Actions = @{"Set" = $definition.$property}
                                        }
                                        if ($definition.expirationType -ne "noExpiration" -and -not ($resource.properties.endDateTime)) {
                                            $change.Actions = @{"Set" = $definition.$property}
                                        }
                                    }
                                }
                                
                                if ($change.Actions) {$changes += $change}
                            }    
                        }
                        
                        if ($changes.count -gt 0) { $result = New-TestResult @result -Changes $changes -ActionType "Update"}
                        else { $result = New-TestResult @result -ActionType "NoActionRequired" }
                    }
                    else {
                        $result = New-TestResult @result -ActionType "Delete"
                    }
                }
                default {
                    Write-PSFMessage -Level Warning -String 'AzurePIM.Test.MultipleResourcesError' -StringValues $resourceName, $result.ResourceName -Tag 'failed'
                    $exception = New-Object System.Data.DataException("Query returned multiple results. Cannot decide which resource to test.")
                    $errorID = 'MultipleResourcesError'
                    $category = [System.Management.Automation.ErrorCategory]::NotSpecified
                    $recordObject = New-Object System.Management.Automation.ErrorRecord($exception, $errorID, $category, $Cmdlet)
                    $cmdlet.ThrowTerminatingError($recordObject)
                }
            }
            
            $result
        }
    }
}