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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
function Invoke-PASRestMethod {
    <#
    .SYNOPSIS
    Wrapper for Invoke-WebRequest to call REST method via API

    .DESCRIPTION
    Sends requests to web services. Catches Exceptions. Outputs Success.
    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 the WebSession
    object to the $Script:WebSession variable.

    .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 set as the value of $Script:WebSession to be available in a modules scope.
    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 Credential
    See Invoke-WebRequest
    Used for Integrated Auth

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

    .PARAMETER Certificate
    See Invoke-WebRequest
    The client certificate used for a secure web request.

    .PARAMETER CertificateThumbprint
    See Invoke-WebRequest
    The thumbprint of the certificate to use for client certificate authentication.

    .PARAMETER SkipCertificateCheck
    Skips certificate validation checks.

    .EXAMPLE
    Invoke-PASRestMethod -Uri $URI -Method DELETE -WebSession $Script:WebSession

    Send request to web service
    #>

    [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)]
        [PSCredential]$Credential,

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

        [Parameter(Mandatory = $false)]
        [X509Certificate]$Certificate,

        [Parameter(Mandatory = $false)]
        [string]$CertificateThumbprint,

        [Parameter(Mandatory = $false)]
        [switch]$SkipCertificateCheck
    )

    Begin {

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

        #Bypass strict RFC header parsing in PS Core
        #Use TLS 1.2
        if (Test-IsCoreCLR) {

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

        }

        Switch ($PSBoundParameters.ContainsKey("SkipCertificateCheck")) {

            $true {

                #SkipCertificateCheck Declared
                if ( -not (Test-IsCoreCLR)) {

                    #Remove parameter, incompatible with PowerShell
                    $PSBoundParameters.Remove("SkipCertificateCheck") | Out-Null

                    if ($SkipCertificateCheck) {

                        #Skip SSL Validation
                        Skip-CertificateCheck

                    }

                }
                else {

                    #PWSH
                    if ($SkipCertificateCheck) {

                        #Ongoing SSL Validation Bypass Required
                        $Script:SkipCertificateCheck = $true

                    }

                }

            }

            $false {

                #SkipCertificateCheck Not Declared
                #SSL Validation Bypass Previously Requested
                If ($Script:SkipCertificateCheck) {

                    #PWSH Zone
                    if (Test-IsCoreCLR) {

                        #Add SkipCertificateCheck to PS Core command
                        #Parameter must be included for all pwsh invocations of Invoke-WebRequest
                        $PSBoundParameters.Add("SkipCertificateCheck", $true)

                    }

                }

            }

        }

        #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"))) {

            [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

        }

    }

    Process {

        #Show sanitised request body if in debug mode
        If ([System.Management.Automation.ActionPreference]::SilentlyContinue -ne $DebugPreference) {

            If ($PSBoundParameters.ContainsKey("Body")) {

                Write-Debug "[Body] $(Hide-SecretValue -InputValue $Body)"

            }

        }

        try {

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

        }
        catch [System.UriFormatException] {

            #Catch URI Format errors. Likely $Script:BaseURI is not set; New-PASSession should be run.
            $PSCmdlet.ThrowTerminatingError(

                [System.Management.Automation.ErrorRecord]::new(

                    "$PSItem Run New-PASSession",
                    $null,
                    [System.Management.Automation.ErrorCategory]::NotSpecified,
                    $PSItem

                )

            )

        }
        catch {

            $ErrorID = $null
            $StatusCode = $($PSItem.Exception.Response).StatusCode.value__
            $ErrorMessage = $($PSItem.Exception.Message)

            $Response = $PSItem.Exception | Select-Object -ExpandProperty 'Response' -ErrorAction Ignore
            if ( $Response ) {

                $ErrorDetails = $($PSItem.ErrorDetails)
            }

            # Not an exception making the request or the failed request didn't have a response body.
            if ( $null -eq $ErrorDetails ) {

                throw $PSItem

            }
            Else {

                If (-not($StatusCode)) {

                    #Generic failure message if no status code/response
                    $ErrorMessage = "Error contacting $($PSItem.TargetObject.RequestUri.AbsoluteUri)"

                }
                ElseIf ($ErrorDetails) {

                    try {

                        #Convert ErrorDetails JSON to Object
                        $Response = $ErrorDetails | ConvertFrom-Json

                        #API Error Message
                        $ErrorMessage = "[$StatusCode] $($Response.ErrorMessage)"

                        #API Error Code
                        $ErrorID = $Response.ErrorCode

                        #Inner error details are present
                        if ($Response.Details) {

                            #Join Inner Error Text to Error Message
                            $ErrorMessage = $ErrorMessage, $(($Response.Details | Select-Object -ExpandProperty ErrorMessage) -join ", ") -join ": "

                            #Join Inner Error Codes to ErrorID
                            $ErrorID = $ErrorID, $(($Response.Details | Select-Object -ExpandProperty ErrorCode) -join ",") -join ","

                        }

                    }
                    catch {

                        #If error converting JSON, return $ErrorDetails
                        #replace any new lines or whitespace with single spaces
                        $ErrorMessage = $ErrorDetails -replace "(`n|\W+)", " "
                        #Use $StatusCode as ErrorID
                        $ErrorID = $StatusCode

                    }
                }

            }

            #throw the error
            $PSCmdlet.ThrowTerminatingError(

                [System.Management.Automation.ErrorRecord]::new(

                    $ErrorMessage,
                    $ErrorID,
                    [System.Management.Automation.ErrorCategory]::NotSpecified,
                    $PSItem

                )

            )

        }
        finally {

            #If Session Variable passed as argument
            If ($PSCmdlet.ParameterSetName -eq "SessionVariable") {

                #Make the WebSession available in the module scope
                Set-Variable -Name WebSession -Value $(Get-Variable $(Get-Variable sessionVariable).Value).Value -Scope Script

            }

            #If Command Succeeded
            if ($?) {

                #Status code indicates success
                If ($APIResponse.StatusCode -match '^20\d$') {

                    #Pass APIResponse to Get-PASResponse
                    $APIResponse | Get-PASResponse

                }

            }

        }

    }

    End { }

}