-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathcreate-scan-from-github.test.mts
More file actions
595 lines (523 loc) · 17.7 KB
/
create-scan-from-github.test.mts
File metadata and controls
595 lines (523 loc) · 17.7 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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/**
* Unit tests for GitHub scan internal functions.
*
* Purpose:
* Tests the internal functions that interact with GitHub API during scans.
* Validates proper error handling, rate limit detection, and data extraction
* from GitHub API responses.
*
* Test Coverage:
* - getRepoDetails: fetching repository metadata
* - getRepoBranchTree: fetching file tree
* - getLastCommitDetails: fetching latest commit SHA
* - Error handling for rate limits and API failures
*
* Testing Approach:
* Mocks Octokit to test the scan functions without actual GitHub API calls.
* Tests verify proper error propagation and user-friendly error messages.
*
* Related Files:
* - src/commands/scan/create-scan-from-github.mts (implementation)
* - src/utils/git/github.mts (GitHub utilities)
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
const mockOctokit = vi.hoisted(() => ({
repos: {
get: vi.fn(),
listCommits: vi.fn(),
getContent: vi.fn(),
},
git: {
getTree: vi.fn(),
},
}))
const mockWithGitHubRetry = vi.hoisted(() =>
vi.fn(async (operation: () => Promise<unknown>, context: string) => {
try {
const result = await operation()
return { ok: true, data: result }
} catch (e) {
return {
ok: false,
message: 'GitHub API error',
cause: `Error while ${context}: ${e instanceof Error ? e.message : String(e)}`,
}
}
}),
)
// Mock dependencies.
vi.mock('../../../../src/utils/git/github.mts', () => ({
GITHUB_ERR_ABUSE_DETECTION: 'GitHub abuse detection triggered',
GITHUB_ERR_AUTH_FAILED: 'GitHub authentication failed',
GITHUB_ERR_GRAPHQL_RATE_LIMIT: 'GitHub GraphQL rate limit exceeded',
GITHUB_ERR_RATE_LIMIT: 'GitHub rate limit exceeded',
getOctokit: vi.fn(() => mockOctokit),
withGitHubRetry: mockWithGitHubRetry,
}))
vi.mock('@socketsecurity/lib/debug', () => ({
debug: vi.fn(),
debugDir: vi.fn(),
}))
vi.mock('@socketsecurity/lib/logger', () => ({
getDefaultLogger: vi.fn(() => ({
fail: vi.fn(),
group: vi.fn(),
groupEnd: vi.fn(),
info: vi.fn(),
log: vi.fn(),
success: vi.fn(),
warn: vi.fn(),
})),
}))
// Mock other dependencies to isolate the functions under test.
vi.mock(
'../../../../src/commands/scan/fetch-supported-scan-file-names.mts',
() => ({
fetchSupportedScanFileNames: vi.fn().mockResolvedValue({
ok: true,
data: ['package.json', 'package-lock.json', 'yarn.lock'],
}),
}),
)
vi.mock('../../../../src/commands/scan/handle-create-new-scan.mts', () => ({
handleCreateNewScan: vi.fn().mockResolvedValue({ ok: true, data: undefined }),
}))
vi.mock('../../../../src/commands/repository/fetch-list-all-repos.mts', () => ({
fetchListAllRepos: vi.fn().mockResolvedValue({
ok: true,
data: { results: [{ slug: 'test-repo' }] },
}),
}))
// Import after mocks are set up.
// Note: We can't directly import the internal functions as they're not exported.
// Instead, we test them through the exported createScanFromGithub function
// or test the withGitHubRetry wrapper behavior.
describe('GitHub scan API interactions', () => {
beforeEach(() => {
vi.clearAllMocks()
})
describe('getRepoDetails behavior', () => {
it('handles successful repo details fetch', async () => {
mockOctokit.repos.get.mockResolvedValue({
data: {
default_branch: 'main',
name: 'test-repo',
full_name: 'org/test-repo',
},
})
// Call the mock to simulate the behavior.
const result = await mockWithGitHubRetry(async () => {
const { data } = await mockOctokit.repos.get({
owner: 'org',
repo: 'test-repo',
})
return data
}, 'fetching repository details for org/test-repo')
expect(result.ok).toBe(true)
if (result.ok) {
expect(result.data.default_branch).toBe('main')
}
})
it('handles rate limit error from repo details', async () => {
mockOctokit.repos.get.mockRejectedValue(
new Error('API rate limit exceeded'),
)
// Simulate withGitHubRetry returning a rate limit error.
mockWithGitHubRetry.mockResolvedValueOnce({
ok: false,
message: 'GitHub rate limit exceeded',
cause:
'GitHub API rate limit exceeded while fetching repository details. ' +
'Try again in a few minutes.\n\n' +
'To increase your rate limit:\n' +
'- Set GITHUB_TOKEN environment variable',
})
const result = await mockWithGitHubRetry(
async () => mockOctokit.repos.get({ owner: 'org', repo: 'test-repo' }),
'fetching repository details',
)
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.message).toBe('GitHub rate limit exceeded')
expect(result.cause).toContain('GITHUB_TOKEN')
}
})
it('handles 404 not found for repo', async () => {
mockOctokit.repos.get.mockRejectedValue(new Error('Not Found'))
mockWithGitHubRetry.mockResolvedValueOnce({
ok: false,
message: 'GitHub resource not found',
cause:
'GitHub resource not found while fetching repository details. ' +
'The repository may not exist or you may not have access.',
})
const result = await mockWithGitHubRetry(
async () =>
mockOctokit.repos.get({ owner: 'org', repo: 'nonexistent' }),
'fetching repository details',
)
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.message).toBe('GitHub resource not found')
}
})
})
describe('getRepoBranchTree behavior', () => {
it('handles successful tree fetch', async () => {
mockOctokit.git.getTree.mockResolvedValue({
data: {
sha: 'abc123',
tree: [
{ type: 'blob', path: 'package.json' },
{ type: 'blob', path: 'src/index.ts' },
{ type: 'tree', path: 'src' },
],
},
})
const result = await mockWithGitHubRetry(async () => {
const { data } = await mockOctokit.git.getTree({
owner: 'org',
repo: 'test-repo',
tree_sha: 'main',
recursive: 'true',
})
return data
}, 'fetching file tree for branch main in org/test-repo')
expect(result.ok).toBe(true)
if (result.ok) {
expect(result.data.tree).toHaveLength(3)
// Should filter to only blobs.
const files = result.data.tree
.filter((obj: any) => obj.type === 'blob')
.map((obj: any) => obj.path)
expect(files).toEqual(['package.json', 'src/index.ts'])
}
})
it('handles rate limit error during tree fetch', async () => {
mockWithGitHubRetry.mockResolvedValueOnce({
ok: false,
message: 'GitHub rate limit exceeded',
cause: 'GitHub API rate limit exceeded while fetching file tree.',
})
const result = await mockWithGitHubRetry(
async () => mockOctokit.git.getTree({ owner: 'org', repo: 'test' }),
'fetching file tree',
)
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.message).toBe('GitHub rate limit exceeded')
}
})
it('handles empty tree (empty repo)', async () => {
mockOctokit.git.getTree.mockResolvedValue({
data: {
sha: 'abc123',
tree: [],
},
})
const result = await mockWithGitHubRetry(async () => {
const { data } = await mockOctokit.git.getTree({
owner: 'org',
repo: 'empty-repo',
tree_sha: 'main',
recursive: 'true',
})
return data
}, 'fetching file tree')
expect(result.ok).toBe(true)
if (result.ok) {
expect(result.data.tree).toHaveLength(0)
}
})
})
describe('getLastCommitDetails behavior', () => {
it('handles successful commit fetch', async () => {
mockOctokit.repos.listCommits.mockResolvedValue({
data: [
{
sha: 'abc123def456',
commit: {
message: 'feat: add new feature',
author: { name: 'John Doe' },
committer: { name: 'John Doe' },
},
},
],
})
const result = await mockWithGitHubRetry(async () => {
const { data } = await mockOctokit.repos.listCommits({
owner: 'org',
repo: 'test-repo',
sha: 'main',
per_page: 1,
})
return data
}, 'fetching latest commit SHA for org/test-repo')
expect(result.ok).toBe(true)
if (result.ok) {
expect(result.data[0].sha).toBe('abc123def456')
expect(result.data[0].commit.message).toBe('feat: add new feature')
}
})
it('handles rate limit error during commit fetch (the original bug)', async () => {
// This is the exact scenario that caused "Cannot read properties of undefined (reading 'sha')".
mockWithGitHubRetry.mockResolvedValueOnce({
ok: false,
message: 'GitHub rate limit exceeded',
cause:
'GitHub API rate limit exceeded while fetching latest commit SHA. ' +
'Try again in a few minutes.',
})
const result = await mockWithGitHubRetry(
async () =>
mockOctokit.repos.listCommits({ owner: 'org', repo: 'test' }),
'fetching latest commit SHA',
)
// With the fix, we get a proper error instead of crashing.
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.message).toBe('GitHub rate limit exceeded')
// Should NOT crash with "Cannot read properties of undefined (reading 'sha')".
}
})
it('handles empty commits response', async () => {
mockOctokit.repos.listCommits.mockResolvedValue({
data: [],
})
const result = await mockWithGitHubRetry(async () => {
const { data } = await mockOctokit.repos.listCommits({
owner: 'org',
repo: 'empty-repo',
sha: 'main',
per_page: 1,
})
return data
}, 'fetching latest commit')
expect(result.ok).toBe(true)
if (result.ok) {
// The actual function checks for empty commits.
expect(result.data).toHaveLength(0)
}
})
})
describe('downloadManifestFile behavior', () => {
it('handles successful file content fetch', async () => {
mockOctokit.repos.getContent.mockResolvedValue({
data: {
type: 'file',
content: Buffer.from('{"name": "test"}').toString('base64'),
download_url:
'https://raw.githubusercontent.com/org/repo/main/package.json',
size: 16,
},
})
const result = await mockWithGitHubRetry(async () => {
const { data } = await mockOctokit.repos.getContent({
owner: 'org',
repo: 'test-repo',
path: 'package.json',
ref: 'main',
})
return data
}, 'fetching file content for package.json in org/test-repo')
expect(result.ok).toBe(true)
if (result.ok) {
expect(result.data.type).toBe('file')
expect(result.data.download_url).toContain('raw.githubusercontent.com')
}
})
it('handles rate limit during file fetch', async () => {
mockWithGitHubRetry.mockResolvedValueOnce({
ok: false,
message: 'GitHub rate limit exceeded',
cause: 'GitHub API rate limit exceeded while fetching file content.',
})
const result = await mockWithGitHubRetry(
async () =>
mockOctokit.repos.getContent({
owner: 'org',
repo: 'test',
path: 'package.json',
}),
'fetching file content',
)
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.message).toBe('GitHub rate limit exceeded')
}
})
})
})
describe('error message quality', () => {
it('provides actionable error messages for rate limits', () => {
const errorResult = {
ok: false as const,
message: 'GitHub rate limit exceeded',
cause:
'GitHub API rate limit exceeded while fetching commits. ' +
'Try again in a few minutes.\n\n' +
'To increase your rate limit:\n' +
'- Set GITHUB_TOKEN environment variable with a valid token\n' +
'- In GitHub Actions, GITHUB_TOKEN is automatically available',
}
expect(errorResult.cause).toContain('GITHUB_TOKEN')
expect(errorResult.cause).toContain('GitHub Actions')
expect(errorResult.cause).toContain('Try again')
})
it('provides context-specific error messages', () => {
const contexts = [
'fetching repository details for org/repo',
'fetching file tree for branch main in org/repo',
'fetching latest commit SHA for org/repo',
'fetching file content for package.json in org/repo',
]
for (const context of contexts) {
const errorResult = {
ok: false as const,
message: 'GitHub API error',
cause: `Unexpected error while ${context}: Network failure`,
}
expect(errorResult.cause).toContain(context)
}
})
})
// Regression tests: the bulk loop in createScanFromGithub used to
// swallow per-repo failures, so a rate-limited token returned ok:true
// with "0 manifests". These drive the full function through mocked
// octokit calls.
describe('createScanFromGithub rate-limit short-circuit', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('returns ok:false and stops the loop on GitHub rate limit', async () => {
// First call (getRepoDetails for repo-a) fails with rate limit.
mockWithGitHubRetry.mockResolvedValueOnce({
ok: false,
message: 'GitHub rate limit exceeded',
cause: 'GitHub API rate limit exceeded.',
})
const { createScanFromGithub } = await import(
'../../../../src/commands/scan/create-scan-from-github.mts'
)
const result = await createScanFromGithub({
all: false,
githubApiUrl: '',
githubToken: '',
interactive: false,
orgGithub: 'org',
orgSlug: 'org',
outputKind: 'text',
repos: 'repo-a,repo-b,repo-c',
})
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.message).toBe('GitHub rate limit exceeded')
}
// Short-circuit: only the first repo's getRepoDetails should have run.
expect(mockWithGitHubRetry).toHaveBeenCalledTimes(1)
})
it('returns ok:false and stops on GitHub GraphQL rate limit', async () => {
mockWithGitHubRetry.mockResolvedValueOnce({
ok: false,
message: 'GitHub GraphQL rate limit exceeded',
cause: 'GraphQL rate limit hit.',
})
const { createScanFromGithub } = await import(
'../../../../src/commands/scan/create-scan-from-github.mts'
)
const result = await createScanFromGithub({
all: false,
githubApiUrl: '',
githubToken: '',
interactive: false,
orgGithub: 'org',
orgSlug: 'org',
outputKind: 'text',
repos: 'repo-a,repo-b,repo-c',
})
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.message).toBe('GitHub GraphQL rate limit exceeded')
}
expect(mockWithGitHubRetry).toHaveBeenCalledTimes(1)
})
it('returns ok:false and stops on GitHub abuse detection', async () => {
mockWithGitHubRetry.mockResolvedValueOnce({
ok: false,
message: 'GitHub abuse detection triggered',
cause: 'Secondary rate limit hit.',
})
const { createScanFromGithub } = await import(
'../../../../src/commands/scan/create-scan-from-github.mts'
)
const result = await createScanFromGithub({
all: false,
githubApiUrl: '',
githubToken: '',
interactive: false,
orgGithub: 'org',
orgSlug: 'org',
outputKind: 'text',
repos: 'repo-a,repo-b,repo-c',
})
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.message).toBe('GitHub abuse detection triggered')
}
expect(mockWithGitHubRetry).toHaveBeenCalledTimes(1)
})
it('returns ok:false and stops on GitHub auth failure', async () => {
mockWithGitHubRetry.mockResolvedValueOnce({
ok: false,
message: 'GitHub authentication failed',
cause: 'Bad credentials.',
})
const { createScanFromGithub } = await import(
'../../../../src/commands/scan/create-scan-from-github.mts'
)
const result = await createScanFromGithub({
all: false,
githubApiUrl: '',
githubToken: '',
interactive: false,
orgGithub: 'org',
orgSlug: 'org',
outputKind: 'text',
repos: 'repo-a,repo-b',
})
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.message).toBe('GitHub authentication failed')
}
expect(mockWithGitHubRetry).toHaveBeenCalledTimes(1)
})
it('returns "All repos failed to scan" when every repo errors with a non-blocking reason', async () => {
// Each repo's getRepoDetails fails with a non-rate-limit error;
// the loop should finish all repos and return the catch-all error.
mockWithGitHubRetry.mockResolvedValue({
ok: false,
message: 'GitHub resource not found',
cause: 'Not found.',
})
const { createScanFromGithub } = await import(
'../../../../src/commands/scan/create-scan-from-github.mts'
)
const result = await createScanFromGithub({
all: false,
githubApiUrl: '',
githubToken: '',
interactive: false,
orgGithub: 'org',
orgSlug: 'org',
outputKind: 'text',
repos: 'repo-a,repo-b',
})
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.message).toBe('All repos failed to scan')
expect(result.cause).toContain('repo-a')
}
// Both repos should have been attempted (no short-circuit for 404).
expect(mockWithGitHubRetry).toHaveBeenCalledTimes(2)
})
})