IdentityCommand.CEM.psm1

# .ExternalHelp IdentityCommand.CEM-help.xml
function Connect-CEMTenant {

    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Subdomain')]
    param(

        #subdomain
        [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'Subdomain')]
        [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'SubdomainCredential')]
        [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'SubdomainSAML')]
        [ValidateNotNullOrEmpty()]
        [Alias('subdomain')]
        [String]$tenant_subdomain,

        #tenant_url
        [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'URL')]
        [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'URLCredential')]
        [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'URLSAML')]
        [ValidateNotNullOrEmpty()]
        [Alias('cem_url')]
        [String]$tenant_url,

        #Credential used to authenticate to CyberArk Identity. Authentication is performed even if an active IdentityCommand session is found, replacing it
        [parameter(Mandatory = $true, ParameterSetName = 'SubdomainCredential')]
        [parameter(Mandatory = $true, ParameterSetName = 'URLCredential')]
        [ValidateNotNullOrEmpty()]
        [PSCredential]$Credential,

        #Authenticate as a service user via New-IDPlatformToken (OAuth client_credentials) instead of the interactive New-IDSession
        [parameter(ParameterSetName = 'SubdomainCredential')]
        [parameter(ParameterSetName = 'URLCredential')]
        [Switch]$PlatformToken,

        #SAML assertion used to authenticate to CyberArk Identity. Authentication is performed even if an active IdentityCommand session is found, replacing it
        [parameter(Mandatory = $true, ParameterSetName = 'SubdomainSAML')]
        [parameter(Mandatory = $true, ParameterSetName = 'URLSAML')]
        [ValidateNotNullOrEmpty()]
        [String]$SAMLResponse

    )

    begin {

        $IDSession = Get-IDSession
        $HaveSession = $null -ne $IDSession.tenant_url
        $AuthRequested = $PSBoundParameters.ContainsKey('Credential') -or $PSBoundParameters.ContainsKey('SAMLResponse')

        if ($HaveSession -and $AuthRequested) {
            Write-Verbose 'Authentication parameters were supplied; authenticating and replacing the existing IdentityCommand session'
        }

    }#begin

    process {

        $UsingSubdomain = $PSCmdlet.ParameterSetName -like 'Subdomain*'

        #Cloud Visibility is served from a tenant-scoped gateway (<subdomain>-cem.cyberark.cloud), not
        #the regional host platform discovery reports for the cem service key. Discovery is still used
        #to resolve the CyberArk Identity URL authentication runs against.
        $ServiceUrl = $null

        if ($UsingSubdomain) {

            $ServiceUrl = Resolve-ServiceUrl -Service cem -Subdomain $tenant_subdomain
            $tenant_url = "https://$tenant_subdomain-cem.cyberark.cloud"

        } else {

            #Ensure URL is in expected format - remove trailing slash if provided in Url
            $tenant_url = $tenant_url -replace '/$', ''

            if ($AuthRequested) {
                $Subdomain = ([System.Uri]$tenant_url).Host.Split('.')[0] -replace '-cem$', ''
                $ServiceUrl = Resolve-ServiceUrl -Service cem -Subdomain $Subdomain
            }

        }

        if ($AuthRequested -or (-not $HaveSession)) {

            if (-not $AuthRequested) {
                throw 'Authenticate with New-IDSession or New-IDPlatformToken, or supply -Credential, and try again'
            }

            $IdentityUrl = $ServiceUrl.IdentityUrl

            if ($PSCmdlet.ShouldProcess($IdentityUrl, 'Authenticate to CyberArk Identity')) {

                if ($PSCmdlet.ParameterSetName -like '*SAML') {
                    $null = New-IDSession -tenant_url $IdentityUrl -SAMLResponse $SAMLResponse
                } elseif ($PlatformToken) {
                    $null = New-IDPlatformToken -tenant_url $IdentityUrl -Credential $Credential
                } else {
                    $null = New-IDSession -tenant_url $IdentityUrl -Credential $Credential
                }

                $IDSession = Get-IDSession

            }

        }

        #Make the CyberArk Identity Session available in the IdentityCommand.CEM scope
        foreach ($key in $IDSession.keys) {
            if ($null -ne $IDSession[$key]) {
                $ISPSSSession[$key] = $IDSession[$key]
            }
        }

        #Set the Cloud Visibility URL in the session data
        $ISPSSSession.tenant_url = $tenant_url

    }#process

    end { }#end

}

