-
Notifications
You must be signed in to change notification settings - Fork 0
/
profile.ps1
394 lines (310 loc) · 12.6 KB
/
profile.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# Azure Functions profile.ps1
#
# This profile.ps1 will get executed every "cold start" of your Function App.
# "cold start" occurs when:
#
# * A Function App starts up for the very first time
# * A Function App starts up after being de-allocated due to inactivity
#
# You can define helper functions, run commands, or specify environment variables
# NOTE: any variables defined that are not environment variables will get reset after the first execution
# Authenticate with Azure PowerShell using MSI.
# Remove this if you are not planning on using MSI or Azure PowerShell.
# if ($env:MSI_SECRET) {
# Disable-AzContextAutosave -Scope Process | Out-Null
# Connect-AzAccount -Identity
# }
# Uncomment the next line to enable legacy AzureRm alias in Azure PowerShell.
# Enable-AzureRmAlias
# You can also define functions or aliases that can be referenced in any of your PowerShell functions.
Write-Host 'Loading StackExchange.Redis assembly'
# Load the StackExchange.Redis assembly
Add-Type -Path (Join-Path $PSScriptRoot './Relabeler/bin/netstandard2.0/StackExchange.Redis.dll')
# Import necessary modules
Import-Module Az.ApplicationInsights
Import-Module powershell-yaml
# if ([System.String]::IsNullOrEmpty($env:APPINSIGHTS_INSTRUMENTATIONKEY))
# {
# <#
# When developing and testing Azure Functions locally, accessing Azure services that rely
# on Managed Identities such as Azure Key Vault—can pose challenging. This is because
# the **Managed Identity endpoint (`http://169.254.169.254`)** is **only available within
# the Azure environment**. Consequently, the PowerShell script cannot access this endpoint
# when running on the local machine, resulting in authentication failures.
# #>
# $KeyVaultName = 'kvRelabeler'
# $SecretName = 'InstrumentationKey'
# # User-Assigned Managed Identity Client ID
# $UserAssignedIdentityClientId = $env:IDENTITY_CLIENT_ID
# # Azure Environment and Resource for Key Vault
# $VaultResource = 'https://vault.azure.net'
# # Obtain an Access Token using the User-Assigned Managed Identity
# $AccessTokenResponse = Invoke-RestMethod -Method Post -Uri "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2019-08-01&resource=$VaultResource&client_id=$UserAssignedIdentityClientId" -Headers @{Metadata = 'true' }
# $AccessToken = $AccessTokenResponse.access_token
# $SecretUri = "https://$KeyVaultName.vault.azure.net/secrets/$SecretName?api-version=7.0"
# # Retrieve the Instrumentation Key from Azure Key Vault
# $InstrumentationKey = (Invoke-RestMethod -Method GET -Headers @{Authorization = "Bearer $AccessToken" } -Uri $SecretUri).value
# $env:APPINSIGHTS_INSTRUMENTATIONKEY = $InstrumentationKey
# }
function Send-Metric
{
param
(
[Parameter()]
[string]$BaseName = 'RepositoryEvent', # The base name of the custom metric, e.g., "RepositoryEvent"
[Parameter(Mandatory = $true)]
[int]$value, # The numerical value of the metric.
[int]$count = 1, # The number of times the metric was sampled.
[Int16]$min = 0, # The minimum value of the metric.
[int]$max = $value, # The maximum value of the metric.
[int]$stdDev = 0, # The standard deviation of the metric.
[int]$sum = $value,
[Parameter(Mandatory = $true)]
[string]$organization, # The name of the organization the repository belongs to
[Parameter(Mandatory = $true)]
[string]$repository, # The name of the repository
[Parameter(Mandatory = $true)]
[string]$resource, # The resource type (e.g., 'Pull Request', 'Issue')
[Parameter(Mandatory = $true)]
[string]$eventType, # The event type (e.g., 'issue_comment')
[Parameter(Mandatory = $true)]
[string]$eventAction # The event action (e.g., 'opened')
)
# TODO: Make this configurable via an environment variable
# Application Insights Configuration
$IngestionEndpoint = 'https://dc.services.visualstudio.com/v2/track'
# Validate Repository parameter
if (-not $repository)
{
Write-Error 'Repository parameter is mandatory. Please provide a valid repository name.'
return
}
# Validate Resource parameter
if (-not $resource)
{
Write-Error "Resource parameter is mandatory. Please provide a valid resource type (e.g., 'Pull Request', 'Issue')."
return
}
# Validate Organization parameter
if (-not $organization)
{
Write-Error 'Organization parameter is mandatory. Please provide a valid organization name.'
return
}
# Validate EventType parameter
if (-not $eventType)
{
Write-Error "EventType parameter is mandatory. Please provide a valid event type (e.g., 'issue_comment')."
return
}
# Validate EventAction parameter
if (-not $eventAction)
{
Write-Error "EventAction parameter is mandatory. Please provide a valid event action (e.g., 'opened')."
return
}
$body = @{
name = "Microsoft.ApplicationInsights.$BaseName" # e.g., "Microsoft.ApplicationInsights.RepositoryEvent"
time = (Get-Date).ToUniversalTime().ToString('o')
iKey = $InstrumentationKey
data = @{
baseType = 'MetricData'
baseData = @{
metrics = @(
@{
name = $BaseName
value = $value
count = $count
min = $min
max = $max
stdDev = $stdDev
sum = $sum
dimensions = @(
@{
name = 'Organization'
value = $organization
},
@{
name = 'Repository'
value = $repository
},
@{
name = 'Resource'
value = $resource
},
@{
name = 'EventType'
value = $eventType
},
@{
name = 'EventAction'
value = $eventAction
}
)
}
)
}
}
} | ConvertTo-Json -Depth 10 -Compress
try
{
$null = Invoke-RestMethod -Method Post -ContentType 'application/json' -Body $body -Uri $IngestionEndpoint
Write-Host "Metric '$BaseName' sent successfully with value $value. Dimensions - Repository: '$repository', Resource: '$resource', EventType: '$eventType', EventAction: '$eventAction'."
}
catch
{
Write-Error "Failed to send metric '$name': $_"
}
}
function Get-RepoConfig
{
param
(
[string]$ApiUrl,
[string]$GithubToken
)
try
{
# This is to allow for local debugging with a local config file
if ([System.String]::IsNullOrEmpty($env:RELABELER_CONFIG_PATH))
{
$headers = @{
'Authorization' = "token $GithubToken"
'User-Agent' = 'AzureFunction-Relabeler'
}
$configPath = '.github/relabeler-config.yml'
$configApiUrl = "$ApiUrl/contents/$configPath"
Write-Information "Retrieving configuration from $configApiUrl." -InformationAction 'Continue'
$response = Invoke-RestMethod -Uri $configApiUrl -Headers $headers -Method Get -ErrorAction 'Stop'
# Decode the base64 content
$decodedBytes = [System.Convert]::FromBase64String($response.content)
# Convert bytes to UTF8 string
$content = [System.Text.Encoding]::UTF8.GetString($decodedBytes)
}
else
{
Write-Information "Using local config file: $env:RELABELER_CONFIG_PATH" -InformationAction 'Continue'
$content = Get-Content -Raw -Path $env:RELABELER_CONFIG_PATH
}
# Convert YAML to JSON
$configHashtable = $content | ConvertFrom-Yaml
$configJson = $configHashtable | ConvertTo-Json -Depth 10 -Compress
# Load JSON schema
$schemaPath = Resolve-Path -Path './Relabeler/schemas/relabeler-config.schema.json'
if (-not (Test-Path -Path $schemaPath))
{
Write-Error "Configuration schema file not found at path: $schemaPath"
return $null
}
# Validate the JSON against the schema using Test-Json
$isValid = Test-Json -Json $configJson -SchemaFile $schemaPath
if (-not $isValid)
{
Write-Error 'Configuration validation failed. JSON does not conform to the provided schema.'
return $null
}
Write-Information 'Configuration validated successfully against the schema.' -InformationAction 'Continue'
# Return the configuration as a PowerShell object
return [PSCustomObject] $configHashtable
}
catch
{
Write-Error "Failed to fetch or validate configuration: $_"
return $null
}
}
function Assert-GitHubPayloadSignature
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.Object]
$Request,
[Parameter(Mandatory = $true)]
[ref] $ResponseCode,
[Parameter(Mandatory = $true)]
[ref] $Body
)
Write-Host 'Validating payload signature.'
$secretPlainText = $env:RELABELER_WEBHOOK_SECRET
if (-not $secretPlainText)
{
Write-Error -Message 'RELABELER_WEBHOOK_SECRET environment variable is not set.'
$ResponseCode.Value = [HttpStatusCode]::InternalServerError
$Body.Value = 'Server configuration error.'
return
}
else
{
$secret = ConvertTo-SecureString -String $secretPlainText -AsPlainText -Force
}
$payloadString = $Request.RawBody
$sourceSignature = $Request.headers.'x-hub-signature-256'
if ([System.String]::IsNullOrEmpty($sourceSignature))
{
Write-Error -Message 'Missing x-hub-signature-256 header. Provide a valid signature to validate the payload.'
$ResponseCode.Value = [HttpStatusCode]::Unauthorized
$Body.Value = 'Missing x-hub-signature-256 header. Provide a valid signature to validate the payload.'
return
}
$isSignatureValid = Test-Sha256SignatureHash -PayloadString $payloadString -Secret $secret -SourceSignature $sourceSignature
if ($isSignatureValid)
{
Write-Host 'Signature is valid.'
$ResponseCode.Value = [HttpStatusCode]::OK
$Body.Value = $null
}
else
{
Write-Error -Message ('Payload sha256 hash signature ''{0}'' is not valid! Unauthorized.' -f $SourceSignature)
$ResponseCode.Value = [HttpStatusCode]::Unauthorized
$Body.Value = "Payload sha256 hash signature ''{0}'' is not valid! Unauthorized."
}
}
function Test-Sha256SignatureHash
{
param
(
[System.String]
$PayloadString,
[System.Security.SecureString]
$Secret,
[System.String]
$SourceSignature
)
# Get the calculated signature hash using the new function
$calculatedSignatureHash = Get-Sha256SignatureHash -PayloadString $PayloadString -Secret $Secret
# Compare the source signature with the calculated signature
if ($SourceSignature -eq $calculatedSignatureHash)
{
$result = $true
}
else
{
$result = $false
}
return $result
}
function Get-Sha256SignatureHash
{
param
(
[System.String]
$PayloadString,
[System.Security.SecureString]
$Secret
)
# Convert SecureString to plain text
$unsecureSecret = ConvertFrom-SecureString -SecureString $Secret -AsPlainText
$payloadData = [System.Text.Encoding]::UTF8.GetBytes($PayloadString)
$keyData = [System.Text.Encoding]::UTF8.GetBytes($unsecureSecret)
# cSpell: ignore HMACSHA256
$hmacSha256 = [System.Security.Cryptography.HMACSHA256]::new($keyData)
$payloadHash = $hmacSha256.ComputeHash($payloadData)
$hmacSha256.Dispose()
# Format the calculated signature
$calculatedSignatureHash = 'sha256={0}' -f ([BitConverter]::ToString($payloadHash) -replace '-', '').ToLower()
Write-Debug -Message "Calculated signature hash: $calculatedSignatureHash"
return $calculatedSignatureHash
}