From 9ba8401aad90c436b9a6812eb32762de60a83b24 Mon Sep 17 00:00:00 2001 From: Pete Maan Date: Fri, 9 Oct 2026 13:33:42 +0100 Subject: [PATCH 01/12] =?UTF-8?q?=E2=9A=A1=20Cache=20CurrentUser=20modules?= =?UTF-8?q?=20in=20CI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 26 +++++++++++++++++++------- CHANGELOG.md | 4 +++- 2 files changed, 22 insertions(+), 8 deletions(-) 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..2335174 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,9 @@ All notable changes to this project will be documented in this file. ## Unreleased -- N/A +### Changed + +- CI caches the PowerShell modules it installs, so dependency installs skip the PowerShell Gallery on a cache hit. ## [0.8.0] - 2026-10-08 From 3db8a56e6248193c959d4170b74fa6c80e9f88ae Mon Sep 17 00:00:00 2001 From: Pete Maan Date: Mon, 12 Oct 2026 19:38:05 +0100 Subject: [PATCH 02/12] =?UTF-8?q?=E2=9C=A8=20Resolve=20companion=20module?= =?UTF-8?q?=20service=20URLs=20from=20the=20IdentityCommand=20session?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Record the shared services subdomain from the session token claims on New-IDSession and New-IDPlatformToken, and clear it on Close-IDSession. Add private helpers for companion modules: - ConvertFrom-JwtPayload decodes token claims - Resolve-RequestUrl syncs the module session with the IdentityCommand session, resolves the service URL by platform discovery on first use, and drops the module session once the IdentityCommand session closes --- IdentityCommand/IdentityCommand.psm1 | 1 + .../Private/ConvertFrom-JwtPayload.ps1 | 52 +++++ .../Private/Resolve-RequestUrl.ps1 | 107 +++++++++++ .../Public/Authentication/Close-IDSession.ps1 | 1 + .../Authentication/New-IDPlatformToken.ps1 | 4 + .../Public/Authentication/New-IDSession.ps1 | 4 + Tests/ConvertFrom-JwtPayload.Tests.ps1 | 60 ++++++ Tests/New-IDPlatformToken.Tests.ps1 | 23 +++ Tests/Resolve-RequestUrl.Tests.ps1 | 179 ++++++++++++++++++ 9 files changed, 431 insertions(+) create mode 100644 IdentityCommand/Private/ConvertFrom-JwtPayload.ps1 create mode 100644 IdentityCommand/Private/Resolve-RequestUrl.ps1 create mode 100644 Tests/ConvertFrom-JwtPayload.Tests.ps1 create mode 100644 Tests/Resolve-RequestUrl.Tests.ps1 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/Resolve-RequestUrl.ps1 b/IdentityCommand/Private/Resolve-RequestUrl.ps1 new file mode 100644 index 0000000..edcfd36 --- /dev/null +++ b/IdentityCommand/Private/Resolve-RequestUrl.ps1 @@ -0,0 +1,107 @@ +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 $Script:ServiceKey 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 set by the companion module's Connect- command 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. + + .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 + ) + + process { + + $IDSession = Get-IDSession + + 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 + + } + + 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" + } + + $ISPSSSession.tenant_url = (Resolve-ServiceUrl -Service $Service -Subdomain $ISPSSSession.Subdomain).ServiceUrl + + } + + if ([string]::IsNullOrEmpty($Path)) { + $ISPSSSession.tenant_url + } else { + "$($ISPSSSession.tenant_url)/$($Path -replace '^/', '')" + } + + } + +} 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..9c91c0b 100644 --- a/IdentityCommand/Public/Authentication/New-IDPlatformToken.ps1 +++ b/IdentityCommand/Public/Authentication/New-IDPlatformToken.ps1 @@ -22,6 +22,7 @@ Function New-IDPlatformToken { Begin { #Remove WebSession which may exist in module scope $ISPSSSession.WebSession = $null + $ISPSSSession.Subdomain = $null $LogonRequest = @{ } $LogonRequest['Method'] = 'POST' @@ -79,6 +80,9 @@ 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 } + #Return the result $result diff --git a/IdentityCommand/Public/Authentication/New-IDSession.ps1 b/IdentityCommand/Public/Authentication/New-IDSession.ps1 index df6a134..d4f6958 100644 --- a/IdentityCommand/Public/Authentication/New-IDSession.ps1 +++ b/IdentityCommand/Public/Authentication/New-IDSession.ps1 @@ -36,6 +36,7 @@ Function New-IDSession { #Remove WebSession which may exist in module scope $ISPSSSession.WebSession = $null + $ISPSSSession.Subdomain = $null $LogonRequest = @{ } $LogonRequest['Method'] = 'POST' @@ -245,6 +246,9 @@ $($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 } + #Return the result $result 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/New-IDPlatformToken.Tests.ps1 b/Tests/New-IDPlatformToken.Tests.ps1 index 0c939c7..5be2699 100644 --- a/Tests/New-IDPlatformToken.Tests.ps1 +++ b/Tests/New-IDPlatformToken.Tests.ps1 @@ -135,6 +135,29 @@ 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 + + } + } } diff --git a/Tests/Resolve-RequestUrl.Tests.ps1 b/Tests/Resolve-RequestUrl.Tests.ps1 new file mode 100644 index 0000000..d187c89 --- /dev/null +++ b/Tests/Resolve-RequestUrl.Tests.ps1 @@ -0,0 +1,179 @@ +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' + } + + } + + } + +} From c505393fa8e64f97cd4079f6d54fccc99f2fc222 Mon Sep 17 00:00:00 2001 From: Pete Maan Date: Mon, 12 Oct 2026 20:08:04 +0100 Subject: [PATCH 03/12] =?UTF-8?q?=E2=9C=A8=20Add=20session=20hooks=20and?= =?UTF-8?q?=20discovery=20endpoint=20selection=20to=20Resolve-RequestUrl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - SessionConnectedHook runs after the module connects, retried on failure - IndependentSession skips sync with the IdentityCommand session - ServiceEndpoint / Resolve-ServiceUrl -Endpoint read a non-api discovery URL (CEM bootstrap) --- .../Private/Resolve-RequestUrl.ps1 | 68 +++++++++++--- .../Private/Resolve-ServiceUrl.ps1 | 15 ++- Tests/Resolve-RequestUrl.Tests.ps1 | 91 +++++++++++++++++++ Tests/Resolve-ServiceUrl.Tests.ps1 | 15 ++- 4 files changed, 172 insertions(+), 17 deletions(-) diff --git a/IdentityCommand/Private/Resolve-RequestUrl.ps1 b/IdentityCommand/Private/Resolve-RequestUrl.ps1 index edcfd36..bd419e7 100644 --- a/IdentityCommand/Private/Resolve-RequestUrl.ps1 +++ b/IdentityCommand/Private/Resolve-RequestUrl.ps1 @@ -5,7 +5,7 @@ function Resolve-RequestUrl { .DESCRIPTION Used by the IdentityCommand.* companion modules, which copy this function into their own scope, - so $ISPSSSession and $Script:ServiceKey here are the companion module's own. + 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: @@ -23,6 +23,17 @@ function Resolve-RequestUrl { A service URL set by the companion module's Connect- command 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. @@ -31,6 +42,10 @@ function Resolve-RequestUrl { 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' @@ -50,31 +65,40 @@ function Resolve-RequestUrl { [string]$Path, [parameter(Mandatory = $false)] - [string]$Service = $Script:ServiceKey + [string]$Service = $Script:ServiceKey, + + [parameter(Mandatory = $false)] + [string]$Endpoint = $Script:ServiceEndpoint ) process { $IDSession = Get-IDSession + $Connected = $false - if (($null -eq $IDSession.StartTime) -and ($null -ne $ISPSSSession.StartTime)) { + 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 + } - #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)) { - if (($null -ne $IDSession.StartTime) -and ($IDSession.StartTime -ne $ISPSSSession.StartTime)) { + $ServiceUrl = if ($IDSession.Subdomain -eq $ISPSSSession.Subdomain) { $ISPSSSession.tenant_url } - $ServiceUrl = if ($IDSession.Subdomain -eq $ISPSSSession.Subdomain) { $ISPSSSession.tenant_url } + foreach ($key in $IDSession.keys) { + $ISPSSSession[$key] = $IDSession[$key] + } - foreach ($key in $IDSession.keys) { - $ISPSSSession[$key] = $IDSession[$key] - } + $ISPSSSession.tenant_url = $ServiceUrl + $Connected = $true - $ISPSSSession.tenant_url = $ServiceUrl + } } @@ -92,7 +116,23 @@ function Resolve-RequestUrl { throw "Unable to resolve the '$Service' service URL: the IdentityCommand session token does not include the shared services subdomain" } - $ISPSSSession.tenant_url = (Resolve-ServiceUrl -Service $Service -Subdomain $ISPSSSession.Subdomain).ServiceUrl + 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 { + #Run the hook again on the next request + $ISPSSSession.StartTime = $null + throw + } } 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/Tests/Resolve-RequestUrl.Tests.ps1 b/Tests/Resolve-RequestUrl.Tests.ps1 index d187c89..315a5bd 100644 --- a/Tests/Resolve-RequestUrl.Tests.ps1 +++ b/Tests/Resolve-RequestUrl.Tests.ps1 @@ -174,6 +174,97 @@ Describe $($PSCommandPath -Replace '.Tests.ps1') { } + 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 '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*" From b4f8bb018cf7acf0d1a4514478805fbb59b7805c Mon Sep 17 00:00:00 2001 From: Pete Maan Date: Mon, 12 Oct 2026 20:37:56 +0100 Subject: [PATCH 04/12] =?UTF-8?q?=F0=9F=90=9B=20Report=20the=20request=20e?= =?UTF-8?q?rror=20when=20a=20request=20fails?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A failed SessionVariable request no longer masks its error with a missing variable lookup, and an error response without a body reports the exception message instead of an empty one. --- CHANGELOG.md | 5 +++++ IdentityCommand/Private/Invoke-IDRestMethod.ps1 | 12 ++++++++++-- Tests/Invoke-IDRestMethod.Tests.ps1 | 13 +++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2335174..b743494 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,11 @@ All notable changes to this project will be documented in this file. - 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. + ## [0.8.0] - 2026-10-08 ### Added diff --git a/IdentityCommand/Private/Invoke-IDRestMethod.ps1 b/IdentityCommand/Private/Invoke-IDRestMethod.ps1 index afd068b..49faad0 100644 --- a/IdentityCommand/Private/Invoke-IDRestMethod.ps1 +++ b/IdentityCommand/Private/Invoke-IDRestMethod.ps1 @@ -269,6 +269,11 @@ } + #No message in the response body, report the exception + if ([string]::IsNullOrEmpty($ErrorMessage)) { + $ErrorMessage = $ISPSSSession.LastError.Exception.Message + } + #throw the error $PSCmdlet.ThrowTerminatingError( @@ -295,8 +300,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/Tests/Invoke-IDRestMethod.Tests.ps1 b/Tests/Invoke-IDRestMethod.Tests.ps1 index 0a1f199..3801360 100644 --- a/Tests/Invoke-IDRestMethod.Tests.ps1 +++ b/Tests/Invoke-IDRestMethod.Tests.ps1 @@ -395,6 +395,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 + } + } } From 9c589f2dafcec911c44247fdd8e0d95b3a0fba02 Mon Sep 17 00:00:00 2001 From: Pete Maan Date: Mon, 12 Oct 2026 20:44:50 +0100 Subject: [PATCH 05/12] =?UTF-8?q?=F0=9F=90=9B=20Send=20the=20Accept=20para?= =?UTF-8?q?meter=20as=20a=20request=20header?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Invoke-WebRequest has no Accept parameter, so every request passing -Accept failed. The header is sent with the request, and the WebSession's own Accept header is restored afterwards so it does not carry into later requests. --- CHANGELOG.md | 6 ++ .../Private/Invoke-IDRestMethod.ps1 | 31 ++++++++++ Tests/Invoke-IDRestMethod.Tests.ps1 | 56 +++++++++++++++++++ 3 files changed, 93 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2335174..1b70d19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ All notable changes to this project will be documented in this file. - CI caches the PowerShell modules it installs, so dependency installs skip the PowerShell Gallery on a cache hit. +### Fixed + +- 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 ### Added diff --git a/IdentityCommand/Private/Invoke-IDRestMethod.ps1 b/IdentityCommand/Private/Invoke-IDRestMethod.ps1 index afd068b..fa45c23 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'))) { @@ -287,6 +309,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 diff --git a/Tests/Invoke-IDRestMethod.Tests.ps1 b/Tests/Invoke-IDRestMethod.Tests.ps1 index 0a1f199..ebb4ed1 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 { From 8c31d0008f70ad7071c5d0bdb1b6b3f4c04ce4c5 Mon Sep 17 00:00:00 2001 From: Pete Maan Date: Mon, 12 Oct 2026 21:44:02 +0100 Subject: [PATCH 06/12] =?UTF-8?q?=F0=9F=93=9D=20Drop=20the=20Connect=20com?= =?UTF-8?q?mand=20reference=20from=20Resolve-RequestUrl=20help?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- IdentityCommand/Private/Resolve-RequestUrl.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/IdentityCommand/Private/Resolve-RequestUrl.ps1 b/IdentityCommand/Private/Resolve-RequestUrl.ps1 index bd419e7..32420e1 100644 --- a/IdentityCommand/Private/Resolve-RequestUrl.ps1 +++ b/IdentityCommand/Private/Resolve-RequestUrl.ps1 @@ -21,7 +21,7 @@ function Resolve-RequestUrl { 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 set by the companion module's Connect- command is used as is. + 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: From 12866f7ee2032623316e94e3b012cfcb22ff6bd3 Mon Sep 17 00:00:00 2001 From: Pete Maan Date: Mon, 12 Oct 2026 22:03:51 +0100 Subject: [PATCH 07/12] =?UTF-8?q?=F0=9F=93=9D=20Unpin=20the=20companion=20?= =?UTF-8?q?module=20Connect=20commands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/README.md | 2 +- docs/_data/menus.yml | 20 -------------------- 2 files changed, 1 insertion(+), 21 deletions(-) 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 From b23ceebd5cf22cdc4d797cbbc260ab2e267ea06f Mon Sep 17 00:00:00 2001 From: Pete Maan Date: Mon, 12 Oct 2026 22:08:40 +0100 Subject: [PATCH 08/12] =?UTF-8?q?=F0=9F=93=9D=20Replace=20the=20pre-1.0.0?= =?UTF-8?q?=20notice=20with=20the=20versioning=20policy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 10 +++++----- docs/index.md | 7 +++---- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 7f059a5..6f90f37 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 | | ------------------------ | -------------------------- | ---------------------------- | ------------------------- | ---------------------------- | @@ -182,7 +182,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/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 From 16977b077ce2091e71476cfe1bace5f482982cd1 Mon Sep 17 00:00:00 2001 From: Pete Maan Date: Mon, 12 Oct 2026 22:34:36 +0100 Subject: [PATCH 09/12] =?UTF-8?q?=F0=9F=90=9B=20Keep=20the=20Close-IDSessi?= =?UTF-8?q?on=20check=20after=20a=20failed=20connected=20hook?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A failed SessionConnectedHook cleared the module session StartTime, which the closed session check relies on, so the module kept sending requests after Close-IDSession. Clear the service URL instead, so the next request resolves it and runs the hook again. --- IdentityCommand/Private/Resolve-RequestUrl.ps1 | 4 ++-- Tests/Resolve-RequestUrl.Tests.ps1 | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/IdentityCommand/Private/Resolve-RequestUrl.ps1 b/IdentityCommand/Private/Resolve-RequestUrl.ps1 index 32420e1..ec486f8 100644 --- a/IdentityCommand/Private/Resolve-RequestUrl.ps1 +++ b/IdentityCommand/Private/Resolve-RequestUrl.ps1 @@ -129,8 +129,8 @@ function Resolve-RequestUrl { try { & $Script:SessionConnectedHook } catch { - #Run the hook again on the next request - $ISPSSSession.StartTime = $null + #Resolve the service URL and run the hook again on the next request + $ISPSSSession.tenant_url = $null throw } diff --git a/Tests/Resolve-RequestUrl.Tests.ps1 b/Tests/Resolve-RequestUrl.Tests.ps1 index 315a5bd..60e3dbb 100644 --- a/Tests/Resolve-RequestUrl.Tests.ps1 +++ b/Tests/Resolve-RequestUrl.Tests.ps1 @@ -237,6 +237,14 @@ Describe $($PSCommandPath -Replace '.Tests.ps1') { $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' From 9ded4639ea56bbcd19d6cde594775205dad34623 Mon Sep 17 00:00:00 2001 From: Pete Maan Date: Mon, 12 Oct 2026 22:49:05 +0100 Subject: [PATCH 10/12] =?UTF-8?q?=F0=9F=90=9B=20Leave=20no=20session=20aft?= =?UTF-8?q?er=20a=20failed=20sign-in?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New-IDSession and New-IDPlatformToken cleared the web session and subdomain when they started, but kept the earlier user and start time, so a failed sign-in left a session with no usable web session that companion modules took as still current. Clear the user and start time too. --- .../Public/Authentication/New-IDPlatformToken.ps1 | 4 +++- IdentityCommand/Public/Authentication/New-IDSession.ps1 | 4 +++- Tests/New-IDPlatformToken.Tests.ps1 | 9 +++++++++ Tests/New-IDSession.Tests.ps1 | 9 +++++++++ 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/IdentityCommand/Public/Authentication/New-IDPlatformToken.ps1 b/IdentityCommand/Public/Authentication/New-IDPlatformToken.ps1 index 9c91c0b..dfd0747 100644 --- a/IdentityCommand/Public/Authentication/New-IDPlatformToken.ps1 +++ b/IdentityCommand/Public/Authentication/New-IDPlatformToken.ps1 @@ -20,9 +20,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' diff --git a/IdentityCommand/Public/Authentication/New-IDSession.ps1 b/IdentityCommand/Public/Authentication/New-IDSession.ps1 index d4f6958..9b88584 100644 --- a/IdentityCommand/Public/Authentication/New-IDSession.ps1 +++ b/IdentityCommand/Public/Authentication/New-IDSession.ps1 @@ -34,9 +34,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' diff --git a/Tests/New-IDPlatformToken.Tests.ps1 b/Tests/New-IDPlatformToken.Tests.ps1 index 5be2699..46ac6bc 100644 --- a/Tests/New-IDPlatformToken.Tests.ps1 +++ b/Tests/New-IDPlatformToken.Tests.ps1 @@ -158,6 +158,15 @@ Describe $($PSCommandPath -Replace '.Tests.ps1') { } + 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 + } + } } diff --git a/Tests/New-IDSession.Tests.ps1 b/Tests/New-IDSession.Tests.ps1 index 367cac6..d6a70e4 100644 --- a/Tests/New-IDSession.Tests.ps1 +++ b/Tests/New-IDSession.Tests.ps1 @@ -93,6 +93,15 @@ 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 'Start-Authentication' { From 434e75d3fa28d6e090f2231166d8cc4f0a552a3b Mon Sep 17 00:00:00 2001 From: Pete Maan Date: Mon, 12 Oct 2026 22:49:05 +0100 Subject: [PATCH 11/12] =?UTF-8?q?=F0=9F=93=9D=20Add=20the=201.0.0=20releas?= =?UTF-8?q?e=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mark Unreleased as a major release, and add the entries for companion module support, the session Subdomain, and the failed sign-in change. --- CHANGELOG.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0da09f7..cc15b46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,10 +2,21 @@ All notable changes to this project will be documented in this file. -## Unreleased +## Unreleased (major) + +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. ### 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 From cf0b943bc0186fa88058971223d36fb65f964756 Mon Sep 17 00:00:00 2001 From: Pete Maan Date: Mon, 12 Oct 2026 23:03:19 +0100 Subject: [PATCH 12/12] =?UTF-8?q?=E2=9C=A8=20Add=20-subdomain=20to=20New-I?= =?UTF-8?q?DSession=20and=20New-IDPlatformToken?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Find the Identity URL from the tenant's shared services subdomain by platform discovery, as an alternative to -tenant_url. --- CHANGELOG.md | 2 + .../Authentication/New-IDPlatformToken.ps1 | 19 +- .../Public/Authentication/New-IDSession.ps1 | 56 +++++- .../en-US/IdentityCommand-help.xml | 186 ++++++++++++++++++ README.md | 8 + Tests/New-IDPlatformToken.Tests.ps1 | 67 +++++++ Tests/New-IDSession.Tests.ps1 | 58 ++++++ docs/authentication.md | 8 + .../_commands/New-IDPlatformToken.md | 32 ++- docs/collections/_commands/New-IDSession.md | 45 ++++- 10 files changed, 465 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc15b46..dab7af0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ All notable changes to this project will be documented in this file. 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 diff --git a/IdentityCommand/Public/Authentication/New-IDPlatformToken.ps1 b/IdentityCommand/Public/Authentication/New-IDPlatformToken.ps1 index dfd0747..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, @@ -33,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 '/$', '' @@ -84,6 +100,7 @@ Function New-IDPlatformToken { #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 9b88584..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 @@ -48,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 '/$', '' @@ -61,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 @@ -84,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) { @@ -209,7 +246,7 @@ $($IDSession.IdpRedirectShortUrl) break } - 'SAML' { + '*SAML' { #*Get Saml ID Token $IDSession = $LogonRequest | Complete-SamlAuthentication break @@ -250,6 +287,7 @@ $($IDSession.IdpRedirectShortUrl) #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 6f90f37..efd3dfe 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/Tests/New-IDPlatformToken.Tests.ps1 b/Tests/New-IDPlatformToken.Tests.ps1 index 46ac6bc..03d1949 100644 --- a/Tests/New-IDPlatformToken.Tests.ps1 +++ b/Tests/New-IDPlatformToken.Tests.ps1 @@ -169,6 +169,73 @@ Describe $($PSCommandPath -Replace '.Tests.ps1') { } + 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 + } + + } + } } \ No newline at end of file diff --git a/Tests/New-IDSession.Tests.ps1 b/Tests/New-IDSession.Tests.ps1 index d6a70e4..583005b 100644 --- a/Tests/New-IDSession.Tests.ps1 +++ b/Tests/New-IDSession.Tests.ps1 @@ -104,6 +104,64 @@ Describe $($PSCommandPath -Replace '.Tests.ps1') { } + 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' { It 'sends Start-Authentication request with expected credential' { 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).