# .ExternalHelp IdentityCommand.CEM-help.xml
function Find-CEMWorkspaceDelegation {
    [CmdletBinding()]
    param(
        [parameter(
            Mandatory = $false,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateSet('AWS', 'AZURE', 'GCP')]
        [String[]]$cloud_platforms,

        [parameter(
            Mandatory = $false,
            ValueFromPipelinebyPropertyName = $true
        )]
        [String[]]$workspace_names,

        [parameter(
            Mandatory = $false,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateSet('account', 'root', 'ou', 'directory', 'management_group', 'subscription', 'gcp_organization', 'folder', 'project')]
        [String[]]$workspace_types,

        [parameter(
            Mandatory = $false,
            ValueFromPipelinebyPropertyName = $true
        )]
        [String[]]$owners,

        [parameter(
            Mandatory = $false,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateLength(3, [int]::MaxValue)]
        [String]$searchString,

        [parameter(
            Mandatory = $false,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateRange(0, [int]::MaxValue)]
        [int]$offset,

        [parameter(
            Mandatory = $false,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateRange(1, [int]::MaxValue)]
        [int]$limit
    )

    begin { }#begin

    process {

        $URI = "$($ISPSSSession.tenant_url)/api/delegations/workspace/search"

        $Filters = $PSBoundParameters | Get-Parameter -ParametersToKeep cloud_platforms, workspace_names, workspace_types, owners

        $body = $PSBoundParameters | Get-Parameter -ParametersToRemove cloud_platforms, workspace_names, workspace_types, owners

        if ($Filters.Keys.Count -gt 0) {
            $body['filters'] = $Filters
        }

        if (-not $PSBoundParameters.ContainsKey('offset')) { $body['offset'] = 0 }
        if (-not $PSBoundParameters.ContainsKey('limit')) { $body['limit'] = 50 }

        $result = Invoke-IDRestMethod -Uri $URI -Method POST -Body ($body | ConvertTo-Json -Depth 4)

        if ($null -ne $result) {

            Get-PagedResult -InitialResult $result -URI $URI -Style Offset -ResultProperty items `
                -TotalResponseKey count -OffsetRequestKey offset -Method POST -BodyTemplate $body

        }

    }#process

    end { }#end

}

# .ExternalHelp IdentityCommand.CEM-help.xml
function Get-CEMModuleData {

    [CmdletBinding()]
    param()

    begin { }#begin

    process {

        #Calculate the time elapsed since the start of the session and include in return data
        if ($null -ne $ISPSSSession.StartTime) {
            $ISPSSSession.ElapsedTime = '{0:HH:mm:ss}' -f ([datetime]$($(Get-Date) - $($ISPSSSession.StartTime)).Ticks)
        } else { $ISPSSSession.ElapsedTime = $null }

        #Deep Copy the $ISPSSSession session object and return as IdCmd Session type.
        Get-SessionClone -InputObject $ISPSSSession | Add-CustomType -Type IdCmd.Session

    }#process

    end { }#end

}

# .ExternalHelp IdentityCommand.CEM-help.xml
function Get-CEMWorkspaceDelegation {
    [CmdletBinding()]
    param(
        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateSet('AWS', 'AZURE', 'GCP')]
        [String]$cloud_platform,

        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [String]$workspace_id,

        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateSet('account', 'root', 'ou', 'directory', 'management_group', 'subscription', 'gcp_organization', 'folder', 'project')]
        [String]$workspace_type
    )

    begin { }#begin

    process {

        $URI = "$($ISPSSSession.tenant_url)/api/delegations/workspace/details"

        $body = $PSBoundParameters | Get-Parameter

        #Fetching delegation details is a read - the API models it as a POST because the lookup key
        #is a compound object, not because anything changes.
        $result = Invoke-IDRestMethod -Uri $URI -Method POST -Body ($body | ConvertTo-Json -Depth 4)

        if ($null -ne $result) {

            $result

        }

    }#process

    end { }#end

}

# .ExternalHelp IdentityCommand.CEM-help.xml
function New-CEMDelegateDefinition {
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Function builds a definition object and does not change state')]
    [CmdletBinding()]
    [OutputType('IdCmd.CEM.Definition.Delegate')]
    param(
        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateSet('User', 'Role')]
        [String]$entity_type,

        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [String]$entity_name,

        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [String]$user_principal,

        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateSet('workspace_admin', 'business_owner')]
        [String[]]$tags,

        [parameter(
            Mandatory = $false,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [String]$entity_id,

        [parameter(
            Mandatory = $false,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [String]$directory_id,

        [parameter(
            Mandatory = $false,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [String]$directory_name,

        [parameter(
            Mandatory = $false,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [String]$entity_email,

        [parameter(
            Mandatory = $false,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [String]$service_type,

        [parameter(
            Mandatory = $false,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [String]$entity_internal_id,

        [parameter(Mandatory = $false)]
        [psobject[]]$DelegateDefinition
    )

    begin { }#begin

    process {

        $Delegate = $PSBoundParameters | Get-Parameter -ParametersToRemove DelegateDefinition

        $Output = @($DelegateDefinition) + @([pscustomobject]$Delegate) | Where-Object { $null -ne $_ }

        $Output | Add-CustomType -Type 'IdCmd.CEM.Definition.Delegate'

    }#process

    end { }#end

}

# .ExternalHelp IdentityCommand.CEM-help.xml
function New-CEMWorkspaceDefinition {
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Function builds a definition object and does not change state')]
    [CmdletBinding()]
    [OutputType('IdCmd.CEM.Definition.Workspace')]
    param(
        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [String]$organization,

        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateSet('account', 'root', 'ou', 'directory', 'management_group', 'subscription', 'gcp_organization', 'folder', 'project')]
        [String]$workspace_type,

        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [String]$workspace_id,

        [parameter(
            Mandatory = $false,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [String]$workspace_name,

        [parameter(Mandatory = $false)]
        [psobject[]]$WorkspaceDefinition
    )

    begin { }#begin

    process {

        $Workspace = $PSBoundParameters | Get-Parameter -ParametersToRemove WorkspaceDefinition

        $Output = @($WorkspaceDefinition) + @([pscustomobject]$Workspace) | Where-Object { $null -ne $_ }

        $Output | Add-CustomType -Type 'IdCmd.CEM.Definition.Workspace'

    }#process

    end { }#end

}

# .ExternalHelp IdentityCommand.CEM-help.xml
function New-CEMWorkspaceDelegation {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateSet('AWS', 'AZURE', 'GCP')]
        [String]$cloud_platform,

        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateCount(1, 5)]
        [psobject[]]$WorkspaceDefinition,

        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateCount(1, 10)]
        [psobject[]]$DelegateDefinition
    )

    begin { }#begin

    process {

        $URI = "$($ISPSSSession.tenant_url)/api/delegations/workspace/$cloud_platform"

        $body = [ordered]@{
            workspaces = @($WorkspaceDefinition)
            entities   = @($DelegateDefinition)
        }

        if ($PSCmdlet.ShouldProcess($cloud_platform, 'Add workspace delegation')) {

            #The response carries no body - the created delegation's id is not returned here, only
            #from a later Find-CEMWorkspaceDelegation or Get-CEMWorkspaceDelegation lookup.
            Invoke-IDRestMethod -Uri $URI -Method POST -Body ($body | ConvertTo-Json -Depth 8)

        }

    }#process

    end { }#end

}

# .ExternalHelp IdentityCommand.CEM-help.xml
function Remove-CEMWorkspaceDelegation {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateRange(1, [int]::MaxValue)]
        [int]$id
    )

    begin { }#begin

    process {

        $URI = "$($ISPSSSession.tenant_url)/api/delegations/workspace/delegation/$id"

        #Deletes every delegate from every workspace the delegation covers - there is no partial
        #removal, only deleting the whole delegation.
        if ($PSCmdlet.ShouldProcess($id, 'Remove workspace delegation')) {

            Invoke-IDRestMethod -Uri $URI -Method DELETE

        }

    }#process

    end { }#end

}

# .ExternalHelp IdentityCommand.CEM-help.xml
function Set-CEMWorkspaceDelegation {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateRange(1, [int]::MaxValue)]
        [int]$id,

        [parameter(
            Mandatory = $true,
            ValueFromPipelinebyPropertyName = $true
        )]
        [ValidateCount(1, 10)]
        [psobject[]]$DelegateDefinition
    )

    begin { }#begin

    process {

        $URI = "$($ISPSSSession.tenant_url)/api/delegations/workspace/update/$id"

        #Fully replaces the delegates on every workspace the delegation covers - the workspaces
        #themselves are not part of this request and are left as they are.
        $body = [ordered]@{
            entities = @($DelegateDefinition)
        }

        if ($PSCmdlet.ShouldProcess($id, 'Update workspace delegation')) {

            Invoke-IDRestMethod -Uri $URI -Method PUT -Body ($body | ConvertTo-Json -Depth 8)

        }

    }#process

    end { }#end

}

#Copy IdentityCommand's private helpers into this module: this module's functions call them, and
#the argument completer registrations below do so at import time.
#Each copy is created from the function definition, so it runs in this module's scope and uses this
#module's $ISPSSSession, whether IdentityCommand loaded from source or from its combined psm1.
#Resolve a single IdentityCommand module: with more than one version loaded, Get-Module returns
#an array.
$Module = Get-Module -Name IdentityCommand | Sort-Object Version -Descending | Select-Object -First 1

if ($null -eq $Module) {
    throw 'The IdentityCommand module is not loaded. Import IdentityCommand and try again.'
}

& $Module { Get-ChildItem -Path Function: } |

    Where-Object { $_.ModuleName -eq $Module.Name -and -not $Module.ExportedFunctions.ContainsKey($_.Name) } |

    ForEach-Object {

        . ([scriptblock]::Create("function $($_.Name) {$($_.Definition)}"))

    }

#region Registration

#Delegation ids are only known once a search has been run - offer them from the most recent
#Find-CEMWorkspaceDelegation results, labelled by workspace name.
Register-ArgumentCompleter -ParameterName 'id' -ScriptBlock (
    Get-ArgumentCompleter -RetrievalCommand 'Find-CEMWorkspaceDelegation' -ValueProperty 'id' -LabelProperty 'workspace_name'
) -CommandName 'Set-CEMWorkspaceDelegation', 'Remove-CEMWorkspaceDelegation'

#endregion Registration

# Script scope session object for session data
$ISPSSSession = [ordered]@{
    tenant_url         = $null
    User               = $null
    TenantId           = $null
    SessionId          = $null
    WebSession         = $null
    StartTime          = $null
    ElapsedTime        = $null
    LastCommand        = $null
    LastCommandTime    = $null
    LastCommandResults = $null
    LastError          = $null
    LastErrorTime      = $null
} | Add-CustomType -Type IdCmd.Session

New-Variable -Name ISPSSSession -Value $ISPSSSession -Scope Script -Force