Private/Send-CIF3Api.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
function Send-CIF3Api {
    <#
    .SYNOPSIS
        Send a message to the CIFv3 API endpoint
 
    .DESCRIPTION
        Helper function that sends a message to the CIFv3 API endpoint.
 
        This function is used by other CIF3 functions.
 
    .PARAMETER Method
        CIF3 API method to call (GET, POST, DELETE, PATCH)
 
        Reference: https://github.com/csirtgadgets/bearded-avenger/blob/master/cif/httpd/views/help.py
 
    .PARAMETER Headers
        Hash table of headers to send with the CIF API request
 
    .PARAMETER Uri
        String uri of remote CIFv3 URL endpoint to contact. Defaults to /
 
    .PARAMETER Token
        CIFv3 token to use
 
    .PARAMETER Body
        Hash table of arguments to send to the CIF API.
 
    .PARAMETER Proxy
        Proxy server to use
 
    .PARAMETER ForceVerbose
        If specified, don't explicitly remove verbose output from Invoke-RestMethod
 
        *** WARNING ***
        This may expose your token in verbose output
 
    .FUNCTIONALITY
        CIF
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Method,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [hashtable]$Headers = @{ },

        [Parameter()]
        [hashtable]$Body = @{ },

        [ValidateNotNullOrEmpty()]
        [ValidateScript( {
                if (-not $_ -and -not $Script:CIF3.Token) {
                    throw 'Please supply a CIF Token with Set-CIF3Config -Token <token>'
                }
                elseif (-not $Script:CIF3.Uri) {
                    throw 'Please supply a remote Uri with Set-CIF3Config -Uri <remote url>'
                }
                else {
                    $true
                }
            })]
        [string]$Token = $Script:CIF3.Token,

        [string]$Proxy = $Script:CIF3.Proxy,

        [string]$Uri = $Script:CIF3.Uri,

        [switch]$ForceVerbose = $Script:CIF3.ForceVerbose
    )

    begin {

        $Params = @{
            Uri         = $Uri
            ErrorAction = 'Stop'
        }
        if ($Proxy) {
            $Params.Add('Proxy', $Proxy)
        }
        if (-not $ForceVerbose) {
            $Params.Add('Verbose', $false)
        }
        if ($ForceVerbose) {
            $Params.Add('Verbose', $true)
        }
        if ($Body.Count -gt 0) {
            if ($Method -ne 'GET') {
                Write-Verbose 'Adding JSON Body'
                [string]$Body = $Body | ConvertTo-Json -Compress
            }
            $Params.Add('Body', $Body)
        }
        $Headers.Authorization = "Token token=$Token"
        $Headers.Accept = 'application/vnd.cif.v3+json'
        $Headers.'User-Agent' = "CIF3/$($MyInvocation.MyCommand.Module.Version) (PowerShell Wrapper)"

    }

    process {

        try {
            $Response = $null
            $HashToStr = $Params | Out-String
            Write-Verbose "Calling CIF API $Uri with params $HashToStr ..."
            $Response = Invoke-RestMethod @Params -Headers $Headers -Method $Method -ContentType 'application/json'
    
        }
        catch {
            # (HTTP 429 is "Too Many Requests")
            if ($_.Exception.Response.StatusCode -eq 429) {
    
                # Get the time before we can try again.
                if ( $_.Exception.Response.Headers -and $_.Exception.Response.Headers.Contains('Retry-After') ) {
                    $RetryPeriod = $_.Exception.Response.Headers.GetValues('Retry-After')
                    if ($RetryPeriod -is [string[]]) {
                        $RetryPeriod = [int]$RetryPeriod[0]
                    }
                }
                else {
                    $RetryPeriod = 2
                }
                Write-Verbose "Sleeping [$RetryPeriod] seconds due to CIF 429 response"
                Start-Sleep -Seconds $RetryPeriod
                Send-CIF3Api @PSBoundParameters
    
            }
            elseif ($_.Exception.Response.StatusCode -eq 400) {
                Write-Warning -Exception $_.Exception -Message 'Server returned 400. Invalid search?'
            }
            elseif ($_.Exception.Response.StatusCode -eq 401) {
                Write-Error -Exception $_.Exception -Message 'Server returned 401 Unauthorized. Check your token?'
            }
            elseif ($_.Exception.Response.StatusCode -eq 408) {
                Write-Error -Exception $_.Exception -Message 'Server returned 408 timed out. Check connection to CIF instance?'
            }
            elseif ($_.Exception.Response.StatusCode -eq 422) {
                Write-Error -Exception $_.Exception -Message 'Server returned 422 run time error. Check CIF instance logs for more info.'
            }
            elseif ($null -ne $_.ErrorDetails.Message -and $_.ErrorDetails.Message -ne '') {
                # Convert the error-message to an object. (Invoke-RestMethod will not return data by-default if a 4xx/5xx status code is generated.)
                $_.ErrorDetails.Message
            }
            else {
                Write-Error -Exception $_.Exception -Message "CIFv3 API call failed: $_. Check remote Uri?"
            }
        }
    
        # Check to see if we have confirmation that our API call failed.
        # (Responses with exception-generating status codes are handled in the "catch" block above - this one is for errors that don't generate exceptions)
        if ($null -ne $Response -and $Response.message -ne 'success') {
            $Response
        }
        elseif ($Response) {
            Write-Output $Response
        }
        else {
            Write-Verbose "Something went wrong. `$Response is `$null"
        }

    }

    end {}
    
}