-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathmain.ts
More file actions
466 lines (411 loc) · 13.3 KB
/
main.ts
File metadata and controls
466 lines (411 loc) · 13.3 KB
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
import * as core from '@actions/core'
import * as github from '@actions/github'
import {Context} from '@actions/github/lib/context'
import * as httpClient from '@actions/http-client'
import {
ApiClient,
Credential,
CredentialFetchingError,
JobDetails
} from './api-client'
import {PROXY_IMAGE_NAME, updaterImageName} from './docker-tags'
import {ImageService, MetricReporter} from './image-service'
import {getJobParameters} from './inputs'
import {Updater} from './updater'
export enum DependabotErrorType {
Unknown = 'actions_workflow_unknown',
Image = 'actions_workflow_image',
UpdateRun = 'actions_workflow_updater'
}
const FALLBACK_CONTAINER_REGISTRY =
'dependabot-acr-apim-production.azure-api.net'
const FEATURE_DISABLE_GHCR_PULL = 'disable-ghcr-pull'
const FEATURE_PULL_FROM_AZURE = 'azure-registry-backup'
let jobId: number
export async function run(context: Context): Promise<void> {
try {
botSay('starting update')
// Retrieve JobParameters from the Actions environment
const params = getJobParameters(context)
// The parameters will be null if the Action environment
// is not a valid Dependabot-triggered dynamic event.
if (params === null) {
botSay('finished: nothing to do')
return // TODO: This should be setNeutral in future
}
// Use environment variables if set and not empty, otherwise use parameters.
// The param values of job token and credentials token are kept to support backwards compatibility.
const jobToken = process.env.GITHUB_DEPENDABOT_JOB_TOKEN || params.jobToken
const credentialsToken =
process.env.GITHUB_DEPENDABOT_CRED_TOKEN || params.credentialsToken
// Validate jobToken and credentialsToken
if (!jobToken) {
const errorMessage = 'Github Dependabot job token is not set'
botSay(`finished: ${errorMessage}`)
core.setFailed(errorMessage)
return
}
if (!credentialsToken) {
const errorMessage = 'Github Dependabot credentials token is not set'
botSay(`finished: ${errorMessage}`)
core.setFailed(errorMessage)
return
}
jobId = params.jobId
core.setSecret(jobToken)
core.setSecret(credentialsToken)
const client = new httpClient.HttpClient('github/dependabot-action')
const apiClient = new ApiClient(client, params, jobToken, credentialsToken)
core.info('Fetching job details')
// If we fail to succeed in fetching the job details, we cannot be sure the job has entered a 'processing' state,
// so we do not try attempt to report back an exception if this fails and instead rely on the workflow run
// webhook as it anticipates scenarios where jobs have failed while 'enqueued'.
const details = await apiClient.getJobDetails()
// The dynamic workflow can specify which updater image to use. If it doesn't, fall back to the pinned version.
let updaterImage =
params.updaterImage || updaterImageName(details['package-manager'])
let proxyImage = PROXY_IMAGE_NAME
// The sendMetrics function is used to send metrics to the API client.
// It uses the package manager as a tag to identify the metric.
const sendMetricsWithPackageManager: MetricReporter = async (
name,
metricType,
value,
additionalTags = {}
) => {
try {
await apiClient.sendMetrics(name, metricType, value, {
package_manager: details['package-manager'],
...additionalTags
})
} catch (error) {
core.warning(
`Metric sending failed for ${name}: ${(error as Error).message}`
)
}
}
try {
const credentials = (await apiClient.getCredentials()) || []
const registryCredentials = credentialsFromEnv()
credentials.push(...registryCredentials)
const packagesCred = getPackagesCredential(details, context.actor)
if (packagesCred !== null) {
core.info('Adding GitHub Packages credential')
credentials.push(packagesCred)
}
core.startGroup('Pulling updater images')
let imagesPulled = false
let pullError: Error = new Error('No image source was configured')
const experiments =
(details?.experiments as {[key: string]: boolean}) || {}
if (experiments[FEATURE_DISABLE_GHCR_PULL] !== true) {
try {
// Using sendMetricsWithPackageManager wrapper to inject package manager tag to
// avoid passing additional parameters to ImageService.pull method
await ImageService.pull(updaterImage, sendMetricsWithPackageManager)
await ImageService.pull(proxyImage, sendMetricsWithPackageManager)
imagesPulled = true
} catch (error: unknown) {
if (error instanceof Error) {
pullError = error
}
}
}
if (!imagesPulled && experiments[FEATURE_PULL_FROM_AZURE]) {
core.warning('Primary image pull failed, attempting fallback')
updaterImage = `${FALLBACK_CONTAINER_REGISTRY}/${updaterImage}`
proxyImage = `${FALLBACK_CONTAINER_REGISTRY}/${proxyImage}`
try {
await ImageService.pull(updaterImage, sendMetricsWithPackageManager)
await ImageService.pull(proxyImage, sendMetricsWithPackageManager)
imagesPulled = true
} catch (error: unknown) {
if (error instanceof Error) {
pullError = error
}
}
}
if (!imagesPulled) {
await failJob(
apiClient,
'Error fetching updater images',
pullError,
DependabotErrorType.Image
)
return
}
core.endGroup()
try {
core.info('Starting update process')
const updater = new Updater(
updaterImage,
proxyImage,
apiClient,
details,
credentials
)
await updater.runUpdater()
} catch (error: unknown) {
if (error instanceof Error) {
await failJob(
apiClient,
'Dependabot encountered an error performing the update',
error,
DependabotErrorType.UpdateRun
)
return
}
}
botSay('finished')
} catch (error: unknown) {
if (error instanceof CredentialFetchingError) {
await failJob(
apiClient,
'Dependabot was unable to retrieve job credentials',
error,
DependabotErrorType.UpdateRun
)
} else if (error instanceof Error) {
await failJob(
apiClient,
'Dependabot was unable to start the update',
error
)
}
return
}
} catch (error: unknown) {
if (error instanceof Error) {
// If we've reached this point, we do not have a viable
// API client to report back to Dependabot API.
//
// We output the raw error in the Action logs and defer
// to workflow_run monitoring to detect the job failure.
setFailed('Dependabot encountered an unexpected problem', error)
botSay('finished: unexpected error')
}
}
}
export function getPackagesCredential(
jobDetails: JobDetails,
actor: string
): Credential | null {
const experiments =
(jobDetails?.experiments as {[key: string]: boolean}) || {}
const experimentName = 'automatic_github_packages_auth'
const alternateExperimentName = experimentName.replace(/_/g, '-')
const autoAuthWithPackages =
experiments[experimentName] ?? experiments[alternateExperimentName] ?? false
if (!autoAuthWithPackages) {
return null
}
const githubToken = process.env.GITHUB_TOKEN
if (!githubToken) {
core.warning(
'GITHUB_TOKEN is not set; cannot create GitHub Packages credential'
)
return null
}
core.setSecret(githubToken)
let credential: Credential | null = null
switch (jobDetails['package-manager']) {
case 'bundler':
credential = getRubyGemsPackagesCredential(jobDetails, actor, githubToken)
break
case 'docker':
case 'docker_compose':
case 'devcontainers':
credential = getDockerPackagesCredential(jobDetails, actor, githubToken)
break
case 'maven':
case 'gradle':
credential = getMavenPackagesCredential(jobDetails, actor, githubToken)
break
case 'bun':
case 'npm_and_yarn':
credential = getNpmPackagesCredential(jobDetails, actor, githubToken)
break
case 'nuget':
credential = getNuGetPackagesCredential(jobDetails, actor, githubToken)
break
}
return credential
}
function getRubyGemsPackagesCredential(
jobDetails: JobDetails,
actor: string,
githubToken: string
): Credential | null {
const host = 'rubygems.pkg.github.com'
const existingIndex = jobDetails['credentials-metadata'].findIndex(
c => c.type === 'rubygems_server' && (c.host || '').toLowerCase() === host
)
if (existingIndex !== -1) {
return null
}
// proxy expects `host` and `token` fields
return {
type: 'rubygems_server',
host,
token: `${actor}:${githubToken}`
}
}
function getDockerPackagesCredential(
jobDetails: JobDetails,
actor: string,
githubToken: string
): Credential | null {
const registry = 'ghcr.io'
const existingIndex = jobDetails['credentials-metadata'].findIndex(
c =>
c.type === 'docker_registry' &&
(c.registry || '').toLowerCase() === registry
)
if (existingIndex !== -1) {
return null
}
// proxy expects `registry`, `username`, and `password` fields
return {
type: 'docker_registry',
registry,
username: actor,
password: githubToken
}
}
function getMavenPackagesCredential(
jobDetails: JobDetails,
actor: string,
githubToken: string
): Credential | null {
const url = `https://maven.pkg.github.com/${jobDetails.source.repo.split('/')[0]}`
const existingIndex = jobDetails['credentials-metadata'].findIndex(
c =>
c.type === 'maven_repository' &&
(c.url || '').toLowerCase().replace(/\/$/, '') === url.toLowerCase()
)
if (existingIndex !== -1) {
return null
}
// proxy expects `url`, `username`, and `password` fields
return {
type: 'maven_repository',
url,
username: actor,
password: githubToken
}
}
function getNpmPackagesCredential(
jobDetails: JobDetails,
actor: string,
githubToken: string
): Credential | null {
const registry = 'npm.pkg.github.com'
const existingIndex = jobDetails['credentials-metadata'].findIndex(
c =>
c.type === 'npm_registry' && (c.registry || '').toLowerCase() === registry
)
if (existingIndex !== -1) {
return null
}
// proxy expects `registry` and `token` fields
return {
type: 'npm_registry',
registry,
token: `${actor}:${githubToken}`
}
}
function getNuGetPackagesCredential(
jobDetails: JobDetails,
actor: string,
githubToken: string
): Credential | null {
const orgName = jobDetails.source.repo.split('/')[0]
const feedUrl = `https://nuget.pkg.github.com/${orgName}/index.json`
const existingIndex = jobDetails['credentials-metadata'].findIndex(
c =>
c.type === 'nuget_feed' &&
(c.url || '').toLowerCase() === feedUrl.toLowerCase()
)
if (existingIndex !== -1) {
return null
}
// proxy expects `url` and allows either `token` or `username` and `password` fields
return {
type: 'nuget_feed',
url: feedUrl,
username: actor,
password: githubToken
}
}
async function failJob(
apiClient: ApiClient,
message: string,
error: Error,
errorType = DependabotErrorType.Unknown
): Promise<void> {
await apiClient.reportJobError({
'error-type': errorType,
'error-details': {
'action-error': error.message
}
})
await apiClient.markJobAsProcessed()
setFailed(message, error)
botSay('finished: error reported to Dependabot')
}
function botSay(message: string): void {
core.info(`🤖 ~ ${message} ~`)
}
function setFailed(message: string, error: Error | null): void {
if (jobId) {
message = [message, error, dependabotJobHelp()].filter(Boolean).join('\n\n')
}
core.setFailed(message)
}
function dependabotJobHelp(): string | null {
if (jobId) {
return `For more information see: ${dependabotJobUrl(
jobId
)} (write access to the repository is required to view the log)`
} else {
return null
}
}
function dependabotJobUrl(id: number): string {
const url_parts = [
process.env.GITHUB_SERVER_URL,
process.env.GITHUB_REPOSITORY,
'network/updates',
id
]
return url_parts.filter(Boolean).join('/')
}
export function credentialsFromEnv(): Credential[] {
const registriesProxyStr = process.env.GITHUB_REGISTRIES_PROXY
let credentialsStr: string
if (registriesProxyStr !== undefined) {
credentialsStr = Buffer.from(registriesProxyStr, 'base64').toString()
} else {
return []
}
let parsed: Credential[]
try {
parsed = JSON.parse(credentialsStr) as Credential[]
} catch {
// Don't log the error as it may contain sensitive information
parsed = []
botSay('Failed to parse GITHUB_REGISTRIES_PROXY environment variable')
}
const nonSecrets = ['type', 'url', 'username', 'host', 'replaces-base']
for (const e of parsed) {
// Mask credentials to reduce chance of accidental leakage in logs.
for (const key of Object.keys(e)) {
if (!nonSecrets.includes(key)) {
core.setSecret((e as Record<string, unknown>)[key] as string)
}
}
// TODO: Filter down to only credentials relevant to this job.
}
return parsed
}
run(github.context)