-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathcreate-scan-from-github.mts
More file actions
362 lines (330 loc) · 9.46 KB
/
Copy pathcreate-scan-from-github.mts
File metadata and controls
362 lines (330 loc) · 9.46 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
import { mkdtempSync } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { debug } from '@socketsecurity/lib-stable/debug/output'
import { getDefaultLogger } from '@socketsecurity/lib-stable/logger/default'
import { handleCreateNewScan } from './handle-create-new-scan.mts'
import { REPORT_LEVEL_ERROR } from '../../constants/reporting.mjs'
import {
GITHUB_ERR_ABUSE_DETECTION,
GITHUB_ERR_AUTH_FAILED,
GITHUB_ERR_GRAPHQL_RATE_LIMIT,
GITHUB_ERR_RATE_LIMIT,
} from '../../util/git/github.mts'
import { fetchListAllRepos } from '../repository/fetch-list-all-repos.mts'
import { testAndDownloadManifestFiles } from './github-scan-manifest.mts'
import type { CResult, OutputKind } from '../../types.mts'
import type { SocketSdkSuccessResult } from '@socketsecurity/sdk-stable'
import { makeSure, selectFocus } from './create-scan-from-github-prompts.mts'
import {
getLastCommitDetails,
getRepoBranchTree,
getRepoDetails,
} from './create-scan-from-github-api.mts'
import {
cleanupPartialDownload,
downloadManifestFile,
streamDownloadWithFetch,
testAndDownloadManifestFile,
} from './github-scan-manifest.mts'
const logger = getDefaultLogger()
export type RepoListItem =
SocketSdkSuccessResult<'listRepositories'>['data']['results'][number]
export async function createScanFromGithub({
all,
githubApiUrl,
githubToken,
interactive,
orgGithub,
orgSlug,
outputKind,
repos,
}: {
all: boolean
githubApiUrl: string
githubToken: string
interactive: boolean
orgSlug: string
orgGithub: string
outputKind: OutputKind
repos: string
}): Promise<CResult<undefined>> {
let targetRepos: string[] = repos
.trim()
.split(',')
.map(r => r.trim())
.filter(Boolean)
if (all || !targetRepos.length) {
// Fetch from Socket API
const result = await fetchListAllRepos(orgSlug, {
direction: 'asc',
sort: 'name',
})
if (!result.ok) {
return result
}
targetRepos = result.data.results.map((obj: RepoListItem) => obj.slug || '')
}
targetRepos = targetRepos.map(s => s.trim()).filter(Boolean)
logger.info(`Have ${targetRepos.length} repo names to Scan!`)
logger.log('')
if (!targetRepos.length) {
return {
ok: false,
message: 'No repo found',
cause:
'You did not set the --repos value and/or the server responded with zero repos when asked for some. Unable to proceed.',
}
}
// Non-interactive or explicitly requested; just do it.
if (interactive && targetRepos.length > 1 && !all && !repos) {
const result = await selectFocus(targetRepos)
if (!result.ok) {
return result
}
targetRepos = result.data
}
// 10 is an arbitrary number. Maybe confirm whenever count>1 ?
// Do not ask to confirm when the list was given explicit.
if (interactive && (all || !repos) && targetRepos.length > 10) {
const sure = await makeSure(targetRepos.length)
if (!sure.ok) {
return sure
}
}
return scanGithubRepositories(targetRepos, {
githubApiUrl,
githubToken,
orgSlug,
orgGithub,
outputKind,
repos,
})
}
export async function scanGithubRepositories(
targetRepos: string[],
config: Parameters<typeof scanRepo>[1],
): Promise<CResult<undefined>> {
let scansCreated = 0
let reposScanned = 0
// Track a blocking error (rate limit / auth) so we can surface it
// instead of reporting silent success with "0 manifests". Without
// this, a rate-limited GitHub token made every repo fail its tree
// fetch, the outer loop swallowed each error, and the final summary
// ("N repos / 0 manifests") misled users into thinking the scan
// worked.
let blockingError: CResult<undefined> | undefined
const perRepoFailures: Array<{ repo: string; message: string }> = []
for (let i = 0, { length } = targetRepos; i < length; i += 1) {
const repoSlug = targetRepos[i]!
reposScanned += 1
const scanCResult = await scanRepo(repoSlug, config)
if (scanCResult.ok) {
const { scanCreated } = scanCResult.data
if (scanCreated) {
scansCreated += 1
}
continue
}
perRepoFailures.push({
repo: repoSlug,
message: scanCResult.message,
})
// Stop on rate-limit / auth failures: every subsequent repo will
// fail for the same reason and continuing only burns more quota
// while delaying the real error.
if (
scanCResult.message === GITHUB_ERR_ABUSE_DETECTION ||
scanCResult.message === GITHUB_ERR_AUTH_FAILED ||
scanCResult.message === GITHUB_ERR_GRAPHQL_RATE_LIMIT ||
scanCResult.message === GITHUB_ERR_RATE_LIMIT
) {
blockingError = {
ok: false,
message: scanCResult.message,
cause: scanCResult.cause,
}
break
}
}
if (blockingError) {
logger.fail(blockingError.message)
return blockingError
}
logger.success(reposScanned, 'GitHub repos processed')
logger.success(scansCreated, 'with supported Manifest files')
// If every repo failed but not for a known-blocking reason, treat
// the run as an error so scripts know something went wrong instead
// of inferring success from an ok: true with 0 scans.
if (
reposScanned > 0 &&
scansCreated === 0 &&
perRepoFailures.length === reposScanned
) {
const firstFailure = perRepoFailures[0]!
return {
ok: false,
message: 'All repos failed to scan',
cause:
`All ${reposScanned} repos failed to scan. First failure for ${firstFailure.repo}: ${firstFailure.message}. ` +
'Check the log above for per-repo details.',
}
}
return {
ok: true,
data: undefined,
}
}
export async function scanOneRepo(
repoSlug: string,
{
orgGithub,
orgSlug,
outputKind,
}: {
githubApiUrl: string
githubToken: string
orgSlug: string
orgGithub: string
outputKind: OutputKind
repos: string
},
): Promise<CResult<{ scanCreated: boolean }>> {
const repoResult = await getRepoDetails({
orgGithub,
repoSlug,
githubApiUrl: '',
githubToken: '',
})
if (!repoResult.ok) {
return repoResult
}
const { defaultBranch } = repoResult.data
logger.info(`Default branch: \`${defaultBranch}\``)
const treeResult = await getRepoBranchTree({
defaultBranch,
orgGithub,
repoSlug,
})
if (!treeResult.ok) {
return treeResult
}
const files = treeResult.data
if (!files.length) {
logger.warn(
'No files were reported for the default branch. Moving on to next repo.',
)
return { ok: true, data: { scanCreated: false } }
}
const tmpDir = mkdtempSync(path.join(os.tmpdir(), repoSlug))
debug(`init: temp dir for scan root ${tmpDir}`)
const downloadResult = await testAndDownloadManifestFiles({
defaultBranch,
files,
orgGithub,
repoSlug,
tmpDir,
})
if (!downloadResult.ok) {
return downloadResult
}
const commitResult = await getLastCommitDetails({
defaultBranch,
orgGithub,
repoSlug,
})
if (!commitResult.ok) {
return commitResult
}
const { lastCommitMessage, lastCommitSha, lastCommitter } = commitResult.data
// Make request for full scan
// I think we can just kick off the socket scan create command now...
await handleCreateNewScan({
autoManifest: false,
branchName: defaultBranch,
commitHash: lastCommitSha,
commitMessage: lastCommitMessage || '',
committers: lastCommitter || '',
cwd: tmpDir,
defaultBranch: true,
interactive: false,
orgSlug,
outputKind,
pendingHead: true,
pullRequest: 0,
reach: {
excludePaths: [],
runReachabilityAnalysis: false,
reachAnalysisMemoryLimit: 0,
reachAnalysisTimeout: 0,
reachConcurrency: 1,
reachDebug: false,
reachDetailedAnalysisLogFile: false,
reachDisableAnalytics: false,
reachDisableExternalToolChecks: false,
reachEnableAnalysisSplitting: false,
reachEcosystems: [],
reachExcludePaths: [],
reachLazyMode: false,
reachMinSeverity: '',
reachSkipCache: false,
reachUseOnlyPregeneratedSboms: false,
reachUseUnreachableFromPrecomputation: false,
reachVersion: undefined,
},
readOnly: false,
repoName: repoSlug,
report: false,
reportLevel: REPORT_LEVEL_ERROR,
targets: ['.'],
tmp: false,
// Auto-manifest is off here, so no build binary runs.
trustSocketJson: false,
})
return { ok: true, data: { scanCreated: true } }
}
export async function scanRepo(
repoSlug: string,
{
githubApiUrl,
githubToken,
orgGithub,
orgSlug,
outputKind,
repos,
}: {
githubApiUrl: string
githubToken: string
orgSlug: string
orgGithub: string
outputKind: OutputKind
repos: string
},
): Promise<CResult<{ scanCreated: boolean }>> {
logger.info(
`Requesting repo details from GitHub API for: \`${orgGithub}/${repoSlug}\`...`,
)
logger.group()
const result = await scanOneRepo(repoSlug, {
githubApiUrl,
githubToken,
orgSlug,
orgGithub,
outputKind,
repos,
})
logger.groupEnd()
logger.log('')
return result
}
// Interactive prompts extracted to keep this file under the 500-line File-size cap.
export { makeSure, selectFocus }
// GitHub API helpers extracted to keep this file under the 500-line File-size cap.
export { getLastCommitDetails, getRepoBranchTree, getRepoDetails }
// Manifest download helpers extracted to keep this file under the 500-line File-size cap.
export {
cleanupPartialDownload,
downloadManifestFile,
streamDownloadWithFetch,
testAndDownloadManifestFile,
}