Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 }}
Expand All @@ -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
Expand Down
27 changes: 25 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions IdentityCommand/IdentityCommand.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ $ISPSSSession = [ordered]@{
User = $null
TenantId = $null
SessionId = $null
Subdomain = $null
WebSession = $null
StartTime = $null
ElapsedTime = $null
Expand Down
52 changes: 52 additions & 0 deletions IdentityCommand/Private/ConvertFrom-JwtPayload.ps1
Original file line number Diff line number Diff line change
@@ -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 <jwt>).

.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

}

}
43 changes: 41 additions & 2 deletions IdentityCommand/Private/Invoke-IDRestMethod.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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'))) {

Expand Down Expand Up @@ -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(

Expand All @@ -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
Expand All @@ -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
}

}

Expand Down
147 changes: 147 additions & 0 deletions IdentityCommand/Private/Resolve-RequestUrl.ps1
Original file line number Diff line number Diff line change
@@ -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://<subdomain>.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 '^/', '')"
}

}

}
Loading
Loading