Private/Invoke-PASRestMethod.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
function Invoke-PASRestMethod {
    <#
.SYNOPSIS
Wrapper for Invoke-WebRequest to call REST method via API

.DESCRIPTION
Sends requests to web services, and where appropriate returns structured data.
Acts as wrapper for the Invoke-WebRequest CmdLet so that status codes can be
queried and acted on.
All requests are sent with ContentType=application/json.
If the sessionVariable parameter is passed, the function will return a WebSession
object to be used on subsequent calls to the web service.

.PARAMETER Method
The method for the REST Method.
Only accepts GET, POST, PUT, PATCH or DELETE

.PARAMETER URI
The address of the API or service to send the request to.

.PARAMETER Body
The body of the request to send to the API

.PARAMETER Headers
The header of the request to send to the API.

.PARAMETER SessionVariable
If passed, will be sent to invoke-webrequest which in turn will create a websession
variable using the string value as the name. This variable will only exist in the current scope
so will be returned as a WebSession property in the output object.
Cannot be specified with WebSession

.PARAMETER WebSession
Accepts a WebRequestSession object containing session details
Cannot be specified with SessionVariable

.PARAMETER UseDefaultCredentials
See Invoke-WebRequest
Used for Integrated Auth

.PARAMETER TimeoutSec
See Invoke-WebRequest
Specify a timeout value in seconds

.EXAMPLE

.INPUTS

.OUTPUTS
Return data from the call to the REST API where content is returned
Will additionally contain a WebSession property containing a WebRequestSession object if SessionVariable
parameter was specified.

.NOTES
SessionVariable/WebSession functionality should be used where the API exists behind a load balancer
to ensure session persistence.

.LINK

#>

    [CmdletBinding(DefaultParameterSetName = "WebSession")]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateSet('GET', 'POST', 'PUT', 'DELETE', 'PATCH')]
        [String]$Method,

        [Parameter(Mandatory = $true)]
        [String]$URI,

        [Parameter(Mandatory = $false)]
        [String]$Body,

        [Parameter(Mandatory = $false)]
        [hashtable]$Headers,

        [Parameter(
            Mandatory = $false,
            ParameterSetName = "SessionVariable"
        )]
        [String]$SessionVariable,

        [Parameter(
            Mandatory = $false,
            ParameterSetName = "WebSession"
        )]
        [Microsoft.PowerShell.Commands.WebRequestSession]$WebSession,

        [Parameter(Mandatory = $false)]
        [switch]$UseDefaultCredentials,

        [Parameter(Mandatory = $false)]
        [int]$TimeoutSec
    )

    Begin {

        #Get the name of the function which invoked this one
        $CallingFunction = Get-ParentFunction | Select-Object -ExpandProperty FunctionName
        Write-Debug "Function: $($MyInvocation.InvocationName)"
        Write-Debug "Invocation Origin: $CallingFunction"

        #Add ContentType for all function calls
        $PSBoundParameters.Add("ContentType", 'application/json')
        $PSBoundParameters.Add("UseBasicParsing", $true)

        #Bypass strict RFC header parsing in PS Core
        if ($PSVersionTable.PSEdition -eq "Core") {

            $PSBoundParameters.Add("SkipHeaderValidation", $true)
            $PSBoundParameters.Add("SslProtocol", "TLS12")

        }

        #If Tls12 Security Protocol is available
        if(([Net.SecurityProtocolType].GetEnumNames() -contains "Tls12") -and

            #And Tls12 is not already in use
            (-not ([System.Net.ServicePointManager]::SecurityProtocol -match "Tls12"))) {

            Write-Verbose "Setting Security Protocol to TLS12"
            [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

        }

        Else {

            Write-Debug "Security Protocol: $([System.Net.ServicePointManager]::SecurityProtocol)"

        }

    }

    Process {

        try {

            #make web request, splat PSBoundParameters
            $webResponse = Invoke-WebRequest @PSBoundParameters -ErrorAction Stop

            $StatusCode = $webResponse.StatusCode

        }

        catch {

            #Catch any errors, save response
            $StatusCode = $($_.Exception.Response).StatusCode.value__

            Write-Debug $_

            $response = $_

        }

        finally {

            Write-Debug "Status code: $StatusCode"

            if( -not ($StatusCode -match "20*")) {

                #Non 20X Status Codes & No Status Code
                <#
                    400 - Bad Request
                    401 - Unauthorised
                    403 - Forbidden
                    409 - already exists (CONFLICT)
                    404 - not found
                    500 - server error
                    503 - service unavailable
                #>


                Try {

                    $response = $response | ConvertFrom-Json
                    $ErrorMessage = "[$StatusCode] $($response.ErrorMessage)"
                    $ErrorID = $response.ErrorCode

                } Catch {

                    $ErrorMessage = $response -replace "`n", " "
                    $ErrorID = $StatusCode

                } Finally {

                    Write-Error -Message $ErrorMessage -ErrorId $ErrorID

                }

            }

            else {

                #status code is of type 20x
                #If there is a response from the web request
                if($webResponse) {

                    <#
                    200 - OK
                    201 - Created
                    202 - Accepted
                    204 - No Content
                    #>


                    #If Response has content
                    if($webResponse.content) {

                        if(($webResponse.headers)["Content-Type"] -match "application/octet-stream") {

                            if($($webResponse.content | get-member | select-object -expandproperty typename) -eq "System.Byte" ) {

                                $webResponse.content

                            }

                        }

                        elseif(($webResponse.headers)["Content-Type"] -match "application/save") {

                            #'application/save' is the Content-Type returned when saving a PSM recording
                            if($($webResponse.content | get-member | select-object -expandproperty typename) -eq "System.Byte" ) {

                                $webResponse.content

                            }

                        }

                        elseif(($webResponse.headers)["Content-Type"] -match "text/html") {

                            Write-Debug "$($webResponse.content)"

                            If($webResponse.content -match '^"(.*)"$') {
                                #Return only the text between opening and closing quotes
                                $matches[1]
                            } ElseIf($webResponse.content -match '<HTML>') {
                                throw "Guru Meditation - HTML Response Received"
                            }

                        }

                        Elseif(($webResponse.headers)["Content-Type"] -match "application/json") {

                            #Create Return Object from Returned JSON
                            $PASResponse = ConvertFrom-Json -InputObject $webResponse.content

                            #Handle Version 10 Logon Token Return
                            If(($CallingFunction -eq "New-PASSession") -and ($PASResponse.length -eq 180)) {

                                Write-Verbose "Assigning token to CyberArkLogonResult"
                                #If calling function is New-PASSession, and result is a 180 character token
                                #Create a new object and assign the token to the CyberArkLogonResult property.
                                #This ensures an object is returned instead of a string (which would cause issues).
                                $PASResponse = [PSCustomObject]@{

                                    CyberArkLogonResult = $PASResponse

                                }

                            }

                            #If Session Variable passed as argument
                            If($PSBoundParameters.ContainsKey("SessionVariable")) {

                                Write-verbose "SessionVariable Passed; Processing WebSession"

                                #Add WebSession Object to Return Object
                                $PASResponse | Add-ObjectDetail -PropertyToAdd @{

                                    #WebSession is stored in sessionVariable variable in current scope
                                    "WebSession" = $(Get-Variable $(Get-Variable sessionVariable).Value).Value

                                } -Passthru $false

                            }

                            #Return Object
                            $PASResponse

                        }

                        Else {

                            throw $([System.Text.Encoding]::ASCII.GetString($($webResponse.content)))

                        }

                    }

                }

            }

        }

    }

}