diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d77bf17..d5082e3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -61,6 +61,16 @@ jobs: - uses: actions/checkout@v7 - name: Get Build Scripts run: git clone --depth 1 --branch $env:BUILD_REF https://github.com/pspete/pspete.Build build + # CurrentUser modules are cached; install.ps1 and help.ps1 skip those found. + # The key rolls monthly so newer module versions are picked up. + - name: Cache Month + id: month + run: '"month=$(Get-Date -Format yyyy-MM)" >> $env:GITHUB_OUTPUT' + - name: Cache Modules + uses: actions/cache@v6 + with: + path: ~/Documents/PowerShell/Modules + key: psmodules-test-${{ steps.month.outputs.month }} - name: Install Dependencies run: ./build/install.ps1 # Help is generated locally with platyPS 0.14 and committed; PlatyPS 1.x output regresses it. @@ -139,15 +149,19 @@ jobs: - name: PowerShell os: windows-latest shell: pwsh + modules: ~/Documents/PowerShell/Modules - name: WindowsPowerShell os: windows-latest shell: powershell + modules: ~/Documents/WindowsPowerShell/Modules - name: Linux os: ubuntu-latest shell: pwsh + modules: ~/.local/share/powershell/Modules #- name: Mac # os: macos-latest # shell: pwsh + # modules: ~/.local/share/powershell/Modules defaults: run: shell: ${{ matrix.shell }} @@ -162,18 +176,16 @@ jobs: with: name: module path: ${{ env.MODULE_NAME }} - # Windows PowerShell 5.1 has no PSResourceGet; install.ps1 skips its ~60s bootstrap when the module is found. - # The key rolls monthly so a newer PSResourceGet is picked up. + # CurrentUser modules are cached per leg; install.ps1 skips those found, including the PSResourceGet bootstrap on 5.1. + # The key rolls monthly so newer module versions are picked up. - name: Cache Month id: month - if: matrix.shell == 'powershell' run: '"month=$(Get-Date -Format yyyy-MM)" >> $env:GITHUB_OUTPUT' - - name: Cache PSResourceGet - if: matrix.shell == 'powershell' + - name: Cache Modules uses: actions/cache@v6 with: - path: ~/Documents/WindowsPowerShell/Modules/Microsoft.PowerShell.PSResourceGet - key: psresourceget-winps-${{ steps.month.outputs.month }} + path: ${{ matrix.modules }} + key: psmodules-${{ matrix.name }}-${{ steps.month.outputs.month }} - name: Install Dependencies run: ./build/install.ps1 - name: Test Built Module diff --git a/CHANGELOG.md b/CHANGELOG.md index dadf327..dab7af0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,32 @@ All notable changes to this project will be documented in this file. -## Unreleased +## Unreleased (major) -- N/A +1.0.0: from this release, IdentityCommand follows semantic versioning, so breaking changes come only in a major release. + +### Added + +- Support for companion modules (`IdentityCommand.SCA`, `IdentityCommand.SIA` and the others) to connect on + first use, finding their service url by platform discovery and using the `IdentityCommand` session, with no + connection step after `New-IDSession` or `New-IDPlatformToken`. +- `Get-IDSession` reports the tenant's shared services `Subdomain`, read from the sign-in token. +- `New-IDSession` and `New-IDPlatformToken` accept the tenant's shared services subdomain (`-subdomain sometenant`) + in place of `-tenant_url`, finding the Identity URL by platform discovery. + +### Changed + +- `New-IDSession` and `New-IDPlatformToken` end any existing session when they start, so a failed sign-in + leaves no session. Previously, the earlier user and start time were kept, without a usable web session. +- CI caches the PowerShell modules it installs, so dependency installs skip the PowerShell Gallery on a cache hit. + +### Fixed + +- A failed request now reports its own error. Previously, a failed sign-in (for example, to a mistyped or unreachable tenant URL) first + reported `Cannot find a variable with the name 'IDSession'`, and an error response with no body reported an empty message. +- Requests sent with an `Accept` header now succeed: Secrets Manager, SecureAI and Secrets Hub commands previously failed with + `A parameter cannot be found that matches parameter name 'Accept'`. The header applies to that request only, and is not + left on the shared session. ## [0.8.0] - 2026-10-08 diff --git a/IdentityCommand/IdentityCommand.psm1 b/IdentityCommand/IdentityCommand.psm1 index d0e6797..35b241f 100644 --- a/IdentityCommand/IdentityCommand.psm1 +++ b/IdentityCommand/IdentityCommand.psm1 @@ -65,6 +65,7 @@ $ISPSSSession = [ordered]@{ User = $null TenantId = $null SessionId = $null + Subdomain = $null WebSession = $null StartTime = $null ElapsedTime = $null diff --git a/IdentityCommand/Private/ConvertFrom-JwtPayload.ps1 b/IdentityCommand/Private/ConvertFrom-JwtPayload.ps1 new file mode 100644 index 0000000..f7270a0 --- /dev/null +++ b/IdentityCommand/Private/ConvertFrom-JwtPayload.ps1 @@ -0,0 +1,52 @@ +function ConvertFrom-JwtPayload { + <# + .SYNOPSIS + Returns the claims from the payload of a JSON Web Token. + + .DESCRIPTION + Decodes the base64url payload segment of a JWT and returns its claims as an object. + The signature is not validated: use the result only to read values from a token the + module already holds, never to make trust decisions. + + Accepts a raw token, or an Authorization header value with a scheme prefix (Bearer ). + + .PARAMETER Token + The JWT, or an Authorization header value containing one. + + .EXAMPLE + ConvertFrom-JwtPayload -Token $Token + + .EXAMPLE + ConvertFrom-JwtPayload -Token $ISPSSSession.WebSession.Headers['Authorization'] + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [parameter( + Mandatory = $true, + ValueFromPipeline = $true + )] + [ValidateNotNullOrEmpty()] + [string]$Token + ) + + process { + + $Segments = ($Token -replace '^\S+\s+', '').Split('.') + + if ($Segments.Count -ne 3) { + throw 'Token is not a JWT' + } + + $Payload = $Segments[1].Replace('-', '+').Replace('_', '/') + + switch ($Payload.Length % 4) { + 2 { $Payload += '==' } + 3 { $Payload += '=' } + } + + [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Payload)) | ConvertFrom-Json + + } + +} diff --git a/IdentityCommand/Private/Invoke-IDRestMethod.ps1 b/IdentityCommand/Private/Invoke-IDRestMethod.ps1 index afd068b..37d181f 100644 --- a/IdentityCommand/Private/Invoke-IDRestMethod.ps1 +++ b/IdentityCommand/Private/Invoke-IDRestMethod.ps1 @@ -132,6 +132,28 @@ } + #Invoke-WebRequest has no Accept parameter, so Accept is sent as a request header. + #Invoke-WebRequest writes request headers back onto the WebSession; the session's own Accept + #header is recorded here and restored after the request. + if ($PSBoundParameters.ContainsKey('Accept')) { + + $null = $PSBoundParameters.Remove('Accept') + + $RequestHeaders = @{ } + if ($null -ne $Headers) { + foreach ($key in $Headers.Keys) { $RequestHeaders[$key] = $Headers[$key] } + } + $RequestHeaders['Accept'] = $Accept + $PSBoundParameters['Headers'] = $RequestHeaders + + $AcceptSession = $PSBoundParameters['WebSession'] + if ($null -ne $AcceptSession) { + $SessionHasAccept = $AcceptSession.Headers.ContainsKey('Accept') + if ($SessionHasAccept) { $SessionAccept = $AcceptSession.Headers['Accept'] } + } + + } + #Unless otherwise specified, expected content type is json if ( -not ($PSBoundParameters.ContainsKey('ContentType'))) { @@ -269,6 +291,11 @@ } + #No message in the response body, report the exception + if ([string]::IsNullOrEmpty($ErrorMessage)) { + $ErrorMessage = $ISPSSSession.LastError.Exception.Message + } + #throw the error $PSCmdlet.ThrowTerminatingError( @@ -287,6 +314,15 @@ } finally { + #Return the WebSession's Accept header to its state before the request + if ($null -ne $AcceptSession) { + if ($SessionHasAccept) { + $AcceptSession.Headers['Accept'] = $SessionAccept + } else { + $null = $AcceptSession.Headers.Remove('Accept') + } + } + #Add Command Data to $ISPSSSession module scope variable $ISPSSSession.LastCommand = Get-ParentFunction | Select-Object -ExpandProperty CommandData $ISPSSSession.LastCommandResults = $APIResponse @@ -295,8 +331,11 @@ #If Session Variable passed as argument If ($PSCmdlet.ParameterSetName -eq 'SessionVariable') { - #Make the WebSession available in the module scope - $ISPSSSession.WebSession = $(Get-Variable $(Get-Variable sessionVariable).Value).Value + #Make the WebSession available in the module scope; a failed request creates no session variable + $NewWebSession = Get-Variable -Name $SessionVariable -ValueOnly -ErrorAction SilentlyContinue + if ($null -ne $NewWebSession) { + $ISPSSSession.WebSession = $NewWebSession + } } diff --git a/IdentityCommand/Private/Resolve-RequestUrl.ps1 b/IdentityCommand/Private/Resolve-RequestUrl.ps1 new file mode 100644 index 0000000..ec486f8 --- /dev/null +++ b/IdentityCommand/Private/Resolve-RequestUrl.ps1 @@ -0,0 +1,147 @@ +function Resolve-RequestUrl { + <# + .SYNOPSIS + Composes a companion module request URL, connecting the module to the IdentityCommand session on demand. + + .DESCRIPTION + Used by the IdentityCommand.* companion modules, which copy this function into their own scope, + so $ISPSSSession and the $Script: variables here are the companion module's own. + + Before composing the URL, the companion module session is synchronised with the IdentityCommand + session returned by Get-IDSession: + + - If there is no IdentityCommand session, the module session is used as is; an error is thrown + if it holds no service URL. + - If the IdentityCommand session has been closed (Close-IDSession) since it was copied, the + copied session values are cleared, and an error is thrown. + - If the IdentityCommand session has changed since it was last copied (a different StartTime), + its values are copied into the module session. The service URL is kept only if the shared + services subdomain is unchanged. + + If the module session holds no service URL, it is resolved from platform discovery using the + subdomain read from the IdentityCommand session token, and kept for later requests. + + A service URL the companion module sets itself (e.g. Set-SMAccessToken) is used as is. + + A companion module can declare these module scope variables to change the behaviour: + + - $ServiceKey: the platform discovery key of the service. + - $ServiceEndpoint: the property of the service's discovery entry to read the service URL + from, when not 'api' (CEM uses 'bootstrap'). + - $SessionConnectedHook: a scriptblock run after the module session is copied from the + IdentityCommand session or its service URL is resolved, e.g. to exchange the session for a + service specific token. If it fails, it runs again on the next request. + - $IndependentSession: when $true, the module session is not synchronised with the + IdentityCommand session, and is used as is. + + .PARAMETER Path + The path of the operation under the service URL, with or without a leading forward slash. + Any path parameter values must already be escaped by the caller. + + .PARAMETER Service + The platform discovery key of the service. Defaults to the $ServiceKey variable declared in the + companion module scope. + + .PARAMETER Endpoint + The property of the service's discovery entry to read the service URL from. Defaults to the + $ServiceEndpoint variable declared in the companion module scope, or 'api' if there is none. + + .EXAMPLE + Resolve-RequestUrl -Path 'api/policies' + + Returns https://.sca.cyberark.cloud/api/policies when called from IdentityCommand.SCA. + + .OUTPUTS + System.String + #> + [CmdletBinding()] + [OutputType([string])] + param( + [parameter( + Mandatory = $false, + Position = 0 + )] + [AllowEmptyString()] + [string]$Path, + + [parameter(Mandatory = $false)] + [string]$Service = $Script:ServiceKey, + + [parameter(Mandatory = $false)] + [string]$Endpoint = $Script:ServiceEndpoint + ) + + process { + + $IDSession = Get-IDSession + $Connected = $false + + if ($Script:IndependentSession -ne $true) { + + if (($null -eq $IDSession.StartTime) -and ($null -ne $ISPSSSession.StartTime)) { + + #The IdentityCommand session the module session was copied from has been closed + foreach ($key in 'tenant_url', 'TenantId', 'WebSession', 'User', 'StartTime', 'SessionId', 'Subdomain') { + $ISPSSSession[$key] = $null + } + + } + + if (($null -ne $IDSession.StartTime) -and ($IDSession.StartTime -ne $ISPSSSession.StartTime)) { + + $ServiceUrl = if ($IDSession.Subdomain -eq $ISPSSSession.Subdomain) { $ISPSSSession.tenant_url } + + foreach ($key in $IDSession.keys) { + $ISPSSSession[$key] = $IDSession[$key] + } + + $ISPSSSession.tenant_url = $ServiceUrl + $Connected = $true + + } + + } + + if ([string]::IsNullOrEmpty($ISPSSSession.tenant_url)) { + + if ($null -eq $IDSession.StartTime) { + throw 'Authenticate with New-IDSession or New-IDPlatformToken, and try again' + } + + if ([string]::IsNullOrEmpty($Service)) { + throw 'No service specified to resolve the request URL for' + } + + if ([string]::IsNullOrEmpty($ISPSSSession.Subdomain)) { + throw "Unable to resolve the '$Service' service URL: the IdentityCommand session token does not include the shared services subdomain" + } + + if ([string]::IsNullOrEmpty($Endpoint)) { $Endpoint = 'api' } + + $ISPSSSession.tenant_url = (Resolve-ServiceUrl -Service $Service -Subdomain $ISPSSSession.Subdomain -Endpoint $Endpoint).ServiceUrl + + $Connected = $true + + } + + if ($Connected -and ($Script:IndependentSession -ne $true) -and ($null -ne $Script:SessionConnectedHook)) { + + try { + & $Script:SessionConnectedHook + } catch { + #Resolve the service URL and run the hook again on the next request + $ISPSSSession.tenant_url = $null + throw + } + + } + + if ([string]::IsNullOrEmpty($Path)) { + $ISPSSSession.tenant_url + } else { + "$($ISPSSSession.tenant_url)/$($Path -replace '^/', '')" + } + + } + +} diff --git a/IdentityCommand/Private/Resolve-ServiceUrl.ps1 b/IdentityCommand/Private/Resolve-ServiceUrl.ps1 index f1fa49c..aade57b 100644 --- a/IdentityCommand/Private/Resolve-ServiceUrl.ps1 +++ b/IdentityCommand/Private/Resolve-ServiceUrl.ps1 @@ -8,7 +8,7 @@ function Resolve-ServiceUrl { CyberArk platform discovery (via Find-SharedServicesURL) once and returns the URLs a companion module's Connect- command needs: - - ServiceUrl - the api URL of the requested service, with any trailing /api and trailing + - ServiceUrl - the api (or -Endpoint) URL of the requested service, with any trailing /api and trailing slash removed, so a caller can append its own / unconditionally. - IdentityUrl - the 'identity_user_portal' service api URL (the CyberArk Identity tenant URL that New-IDSession / New-IDPlatformToken authenticate against). @@ -31,6 +31,10 @@ function Resolve-ServiceUrl { .PARAMETER Url A service URL to derive the shared services subdomain from. + .PARAMETER Endpoint + The property of the service's discovery entry to read the service URL from. Defaults to 'api'. + CEM serves its API from the 'bootstrap' URL (https://-cem.cyberark.cloud), not 'api'. + .PARAMETER BaseUrlOnly Return only the scheme and host of the service URL, with any path reported separately as ServicePath. Needed by services which publish a path along with the host - 'alerong' (Remote @@ -42,6 +46,9 @@ function Resolve-ServiceUrl { .EXAMPLE Resolve-ServiceUrl -Service jit -Url https://sometenant.dpa.cyberark.cloud + + .EXAMPLE + Resolve-ServiceUrl -Service cem -Subdomain sometenant -Endpoint bootstrap #> [OutputType([pscustomobject])] [CmdletBinding(DefaultParameterSetName = 'Subdomain')] @@ -58,6 +65,10 @@ function Resolve-ServiceUrl { [ValidateNotNullOrEmpty()] [string]$Url, + [parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$Endpoint = 'api', + [parameter(Mandatory = $false)] [switch]$BaseUrlOnly ) @@ -84,7 +95,7 @@ function Resolve-ServiceUrl { throw "CyberArk Identity URL (identity_user_portal) not found in platform discovery response for '$Reference'" } - $ServiceApi = $Discovery.$Service.api + $ServiceApi = $Discovery.$Service.$Endpoint $ServicePath = '' if ($BaseUrlOnly -and (-not [string]::IsNullOrEmpty($ServiceApi))) { diff --git a/IdentityCommand/Public/Authentication/Close-IDSession.ps1 b/IdentityCommand/Public/Authentication/Close-IDSession.ps1 index 5eeaee9..b880272 100644 --- a/IdentityCommand/Public/Authentication/Close-IDSession.ps1 +++ b/IdentityCommand/Public/Authentication/Close-IDSession.ps1 @@ -25,6 +25,7 @@ function Close-IDSession { $ISPSSSession.User = $null $ISPSSSession.StartTime = $null $ISPSSSession.SessionId = $null + $ISPSSSession.Subdomain = $null }#end diff --git a/IdentityCommand/Public/Authentication/New-IDPlatformToken.ps1 b/IdentityCommand/Public/Authentication/New-IDPlatformToken.ps1 index 5685428..48112a6 100644 --- a/IdentityCommand/Public/Authentication/New-IDPlatformToken.ps1 +++ b/IdentityCommand/Public/Authentication/New-IDPlatformToken.ps1 @@ -5,11 +5,22 @@ Function New-IDPlatformToken { #tenant_url [parameter( Mandatory = $true, - ValueFromPipelinebyPropertyName = $true + ValueFromPipelinebyPropertyName = $true, + ParameterSetName = 'URL' )] [ValidateNotNullOrEmpty()] [String]$tenant_url, + #tenant_subdomain + [parameter( + Mandatory = $true, + ValueFromPipelinebyPropertyName = $true, + ParameterSetName = 'Subdomain' + )] + [ValidateNotNullOrEmpty()] + [Alias('subdomain')] + [String]$tenant_subdomain, + #User Creds [Parameter( Mandatory = $true, @@ -20,8 +31,11 @@ Function New-IDPlatformToken { ) Begin { - #Remove WebSession which may exist in module scope + #End any existing session, so a failed sign-in leaves no session $ISPSSSession.WebSession = $null + $ISPSSSession.Subdomain = $null + $ISPSSSession.User = $null + $ISPSSSession.StartTime = $null $LogonRequest = @{ } $LogonRequest['Method'] = 'POST' @@ -30,6 +44,11 @@ Function New-IDPlatformToken { Process { + if ($PSBoundParameters.ContainsKey('tenant_subdomain')) { + #Find the Identity URL of the tenant subdomain from platform discovery + $tenant_url = (Resolve-ServiceUrl -Service identity_user_portal -Subdomain $tenant_subdomain).IdentityUrl + } + #Ensure URL is in expected format #Remove trailing space if provided in Url $tenant_url = $tenant_url -replace '/$', '' @@ -79,6 +98,10 @@ Function New-IDPlatformToken { $ISPSSSession.StartTime = Get-Date $ISPSSSession.WebSession.Headers.Add('Authorization', "$($result.token_type) $($result.access_token)") + #Record the shared services subdomain, used by companion modules to discover service URLs + $ISPSSSession.Subdomain = try { (ConvertFrom-JwtPayload -Token $result.access_token).subdomain } catch { $null } + if (-not $ISPSSSession.Subdomain) { $ISPSSSession.Subdomain = $tenant_subdomain } + #Return the result $result diff --git a/IdentityCommand/Public/Authentication/New-IDSession.ps1 b/IdentityCommand/Public/Authentication/New-IDSession.ps1 index df6a134..36a25a5 100644 --- a/IdentityCommand/Public/Authentication/New-IDSession.ps1 +++ b/IdentityCommand/Public/Authentication/New-IDSession.ps1 @@ -7,16 +7,42 @@ Function New-IDSession { #tenant_url [parameter( Mandatory = $true, - ValueFromPipelinebyPropertyName = $true + ValueFromPipelinebyPropertyName = $true, + ParameterSetName = 'URLCredential' + )] + [parameter( + Mandatory = $true, + ValueFromPipelinebyPropertyName = $true, + ParameterSetName = 'URLSAML' )] [ValidateNotNullOrEmpty()] [String]$tenant_url, + #tenant_subdomain + [parameter( + Mandatory = $true, + ValueFromPipelinebyPropertyName = $true, + ParameterSetName = 'SubdomainCredential' + )] + [parameter( + Mandatory = $true, + ValueFromPipelinebyPropertyName = $true, + ParameterSetName = 'SubdomainSAML' + )] + [ValidateNotNullOrEmpty()] + [Alias('subdomain')] + [String]$tenant_subdomain, + #User Creds [Parameter( Mandatory = $true, ValueFromPipelinebyPropertyName = $true, - ParameterSetName = 'Credential' + ParameterSetName = 'URLCredential' + )] + [Parameter( + Mandatory = $true, + ValueFromPipelinebyPropertyName = $true, + ParameterSetName = 'SubdomainCredential' )] [ValidateNotNullOrEmpty()] [PSCredential]$Credential, @@ -26,7 +52,13 @@ Function New-IDSession { Mandatory = $true, ValueFromPipeline = $false, ValueFromPipelinebyPropertyName = $true, - ParameterSetName = 'SAML' + ParameterSetName = 'URLSAML' + )] + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelinebyPropertyName = $true, + ParameterSetName = 'SubdomainSAML' )] [String]$SAMLResponse @@ -34,8 +66,11 @@ Function New-IDSession { Begin { - #Remove WebSession which may exist in module scope + #End any existing session, so a failed sign-in leaves no session $ISPSSSession.WebSession = $null + $ISPSSSession.Subdomain = $null + $ISPSSSession.User = $null + $ISPSSSession.StartTime = $null $LogonRequest = @{ } $LogonRequest['Method'] = 'POST' @@ -45,6 +80,11 @@ Function New-IDSession { Process { + if ($PSBoundParameters.ContainsKey('tenant_subdomain')) { + #Find the Identity URL of the tenant subdomain from platform discovery + $tenant_url = (Resolve-ServiceUrl -Service identity_user_portal -Subdomain $tenant_subdomain).IdentityUrl + } + #Ensure URL is in expected format #Remove trailing space if provided in Url $tenant_url = $tenant_url -replace '/$', '' @@ -58,14 +98,14 @@ Function New-IDSession { #Must be passed in order to get the parameters needed for OOB IdP auth $LogonRequest['Headers'].Add('OobIdPAuth', $true) - switch ($PSCmdlet.ParameterSetName) { + switch -Wildcard ($PSCmdlet.ParameterSetName) { - 'Credential' { + '*Credential' { #*Start Authentication $IDSession = $LogonRequest | Start-Authentication -Credential $Credential break } - 'SAML' { + '*SAML' { #*Send SAML Assertion $IDSession = $LogonRequest | Start-SamlAuthentication -SAMLResponse $SAMLResponse break @@ -81,9 +121,9 @@ Function New-IDSession { $ISPSSSession.SessionId = $IDSession.SessionId #? does SessionId need to be available in script scope? - switch ($PSCmdlet.ParameterSetName) { + switch -Wildcard ($PSCmdlet.ParameterSetName) { - 'Credential' { + '*Credential' { #IdpRedirectShortUrl is only included in the response if the OobIdPAuth header is set to true if ($IDSession.IdpRedirectShortUrl) { @@ -206,7 +246,7 @@ $($IDSession.IdpRedirectShortUrl) break } - 'SAML' { + '*SAML' { #*Get Saml ID Token $IDSession = $LogonRequest | Complete-SamlAuthentication break @@ -245,6 +285,10 @@ $($IDSession.IdpRedirectShortUrl) $ISPSSSession.StartTime = Get-Date $ISPSSSession.WebSession.Headers.Add('Authorization', "Bearer $($result.Token)") + #Record the shared services subdomain, used by companion modules to discover service URLs + $ISPSSSession.Subdomain = try { (ConvertFrom-JwtPayload -Token $result.Token).subdomain } catch { $null } + if (-not $ISPSSSession.Subdomain) { $ISPSSSession.Subdomain = $tenant_subdomain } + #Return the result $result diff --git a/IdentityCommand/en-US/IdentityCommand-help.xml b/IdentityCommand/en-US/IdentityCommand-help.xml index cbd8697..50d4226 100644 --- a/IdentityCommand/en-US/IdentityCommand-help.xml +++ b/IdentityCommand/en-US/IdentityCommand-help.xml @@ -8591,6 +8591,55 @@ LastCommandResults {"success":true,"Result":{"SomeResult"}}False + + New-IDPlatformToken + + Credential + + Credential object containing username and password of a service user that is an OAuth confidential client to authenticate to CyberArk Identity. + + PSCredential + + PSCredential + + + None + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + tenant_subdomain + + The shared services subdomain of the tenant, the first part of its platform URL: `sometenant` for `https://sometenant.cyberark.cloud`. The CyberArk Identity tenant URL is found from it through platform discovery. + + String + + String + + + None + + @@ -8641,6 +8690,18 @@ LastCommandResults {"success":true,"Result":{"SomeResult"}} False + + tenant_subdomain + + The shared services subdomain of the tenant, the first part of its platform URL: `sometenant` for `https://sometenant.cyberark.cloud`. The CyberArk Identity tenant URL is found from it through platform discovery. + + String + + String + + + None + @@ -8657,6 +8718,13 @@ LastCommandResults {"success":true,"Result":{"SomeResult"}}Initiates OAuth confidential client service user authentication to specified tenant + + -------------------------- Example 2 -------------------------- + PS C:\> New-IDPlatformToken -subdomain sometenant -Credential $Cred + + Initiates OAuth confidential client service user authentication to the CyberArk Identity tenant of the `sometenant` shared services subdomain, found through platform discovery. + + @@ -9846,6 +9914,7 @@ LastCommandResults {"success":true,"Result":{"SomeResult"}} Use this command to authenticate to CyberArk Identity. + Specify the tenant either by its CyberArk Identity URL, or by its shared services subdomain. Allows a user to provide authentication details, and satisfy any required MFA challenges. Currently supports all Identity MFA authentication mechanisms except U2F & DUO. When you specify a username associated with a SAML or OIDC-based federation, then you will be redirected to the external identity provider to authenticate. Alternatively, you can provide a SamlAssertion from a configured external IDP. @@ -9901,6 +9970,55 @@ LastCommandResults {"success":true,"Result":{"SomeResult"}}False + + New-IDSession + + Credential + + Credential object containing username and password required to authenticate to CyberArk Identity. + + PSCredential + + PSCredential + + + None + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + tenant_subdomain + + The shared services subdomain of the tenant, the first part of its platform URL: `sometenant` for `https://sometenant.cyberark.cloud`. The CyberArk Identity tenant URL is found from it through platform discovery. + + String + + String + + + None + + New-IDSession @@ -9950,6 +10068,55 @@ LastCommandResults {"success":true,"Result":{"SomeResult"}}None + + New-IDSession + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + SAMLResponse + + A SAML assertion obtained from an external IDP for the account with which to authenticate. + + String + + String + + + None + + + tenant_subdomain + + The shared services subdomain of the tenant, the first part of its platform URL: `sometenant` for `https://sometenant.cyberark.cloud`. The CyberArk Identity tenant URL is found from it through platform discovery. + + String + + String + + + None + + @@ -10012,6 +10179,18 @@ LastCommandResults {"success":true,"Result":{"SomeResult"}} None + + tenant_subdomain + + The shared services subdomain of the tenant, the first part of its platform URL: `sometenant` for `https://sometenant.cyberark.cloud`. The CyberArk Identity tenant URL is found from it through platform discovery. + + String + + String + + + None + @@ -10063,6 +10242,13 @@ PS C:\> New-IDSession -tenant_url https://sometenant.id.cyberark.cloud -SAMLR Authenticates to CyberArk Identity using SAML assertion from external IDP (obtained using PS-SAML-Interactive) + + -------------------------- Example 3 -------------------------- + PS C:\> New-IDSession -subdomain sometenant -Credential $Cred + + Initiates authentication to the CyberArk Identity tenant of the `sometenant` shared services subdomain (`https://sometenant.cyberark.cloud`), found through platform discovery. + + diff --git a/README.md b/README.md index 7f059a5..efd3dfe 100644 --- a/README.md +++ b/README.md @@ -24,11 +24,11 @@ The module has been in development for a few years, initially focused on authent Documentation, command reference and release notes: [www.pspete.dev/IdentityCommand](https://www.pspete.dev/IdentityCommand/). -- **Prior to a Version 1.0.0 release**: - - Expect changes, although we will do our best to keep these to a minimum +- **Versioning**: + - From 1.0.0, IdentityCommand follows semantic versioning: breaking changes come only in a major release + - The companion modules are pre-1.0.0: their command names, parameters and grouping may still change + - The SCIM `Container`, `ContainerPermission` and `PrivilegedData` commands are not yet exercised against a live tenant - see [Help Us Test](#help-us-test) - Issues / PRs are encouraged & appreciated - - Many commands are built from documented API shapes but not yet exercised against a live tenant - see [Help Us Test](#help-us-test) below, your feedback genuinely shapes what ships next. - - Most of the Identity Administration API is now covered, but real-world usage is still expected to shape further changes to command names, parameters/parameter names, and how commands are grouped - some may split into companion commands, others may combine. These patterns only emerge once commands are actually used, so don't consider anything final yet. | Main Branch | CodeFactor | Coverage | PowerShell Gallery | License | | ------------------------ | -------------------------- | ---------------------------- | ------------------------- | ---------------------------- | @@ -61,6 +61,12 @@ PS C:\> $Credential = Get-Credential PS C:\> New-IDSession -tenant_url https://sometenant.id.cyberark.cloud -Credential $Credential ``` +Instead of the Identity URL, give the tenant's shared services subdomain - `sometenant` for `https://sometenant.cyberark.cloud` - and the Identity URL is found through platform discovery: + +```powershell +PS C:\> New-IDSession -subdomain sometenant -Credential $Credential +``` + This allows initial authentication to progress as well as selection and answer of any required MFA challenges. Once successfully authenticated, all _IdentityCommand_ module commands which require an authenticated session can be used from within the same PowerShell session. @@ -74,6 +80,8 @@ PS C:\> $Credential = Get-Credential PS C:\> New-IDPlatformToken -tenant_url https://sometenant.id.cyberark.cloud -Credential $Credential ``` +`New-IDPlatformToken` also accepts `-subdomain` in place of `-tenant_url`. + This allows initial authentication using a separate dedicated Service user for API activities. Consult the vendor documentation for guidance on setting up a dedicated API Service user for non-interactive API use. @@ -182,7 +190,7 @@ Every command also has a reference page on the [documentation site](https://www. ## Help Us Test -Prior to a 1.0.0 release, some commands are built from documented or captured API shapes but haven't yet been exercised against a live tenant, or only partially confirmed. If you're able to try one of these against your own tenant, [open an issue][new-issue] with what you found (works as-is, needs a fix, or the request shape is wrong) - it's genuinely the fastest way to move a command from "should work" to "confirmed". +These commands are built from the vendor's OpenAPI schema, but haven't yet been exercised against a live tenant. If you're able to try one of these against your own tenant, [open an issue][new-issue] with what you found (works as-is, needs a fix, or the request shape is wrong) - it's genuinely the fastest way to move a command from "should work" to "confirmed". The current list is: diff --git a/Tests/ConvertFrom-JwtPayload.Tests.ps1 b/Tests/ConvertFrom-JwtPayload.Tests.ps1 new file mode 100644 index 0000000..56ec5bd --- /dev/null +++ b/Tests/ConvertFrom-JwtPayload.Tests.ps1 @@ -0,0 +1,60 @@ +Describe $($PSCommandPath -Replace '.Tests.ps1') { + + BeforeAll { + #Get Current Directory + $Here = Split-Path -Parent $PSCommandPath + + #Assume ModuleName from Repository Root folder + $ModuleName = Split-Path (Split-Path $Here -Parent) -Leaf + + #Resolve Path to Module Directory + $ModulePath = Resolve-Path "$Here\..\$ModuleName" + + #Define Path to Module Manifest + $ManifestPath = Join-Path "$ModulePath" "$ModuleName.psd1" + + if ( -not (Get-Module -Name $ModuleName -All)) { + + Import-Module -Name "$ManifestPath" -ArgumentList $true -Force -ErrorAction Stop + + } + + } + + InModuleScope $(Split-Path (Split-Path (Split-Path -Parent $PSCommandPath) -Parent) -Leaf ) { + + Context 'General' { + + BeforeAll { + #{"subdomain":"sometenant","platform_domain":"cyberark.cloud"} - base64url, unpadded + $Jwt = 'eyJhbGciOiJub25lIn0.eyJzdWJkb21haW4iOiJzb21ldGVuYW50IiwicGxhdGZvcm1fZG9tYWluIjoiY3liZXJhcmsuY2xvdWQifQ.c2ln' + } + + It 'returns the payload claims of a raw token' { + $Claims = ConvertFrom-JwtPayload -Token $Jwt + $Claims.subdomain | Should -Be 'sometenant' + $Claims.platform_domain | Should -Be 'cyberark.cloud' + } + + It 'accepts an Authorization header value' { + (ConvertFrom-JwtPayload -Token "Bearer $Jwt").subdomain | Should -Be 'sometenant' + } + + It 'accepts pipeline input' { + ($Jwt | ConvertFrom-JwtPayload).subdomain | Should -Be 'sometenant' + } + + It 'decodes base64url characters' { + #{"n":"a?>b"} encodes with a '_' in base64url + (ConvertFrom-JwtPayload -Token 'e30.eyJuIjoiYT8-YiJ9.c2ln').n | Should -Be 'a?>b' + } + + It 'throws when the value is not a JWT' { + { ConvertFrom-JwtPayload -Token 'SomeAccessToken' } | Should -Throw 'Token is not a JWT' + } + + } + + } + +} diff --git a/Tests/Invoke-IDRestMethod.Tests.ps1 b/Tests/Invoke-IDRestMethod.Tests.ps1 index 0a1f199..b0b8d8a 100644 --- a/Tests/Invoke-IDRestMethod.Tests.ps1 +++ b/Tests/Invoke-IDRestMethod.Tests.ps1 @@ -301,6 +301,62 @@ Describe $($PSCommandPath -Replace '.Tests.ps1') { } + Context 'Accept Header' { + + BeforeEach { + + $ISPSSSession = [ordered]@{ + tenant_url = $null + WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession + LastCommand = $null + LastCommandTime = $null + LastCommandResults = $null + } + New-Variable -Name ISPSSSession -Value $ISPSSSession -Scope Script -Force + + #Invoke-WebRequest writes request headers back onto the WebSession + Mock Invoke-WebRequest -MockWith { + foreach ($key in $Headers.Keys) { $WebSession.Headers[$key] = $Headers[$key] } + } + + } + + It 'sends Accept as a request header' { + Invoke-IDRestMethod -URI 'https://CyberArk_URL' -Method GET -Accept 'application/x.test+json' + Assert-MockCalled Invoke-WebRequest -ParameterFilter { + $Headers['Accept'] -eq 'application/x.test+json' -and -not $PSBoundParameters.ContainsKey('Accept') + } -Times 1 -Exactly -Scope It + } + + It 'keeps other request headers' { + Invoke-IDRestMethod -URI 'https://CyberArk_URL' -Method GET -Accept 'application/x.test+json' -Headers @{ 'X-Test' = 'OK' } + Assert-MockCalled Invoke-WebRequest -ParameterFilter { + $Headers['Accept'] -eq 'application/x.test+json' -and $Headers['X-Test'] -eq 'OK' + } -Times 1 -Exactly -Scope It + } + + It 'does not leave the Accept header on the WebSession' { + Invoke-IDRestMethod -URI 'https://CyberArk_URL' -Method GET -Accept 'application/x.test+json' + $ISPSSSession.WebSession.Headers.ContainsKey('Accept') | Should -BeFalse + } + + It 'restores an Accept header already on the WebSession' { + $ISPSSSession.WebSession.Headers['Accept'] = 'application/json' + Invoke-IDRestMethod -URI 'https://CyberArk_URL' -Method GET -Accept 'application/x.test+json' + $ISPSSSession.WebSession.Headers['Accept'] | Should -Be 'application/json' + } + + It 'restores the WebSession when the request fails' { + Mock Invoke-WebRequest -MockWith { + foreach ($key in $Headers.Keys) { $WebSession.Headers[$key] = $Headers[$key] } + throw 'No such host is known.' + } + { Invoke-IDRestMethod -URI 'https://CyberArk_URL' -Method GET -Accept 'application/x.test+json' } | Should -Throw + $ISPSSSession.WebSession.Headers.ContainsKey('Accept') | Should -BeFalse + } + + } + Context 'Error Handling' { BeforeEach { @@ -395,6 +451,19 @@ Describe $($PSCommandPath -Replace '.Tests.ps1') { } + It 'reports the exception message when the response has no error details' { + Mock Invoke-WebRequest { throw 'No such host is known.' } + { Invoke-IDRestMethod @WebSession } | Should -Throw -ExpectedMessage 'No such host is known.' + } + + It 'reports the request error, not a missing session variable, when a SessionVariable request fails' { + Mock Invoke-WebRequest { throw 'No such host is known.' } + $Error.Clear() + { Invoke-IDRestMethod -URI 'https://CyberArk_URL' -Method GET -SessionVariable 'NoSuchSession' } | + Should -Throw -ExpectedMessage 'No such host is known.' + @($Error | Where-Object { $PSItem.FullyQualifiedErrorId -like 'VariableNotFound*' }).Count | Should -Be 0 + } + } } diff --git a/Tests/New-IDPlatformToken.Tests.ps1 b/Tests/New-IDPlatformToken.Tests.ps1 index 0c939c7..03d1949 100644 --- a/Tests/New-IDPlatformToken.Tests.ps1 +++ b/Tests/New-IDPlatformToken.Tests.ps1 @@ -135,6 +135,105 @@ Describe $($PSCommandPath -Replace '.Tests.ps1') { } + It 'sets Subdomain from the token subdomain claim' { + + Mock Invoke-IDRestMethod -MockWith { + $ISPSSSession.WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession + [pscustomobject]@{ + token_type = 'Bearer' + access_token = 'eyJhbGciOiJub25lIn0.eyJzdWJkb21haW4iOiJzb21ldGVuYW50In0.c2ln' + } + } + + New-IDPlatformToken -tenant_url https://sometenant.id.cyberark.cloud -Credential $Cred + $Script:ISPSSSession.Subdomain | Should -Be 'sometenant' + + } + + It 'sets Subdomain to null when the token is not a JWT' { + + $Script:ISPSSSession.Subdomain = 'stale' + New-IDPlatformToken -tenant_url https://sometenant.id.cyberark.cloud -Credential $Cred + $Script:ISPSSSession.Subdomain | Should -BeNullOrEmpty + + } + + It 'leaves no session when sign-in fails' { + Mock Invoke-IDRestMethod -MockWith { throw 'SomeError' } + $Script:ISPSSSession.User = 'PreviousUser' + $Script:ISPSSSession.StartTime = Get-Date + { New-IDPlatformToken -tenant_url https://sometenant.id.cyberark.cloud -Credential $Cred } | Should -Throw + $Script:ISPSSSession.User | Should -BeNullOrEmpty + $Script:ISPSSSession.StartTime | Should -BeNullOrEmpty + } + + } + + Context 'Subdomain' { + + BeforeEach { + $ISPSSSession = [ordered]@{ + tenant_url = $null + Subdomain = $null + User = $null + WebSession = $null + StartTime = $null + } + New-Variable -Name ISPSSSession -Value $ISPSSSession -Scope Script -Force + Mock Resolve-ServiceUrl -MockWith { + [pscustomobject]@{ + ServiceUrl = 'https://abc1234.id.cyberark.cloud' + IdentityUrl = 'https://abc1234.id.cyberark.cloud' + ServicePath = '' + } + } + Mock Invoke-IDRestMethod -MockWith { + $ISPSSSession.WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession + [pscustomobject]@{ + token_type = 'Bearer' + access_token = 'SomeAccessToken' + } + } + + $Cred = New-Object System.Management.Automation.PSCredential ('SomeUser', $(ConvertTo-SecureString 'SomePassword' -AsPlainText -Force)) + } + + It 'finds the Identity URL of the subdomain from platform discovery' { + New-IDPlatformToken -tenant_subdomain sometenant -Credential $Cred + Assert-MockCalled -CommandName Resolve-ServiceUrl -Times 1 -Exactly -Scope It -ParameterFilter { + $Service -eq 'identity_user_portal' -and $Subdomain -eq 'sometenant' + } + } + + It 'sends request to the discovered Identity URL' { + New-IDPlatformToken -subdomain sometenant -Credential $Cred + Assert-MockCalled -CommandName Invoke-IDRestMethod -Times 1 -Exactly -Scope It -ParameterFilter { + $URI -eq 'https://abc1234.id.cyberark.cloud/OAuth2/PlatformToken' + } + } + + It 'sets Subdomain from the parameter when the token has no subdomain claim' { + New-IDPlatformToken -tenant_subdomain sometenant -Credential $Cred + $Script:ISPSSSession.Subdomain | Should -Be 'sometenant' + } + + It 'sets Subdomain from the token subdomain claim when present' { + Mock Invoke-IDRestMethod -MockWith { + $ISPSSSession.WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession + [pscustomobject]@{ + token_type = 'Bearer' + access_token = 'eyJhbGciOiJub25lIn0.eyJzdWJkb21haW4iOiJzb21ldGVuYW50In0.c2ln' + } + } + New-IDPlatformToken -tenant_subdomain SomeTenant -Credential $Cred + $Script:ISPSSSession.Subdomain | Should -BeExactly 'sometenant' + } + + It 'does not use platform discovery when tenant_url is provided' { + New-IDPlatformToken -tenant_url https://sometenant.id.cyberark.cloud -Credential $Cred + Assert-MockCalled -CommandName Resolve-ServiceUrl -Times 0 -Exactly -Scope It + } + } } diff --git a/Tests/New-IDSession.Tests.ps1 b/Tests/New-IDSession.Tests.ps1 index 367cac6..583005b 100644 --- a/Tests/New-IDSession.Tests.ps1 +++ b/Tests/New-IDSession.Tests.ps1 @@ -93,6 +93,73 @@ Describe $($PSCommandPath -Replace '.Tests.ps1') { } + It 'leaves no session when sign-in fails' { + Mock Start-Authentication -MockWith { throw 'SomeError' } + $Script:ISPSSSession.User = 'PreviousUser' + $Script:ISPSSSession.StartTime = Get-Date + { New-IDSession -tenant_url https://somedomain.id.cyberark.cloud -Credential $Creds } | Should -Throw + $Script:ISPSSSession.User | Should -BeNullOrEmpty + $Script:ISPSSSession.StartTime | Should -BeNullOrEmpty + } + + } + + Context 'Subdomain' { + + BeforeEach { + Mock Resolve-ServiceUrl -MockWith { + [pscustomobject]@{ + ServiceUrl = 'https://abc1234.id.cyberark.cloud' + IdentityUrl = 'https://abc1234.id.cyberark.cloud' + ServicePath = '' + } + } + Mock Start-AdvanceAuthentication -MockWith { + $ISPSSSession.WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession + [pscustomobject]@{ + Summary = 'LoginSuccess' + } + } + } + + It 'finds the Identity URL of the subdomain from platform discovery' { + New-IDSession -tenant_subdomain sometenant -Credential $Creds + Assert-MockCalled -CommandName Resolve-ServiceUrl -Times 1 -Exactly -Scope It -ParameterFilter { + $Service -eq 'identity_user_portal' -and $Subdomain -eq 'sometenant' + } + } + + It 'sets tenant_url to the discovered Identity URL' { + New-IDSession -subdomain sometenant -Credential $Creds + $Script:ISPSSSession.tenant_url | Should -Be 'https://abc1234.id.cyberark.cloud' + } + + It 'sets Subdomain from the parameter when the token has no subdomain claim' { + New-IDSession -tenant_subdomain sometenant -Credential $Creds + $Script:ISPSSSession.Subdomain | Should -Be 'sometenant' + } + + It 'does not use platform discovery when tenant_url is provided' { + New-IDSession -tenant_url https://somedomain.id.cyberark.cloud -Credential $Creds + Assert-MockCalled -CommandName Resolve-ServiceUrl -Times 0 -Exactly -Scope It + } + + It 'sends the SAML assertion to the discovered Identity URL' { + Mock Start-SamlAuthentication -MockWith {} + Mock Complete-SamlAuthentication -MockWith {} + New-IDSession -tenant_subdomain sometenant -SAMLResponse 'SomeAssertion' + Assert-MockCalled -CommandName Start-SamlAuthentication -Times 1 -Exactly -Scope It + $Script:ISPSSSession.tenant_url | Should -Be 'https://abc1234.id.cyberark.cloud' + } + + It 'leaves no session when discovery fails' { + Mock Resolve-ServiceUrl -MockWith { throw 'SomeError' } + $Script:ISPSSSession.User = 'PreviousUser' + { New-IDSession -tenant_subdomain sometenant -Credential $Creds } | Should -Throw + $Script:ISPSSSession.User | Should -BeNullOrEmpty + Assert-MockCalled -CommandName Start-Authentication -Times 0 -Exactly -Scope It + } + } Context 'Start-Authentication' { diff --git a/Tests/Resolve-RequestUrl.Tests.ps1 b/Tests/Resolve-RequestUrl.Tests.ps1 new file mode 100644 index 0000000..60e3dbb --- /dev/null +++ b/Tests/Resolve-RequestUrl.Tests.ps1 @@ -0,0 +1,278 @@ +Describe $($PSCommandPath -Replace '.Tests.ps1') { + + BeforeAll { + #Get Current Directory + $Here = Split-Path -Parent $PSCommandPath + + #Assume ModuleName from Repository Root folder + $ModuleName = Split-Path (Split-Path $Here -Parent) -Leaf + + #Resolve Path to Module Directory + $ModulePath = Resolve-Path "$Here\..\$ModuleName" + + #Define Path to Module Manifest + $ManifestPath = Join-Path "$ModulePath" "$ModuleName.psd1" + + if ( -not (Get-Module -Name $ModuleName -All)) { + + Import-Module -Name "$ManifestPath" -ArgumentList $true -Force -ErrorAction Stop + + } + + } + + InModuleScope $(Split-Path (Split-Path (Split-Path -Parent $PSCommandPath) -Parent) -Leaf ) { + + BeforeAll { + $SessionStart = Get-Date '2026-01-01T09:00:00' + } + + BeforeEach { + + #Stands in for a companion module session which has not yet been connected + $ISPSSSession = [ordered]@{ + tenant_url = $null + User = $null + StartTime = $null + WebSession = $null + } + New-Variable -Name ISPSSSession -Value $ISPSSSession -Scope Script -Force + New-Variable -Name ServiceKey -Value 'sca' -Scope Script -Force + + Mock Get-IDSession -MockWith { + [ordered]@{ + tenant_url = 'https://sometenant.id.cyberark.cloud' + User = 'SomeUser' + Subdomain = 'sometenant' + StartTime = $SessionStart + WebSession = 'SomeWebSession' + } + } + + Mock Resolve-ServiceUrl -MockWith { + [pscustomobject]@{ + ServiceUrl = "https://$Subdomain.$Service.cyberark.cloud" + IdentityUrl = "https://$Subdomain.id.cyberark.cloud" + ServicePath = '' + } + } + + } + + AfterAll { + Remove-Variable -Name ServiceKey -Scope Script -ErrorAction SilentlyContinue + } + + Context 'No IdentityCommand session' { + + It 'throws when there is no IdentityCommand session' { + Mock Get-IDSession -MockWith { [ordered]@{ tenant_url = $null; StartTime = $null } } + { Resolve-RequestUrl -Path 'api/policies' } | Should -Throw 'Authenticate with New-IDSession*' + } + + It 'uses a module session connected without an IdentityCommand session' { + Mock Get-IDSession -MockWith { [ordered]@{ tenant_url = $null; StartTime = $null } } + $Script:ISPSSSession.tenant_url = 'https://explicit.example.com' + Resolve-RequestUrl -Path 'api' | Should -Be 'https://explicit.example.com/api' + } + + It 'throws when the IdentityCommand session it was copied from has been closed' { + Mock Get-IDSession -MockWith { [ordered]@{ tenant_url = $null; StartTime = $null } } + $Script:ISPSSSession.tenant_url = 'https://sometenant.sca.cyberark.cloud' + $Script:ISPSSSession.StartTime = $SessionStart + { Resolve-RequestUrl -Path 'api' } | Should -Throw 'Authenticate with New-IDSession*' + } + + It 'clears the copied session values when the IdentityCommand session has been closed' { + Mock Get-IDSession -MockWith { [ordered]@{ tenant_url = $null; StartTime = $null } } + $Script:ISPSSSession.tenant_url = 'https://sometenant.sca.cyberark.cloud' + $Script:ISPSSSession.User = 'SomeUser' + $Script:ISPSSSession.WebSession = 'SomeWebSession' + $Script:ISPSSSession.StartTime = $SessionStart + { Resolve-RequestUrl -Path 'api' } | Should -Throw + $Script:ISPSSSession.tenant_url | Should -BeNullOrEmpty + $Script:ISPSSSession.User | Should -BeNullOrEmpty + $Script:ISPSSSession.WebSession | Should -BeNullOrEmpty + } + + } + + Context 'Lazy connection' { + + It 'resolves the service URL by the session subdomain' { + $null = Resolve-RequestUrl -Path 'api/policies' + Should -Invoke Resolve-ServiceUrl -ParameterFilter { + $Service -eq 'sca' -and $Subdomain -eq 'sometenant' + } -Times 1 -Exactly -Scope It + } + + It 'returns the request URL' { + Resolve-RequestUrl -Path 'api/policies' | Should -Be 'https://sometenant.sca.cyberark.cloud/api/policies' + } + + It 'accepts a path with a leading slash' { + Resolve-RequestUrl -Path '/api/policies' | Should -Be 'https://sometenant.sca.cyberark.cloud/api/policies' + } + + It 'returns the service URL when no path is given' { + Resolve-RequestUrl | Should -Be 'https://sometenant.sca.cyberark.cloud' + } + + It 'resolves the service named by -Service' { + Resolve-RequestUrl -Path 'api' -Service jit | Should -Be 'https://sometenant.jit.cyberark.cloud/api' + } + + It 'copies the IdentityCommand session into the module session' { + $null = Resolve-RequestUrl -Path 'api/policies' + $Script:ISPSSSession.User | Should -Be 'SomeUser' + $Script:ISPSSSession.WebSession | Should -Be 'SomeWebSession' + $Script:ISPSSSession.StartTime | Should -Be $SessionStart + } + + It 'keeps the service URL for later requests' { + $null = Resolve-RequestUrl -Path 'api/policies' + $null = Resolve-RequestUrl -Path 'api/policies' + Should -Invoke Resolve-ServiceUrl -Times 1 -Exactly -Scope It + } + + It 'throws when the session has no subdomain' { + Mock Get-IDSession -MockWith { [ordered]@{ StartTime = $SessionStart; Subdomain = $null } } + { Resolve-RequestUrl -Path 'api/policies' } | Should -Throw '*shared services subdomain*' + } + + It 'throws when no service is specified' { + Remove-Variable -Name ServiceKey -Scope Script + { Resolve-RequestUrl -Path 'api/policies' } | Should -Throw 'No service specified*' + } + + } + + Context 'Session changes' { + + It 'uses a service URL already set for the current session' { + $Script:ISPSSSession.tenant_url = 'https://explicit.example.com' + $Script:ISPSSSession.StartTime = $SessionStart + Resolve-RequestUrl -Path 'api' | Should -Be 'https://explicit.example.com/api' + Should -Invoke Resolve-ServiceUrl -Times 0 -Exactly -Scope It + } + + It 'copies a new IdentityCommand session and keeps the service URL for the same subdomain' { + $Script:ISPSSSession.tenant_url = 'https://explicit.example.com' + $Script:ISPSSSession.Subdomain = 'sometenant' + $Script:ISPSSSession.StartTime = $SessionStart.AddHours(-1) + Resolve-RequestUrl -Path 'api' | Should -Be 'https://explicit.example.com/api' + $Script:ISPSSSession.StartTime | Should -Be $SessionStart + $Script:ISPSSSession.WebSession | Should -Be 'SomeWebSession' + } + + It 'resolves the service URL again when the subdomain changes' { + $Script:ISPSSSession.tenant_url = 'https://othertenant.sca.cyberark.cloud' + $Script:ISPSSSession.Subdomain = 'othertenant' + $Script:ISPSSSession.StartTime = $SessionStart.AddHours(-1) + Resolve-RequestUrl -Path 'api' | Should -Be 'https://sometenant.sca.cyberark.cloud/api' + } + + } + + Context 'Module hooks' { + + BeforeEach { + New-Variable -Name HookCount -Value 0 -Scope Script -Force + } + + AfterEach { + Remove-Variable -Name ServiceEndpoint, SessionConnectedHook, IndependentSession, HookCount -Scope Script -ErrorAction SilentlyContinue + } + + It 'resolves the api endpoint when the module declares none' { + $null = Resolve-RequestUrl -Path 'api' + Should -Invoke Resolve-ServiceUrl -ParameterFilter { $Endpoint -eq 'api' } -Times 1 -Exactly -Scope It + } + + It 'resolves the endpoint declared by the module' { + New-Variable -Name ServiceEndpoint -Value 'bootstrap' -Scope Script -Force + $null = Resolve-RequestUrl -Path 'api' + Should -Invoke Resolve-ServiceUrl -ParameterFilter { $Endpoint -eq 'bootstrap' } -Times 1 -Exactly -Scope It + } + + It 'runs the connected hook when the module connects' { + New-Variable -Name SessionConnectedHook -Value { $Script:HookCount++ } -Scope Script -Force + $null = Resolve-RequestUrl -Path 'api' + $Script:HookCount | Should -Be 1 + } + + It 'runs the connected hook after the service URL is resolved' { + New-Variable -Name SessionConnectedHook -Value { $Script:HookUrl = $ISPSSSession.tenant_url } -Scope Script -Force + $null = Resolve-RequestUrl -Path 'api' + $Script:HookUrl | Should -Be 'https://sometenant.sca.cyberark.cloud' + } + + It 'does not run the connected hook for later requests' { + New-Variable -Name SessionConnectedHook -Value { $Script:HookCount++ } -Scope Script -Force + $null = Resolve-RequestUrl -Path 'api' + $null = Resolve-RequestUrl -Path 'api' + $Script:HookCount | Should -Be 1 + } + + It 'runs the connected hook again when the IdentityCommand session changes' { + New-Variable -Name SessionConnectedHook -Value { $Script:HookCount++ } -Scope Script -Force + $Script:ISPSSSession.tenant_url = 'https://sometenant.sca.cyberark.cloud' + $Script:ISPSSSession.Subdomain = 'sometenant' + $Script:ISPSSSession.StartTime = $SessionStart.AddHours(-1) + $null = Resolve-RequestUrl -Path 'api' + $Script:HookCount | Should -Be 1 + Should -Invoke Resolve-ServiceUrl -Times 0 -Exactly -Scope It + } + + It 'throws when the connected hook fails' { + New-Variable -Name SessionConnectedHook -Value { throw 'SomeHookError' } -Scope Script -Force + { Resolve-RequestUrl -Path 'api' } | Should -Throw 'SomeHookError' + } + + It 'runs the connected hook again on the next request after it fails' { + New-Variable -Name SessionConnectedHook -Value { throw 'SomeHookError' } -Scope Script -Force + { Resolve-RequestUrl -Path 'api' } | Should -Throw + New-Variable -Name SessionConnectedHook -Value { $Script:HookCount++ } -Scope Script -Force + Resolve-RequestUrl -Path 'api' | Should -Be 'https://sometenant.sca.cyberark.cloud/api' + $Script:HookCount | Should -Be 1 + } + + It 'throws when the IdentityCommand session is closed after the connected hook fails' { + New-Variable -Name SessionConnectedHook -Value { throw 'SomeHookError' } -Scope Script -Force + { Resolve-RequestUrl -Path 'api' } | Should -Throw 'SomeHookError' + Mock Get-IDSession -MockWith { [ordered]@{ tenant_url = $null; StartTime = $null } } + { Resolve-RequestUrl -Path 'api' } | Should -Throw 'Authenticate with New-IDSession*' + $Script:ISPSSSession.WebSession | Should -BeNullOrEmpty + } + + It 'does not copy the IdentityCommand session into an independent session' { + New-Variable -Name IndependentSession -Value $true -Scope Script -Force + $Script:ISPSSSession.tenant_url = 'https://independent.example.com' + $Script:ISPSSSession.WebSession = 'IndependentWebSession' + $Script:ISPSSSession.StartTime = $SessionStart.AddHours(-1) + Resolve-RequestUrl -Path 'api' | Should -Be 'https://independent.example.com/api' + $Script:ISPSSSession.WebSession | Should -Be 'IndependentWebSession' + $Script:ISPSSSession.StartTime | Should -Be $SessionStart.AddHours(-1) + } + + It 'does not clear an independent session when there is no IdentityCommand session' { + Mock Get-IDSession -MockWith { [ordered]@{ tenant_url = $null; StartTime = $null } } + New-Variable -Name IndependentSession -Value $true -Scope Script -Force + $Script:ISPSSSession.tenant_url = 'https://independent.example.com' + $Script:ISPSSSession.StartTime = $SessionStart + Resolve-RequestUrl -Path 'api' | Should -Be 'https://independent.example.com/api' + } + + It 'does not run the connected hook for an independent session' { + New-Variable -Name IndependentSession -Value $true -Scope Script -Force + New-Variable -Name SessionConnectedHook -Value { $Script:HookCount++ } -Scope Script -Force + $Script:ISPSSSession.tenant_url = 'https://independent.example.com' + $null = Resolve-RequestUrl -Path 'api' + $Script:HookCount | Should -Be 0 + } + + } + + } + +} diff --git a/Tests/Resolve-ServiceUrl.Tests.ps1 b/Tests/Resolve-ServiceUrl.Tests.ps1 index 440f13f..fbd68ec 100644 --- a/Tests/Resolve-ServiceUrl.Tests.ps1 +++ b/Tests/Resolve-ServiceUrl.Tests.ps1 @@ -31,7 +31,10 @@ userportal = [pscustomobject]@{ api = 'https://sometenant.api.userportal.cyberark.cloud/api' } compass = [pscustomobject]@{ api = 'https://sometenant.compass.cyberark.cloud' } cds = [pscustomobject]@{ api = 'https://eu-west-2.cds.cyberark.cloud/' } - cem = [pscustomobject]@{ api = 'https://eu-west-2.api.cps.cyberark.com/' } + cem = [pscustomobject]@{ + api = 'https://eu-west-2.api.cps.cyberark.com/' + bootstrap = 'https://sometenant-cem.cyberark.cloud' + } alerong = [pscustomobject]@{ api = 'https://api.alero.io/internal/ra/v1/11ed307a252bbd10987ef76ae4e0982d' } identity_user_portal = [pscustomobject]@{ api = 'https://sometenant.id.cyberark.cloud/' } } @@ -105,6 +108,16 @@ Should -Be 'https://sometenant.id.cyberark.cloud' } + It 'returns the url of the requested endpoint' { + (Resolve-ServiceUrl -Service cem -Subdomain 'sometenant' -Endpoint bootstrap).ServiceUrl | + Should -Be 'https://sometenant-cem.cyberark.cloud' + } + + It 'throws for an endpoint absent from the service entry' { + { Resolve-ServiceUrl -Service sca -Subdomain 'sometenant' -Endpoint bootstrap } | + Should -Throw "*URL for the 'sca' service not found*" + } + It 'throws for a service absent from the discovery response' { { Resolve-ServiceUrl -Service pcloud -Subdomain 'sometenant' } | Should -Throw "*URL for the 'pcloud' service not found*sometenant*" diff --git a/docs/README.md b/docs/README.md index 1a5d457..a609c23 100644 --- a/docs/README.md +++ b/docs/README.md @@ -65,7 +65,7 @@ Copy [_tools/docs-dispatch.yml](_tools/docs-dispatch.yml) to the sibling's `.git For module `IdentityCommand.XYZ`: 1. `_data/navigation.yml` - add `name`, `link: /XYZ/`, `module: XYZ`. -2. `_data/menus.yml` - add key `XYZ` with `label`, `repo`, `commands: XYZ`, `prefix: XYZ`, `pinned` (e.g. `Connect-XYZTenant`), `description`, `image` and `menu`. +2. `_data/menus.yml` - add key `XYZ` with `label`, `repo`, `commands: XYZ`, `prefix: XYZ`, `pinned` (optional: commands listed first in the sidebar), `description`, `image` and `menu`. 3. `_config.yml` - add collection `XYZ` (`output: true`, `permalink: /XYZ/commands/:title/`) and the two `defaults` entries (path `XYZ`, type `XYZ`) matching SCA/SIA. 4. Add `docs/` and the dispatch workflow to the sibling repo. diff --git a/docs/_data/menus.yml b/docs/_data/menus.yml index d1aca9a..3eb6eeb 100644 --- a/docs/_data/menus.yml +++ b/docs/_data/menus.yml @@ -40,8 +40,6 @@ SCA: repo: pspete/IdentityCommand.SCA commands: SCA prefix: SCA - pinned: - - Connect-SCATenant description: >- Secure Cloud Access: just-in-time access policies for cloud roles, discovery, eligibility, and on-demand access requests. @@ -61,8 +59,6 @@ SIA: repo: pspete/IdentityCommand.SIA commands: SIA prefix: SIA - pinned: - - Connect-SIATenant description: >- Secure Infrastructure Access: connectors, access policies, strong accounts, target sets, and SSH / RDP / database connections. @@ -82,8 +78,6 @@ AccessRequest: repo: pspete/IdentityCommand.AccessRequest commands: AccessRequest prefix: AR - pinned: - - Connect-ARTenant description: >- Access Requests: raise, approve and reject requests for access. image: /AccessRequest/media/images/IdentityCommand.AccessRequest.png @@ -102,8 +96,6 @@ CEM: repo: pspete/IdentityCommand.CEM commands: CEM prefix: CEM - pinned: - - Connect-CEMTenant description: >- Cloud Visibility: delegate cloud workspaces through the Workspace Delegation API. image: /CEM/media/images/IdentityCommand.CEM.png @@ -142,8 +134,6 @@ RiskMgmt: repo: pspete/IdentityCommand.RiskMgmt commands: RiskMgmt prefix: RM - pinned: - - Connect-RMTenant description: >- Risk Management: risks, findings, recommendations, remediations and risk posture. image: /RiskMgmt/media/images/IdentityCommand.RiskMgmt.png @@ -162,8 +152,6 @@ SecretsHub: repo: pspete/IdentityCommand.SecretsHub commands: SecretsHub prefix: SH - pinned: - - Connect-SHTenant description: >- Secrets Hub: secret stores, secrets, sync policies, scans, configuration and transformations. image: /SecretsHub/media/images/IdentityCommand.SecretsHub.png @@ -182,8 +170,6 @@ SecretsManager: repo: pspete/IdentityCommand.SecretsManager commands: SecretsManager prefix: SM - pinned: - - Connect-SMTenant description: >- Secrets Manager and Secure Workload Access: groups, workloads, issuers, authenticators, secrets, trust domains and signing keys. image: /SecretsManager/media/images/IdentityCommand.SecretsManager.png @@ -202,8 +188,6 @@ SecureAI: repo: pspete/IdentityCommand.SecureAI commands: SecureAI prefix: SAI - pinned: - - Connect-SAITenant description: >- Secure AI: AI agents, MCP servers and their access policies. image: /SecureAI/media/images/IdentityCommand.SecureAI.png @@ -222,8 +206,6 @@ UAP: repo: pspete/IdentityCommand.UAP commands: UAP prefix: UAP - pinned: - - Connect-UAPTenant description: >- Access Control Policies: build, change, validate and remove access policies. image: /UAP/media/images/IdentityCommand.UAP.png @@ -242,8 +224,6 @@ UserPortal: repo: pspete/IdentityCommand.UserPortal commands: UserPortal prefix: UP - pinned: - - Connect-UPTenant description: >- Access: the user portal view of assets and their secrets. image: /UserPortal/media/images/IdentityCommand.UserPortal.png diff --git a/docs/authentication.md b/docs/authentication.md index 294c824..78ed13c 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -14,6 +14,12 @@ PS C:\> $Credential = Get-Credential PS C:\> New-IDSession -tenant_url https://sometenant.id.cyberark.cloud -Credential $Credential ``` +Instead of the Identity URL, give the tenant's shared services subdomain - `sometenant` for `https://sometenant.cyberark.cloud` - and the Identity URL is found through platform discovery: + +```powershell +PS C:\> New-IDSession -subdomain sometenant -Credential $Credential +``` + Initial authentication progresses through selection and answer of any required MFA challenges, including out-of-band and SAML-based flows. ## Service user authentication @@ -25,6 +31,8 @@ PS C:\> $Credential = Get-Credential PS C:\> New-IDPlatformToken -tenant_url https://sometenant.id.cyberark.cloud -Credential $Credential ``` +`New-IDPlatformToken` also accepts `-subdomain` in place of `-tenant_url`. + This allows authentication using a separate, dedicated service user for API activities. Consult the vendor documentation for guidance on setting up a dedicated API service user for non-interactive use. diff --git a/docs/collections/_commands/New-IDPlatformToken.md b/docs/collections/_commands/New-IDPlatformToken.md index bd03390..a7dd5b8 100644 --- a/docs/collections/_commands/New-IDPlatformToken.md +++ b/docs/collections/_commands/New-IDPlatformToken.md @@ -12,11 +12,18 @@ Request authentication token using OAuth ## SYNTAX +### URL ``` New-IDPlatformToken [-tenant_url] [-Credential] [-WhatIf] [-Confirm] [] ``` +### Subdomain +``` +New-IDPlatformToken -tenant_subdomain [-Credential] [-WhatIf] [-Confirm] + [] +``` + ## DESCRIPTION Gets a CyberArk Identity Security Platform OIDC token based on grant type. @@ -29,6 +36,13 @@ PS C:\> New-IDPlatformToken -tenant_url https://sometenant.id.cyberark.cloud -Cr Initiates OAuth confidential client service user authentication to specified tenant +### Example 2 +``` +PS C:\> New-IDPlatformToken -subdomain sometenant -Credential $Cred +``` + +Initiates OAuth confidential client service user authentication to the CyberArk Identity tenant of the `sometenant` shared services subdomain, found through platform discovery. + ## PARAMETERS ### -tenant_url @@ -36,7 +50,7 @@ The URL of the CyberArk Identity tenant to authenticate to. ```yaml Type: String -Parameter Sets: (All) +Parameter Sets: URL Aliases: Required: True @@ -92,6 +106,22 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -tenant_subdomain +The shared services subdomain of the tenant, the first part of its platform URL: `sometenant` for `https://sometenant.cyberark.cloud`. +The CyberArk Identity tenant URL is found from it through platform discovery. + +```yaml +Type: String +Parameter Sets: Subdomain +Aliases: subdomain + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/docs/collections/_commands/New-IDSession.md b/docs/collections/_commands/New-IDSession.md index 3090e2d..95c9e8f 100644 --- a/docs/collections/_commands/New-IDSession.md +++ b/docs/collections/_commands/New-IDSession.md @@ -12,19 +12,31 @@ Authenticates a user to a CyberArk Identity tenant. ## SYNTAX -### Credential +### URLCredential ``` New-IDSession [-tenant_url] [-Credential] [-WhatIf] [-Confirm] [] ``` -### SAML +### URLSAML ``` New-IDSession [-tenant_url] -SAMLResponse [-WhatIf] [-Confirm] [] ``` +### SubdomainCredential +``` +New-IDSession -tenant_subdomain [-Credential] [-WhatIf] [-Confirm] [] +``` + +### SubdomainSAML +``` +New-IDSession -tenant_subdomain -SAMLResponse [-WhatIf] [-Confirm] [] +``` + ## DESCRIPTION Use this command to authenticate to CyberArk Identity. +Specify the tenant either by its CyberArk Identity URL, or by its shared services subdomain. + Allows a user to provide authentication details, and satisfy any required MFA challenges. Currently supports all Identity MFA authentication mechanisms except U2F & DUO. @@ -52,6 +64,13 @@ PS C:\> New-IDSession -tenant_url https://sometenant.id.cyberark.cloud -SAMLResp Authenticates to CyberArk Identity using SAML assertion from external IDP (obtained using PS-SAML-Interactive) +### Example 3 +``` +PS C:\> New-IDSession -subdomain sometenant -Credential $Cred +``` + +Initiates authentication to the CyberArk Identity tenant of the `sometenant` shared services subdomain (`https://sometenant.cyberark.cloud`), found through platform discovery. + ## PARAMETERS ### -Confirm @@ -74,7 +93,7 @@ Credential object containing username and password required to authenticate to C ```yaml Type: PSCredential -Parameter Sets: Credential +Parameter Sets: URLCredential, SubdomainCredential Aliases: Required: True @@ -105,7 +124,7 @@ The URL of the CyberArk Identity tenant to authenticate to. ```yaml Type: String -Parameter Sets: (All) +Parameter Sets: URLSAML, URLCredential Aliases: Required: True @@ -120,7 +139,7 @@ A SAML assertion obtained from an external IDP for the account with which to aut ```yaml Type: String -Parameter Sets: SAML +Parameter Sets: URLSAML, SubdomainSAML Aliases: Required: True @@ -130,6 +149,22 @@ Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` +### -tenant_subdomain +The shared services subdomain of the tenant, the first part of its platform URL: `sometenant` for `https://sometenant.cyberark.cloud`. +The CyberArk Identity tenant URL is found from it through platform discovery. + +```yaml +Type: String +Parameter Sets: SubdomainSAML, SubdomainCredential +Aliases: subdomain + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/docs/index.md b/docs/index.md index 59fa736..fe81c08 100644 --- a/docs/index.md +++ b/docs/index.md @@ -34,12 +34,11 @@ New-IDSession -tenant_url https://sometenant.id.cyberark.cloud -Credential (Get- {% endfor %} -## Pre-1.0.0 +## Versioning & feedback -- Expect changes, although we will do our best to keep these to a minimum. +- From 1.0.0, IdentityCommand follows semantic versioning: breaking changes come only in a major release. +- The companion modules are pre-1.0.0: their command names, parameters and grouping may still change. - Issues / PRs are encouraged & appreciated. -- Many commands are built from documented API shapes but not yet exercised against a live tenant - your feedback genuinely shapes what ships next. If you can try one against your own tenant, [open an issue](https://github.com/pspete/IdentityCommand/issues/new) with what you found. -- Real-world usage is still expected to shape command names, parameters, and how commands are grouped, so don't consider anything final yet. ## Coverage