-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathcmd-scan-reach.e2e.test.mts
More file actions
1146 lines (1018 loc) · 35.6 KB
/
cmd-scan-reach.e2e.test.mts
File metadata and controls
1146 lines (1018 loc) · 35.6 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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { randomUUID } from 'node:crypto'
import { existsSync, promises as fs } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { describe, expect } from 'vitest'
import { logger } from '@socketsecurity/registry/lib/logger'
import { cmdit, spawnSocketCli, testPath } from '../../../test/utils.mts'
import constants from '../../constants.mts'
const fixtureBaseDir = path.join(testPath, 'fixtures/commands/scan')
const systemTmpDir = tmpdir()
// Types for .socket.facts.json structure.
type Vulnerability = {
ghsaId: string
severity: string
range: string
reachabilityData?: unknown
}
type ReachabilityEntry = {
type: 'reachable' | 'unreachable' | string
workspacePath: string
subprojectPath: string
affectedPurls?: Array<{ type: string; name: string; version: string }>
analysisLevel?: string
matches?: Array<
Array<{
package: string
sourceLocation: {
start: { line: number; column: number }
end: { line: number; column: number }
filename: string
}
confidence: number
}>
>
}
type ComponentReachability = {
ghsa_id: string
reachability: ReachabilityEntry[]
}
type Component = {
id: string
name: string
version: string
type: string
direct: boolean
dev: boolean
dead: boolean
dependencies: string[]
manifestFiles: Array<{ file: string; start: number; end: number }>
vulnerabilities?: Vulnerability[]
reachability?: ComponentReachability[]
}
type WorkspaceDiagnostic = {
subprojectPath: string
workspacePath: string
purl_type: string
diagnostics: {
sourceFilesDetected: string
preinstalledDependencies: string
warnings: Array<{ type: string; message: string; severity: string }>
}
}
type SocketFactsJson = {
components: Component[]
tier1ReachabilityScanId?: string
workspaceDiagnostics: WorkspaceDiagnostic[]
}
/**
* Get environment variables for E2E test subprocess.
* Includes API token and explicitly unsets proxy variables that Vitest sets.
*/
function getTestEnv(apiToken: string): Record<string, string | undefined> {
return {
SOCKET_CLI_API_TOKEN: apiToken,
// Vitest sets HTTP_PROXY/HTTPS_PROXY for internal use, but we need to unset them
// for E2E tests to hit the real Socket API directly.
HTTP_PROXY: undefined,
HTTPS_PROXY: undefined,
http_proxy: undefined,
https_proxy: undefined,
SOCKET_CLI_API_PROXY: undefined,
}
}
/**
* Create a temporary copy of a fixture directory for testing.
* This allows tests to modify the fixture without affecting the original.
* Uses system temp directory with a unique identifier.
*/
async function createTempFixtureCopy(
fixtureName: string,
): Promise<{ cleanup: () => Promise<void>; path: string }> {
const sourceDir = path.join(fixtureBaseDir, fixtureName)
const uniqueId = randomUUID()
const tempDir = path.join(
systemTmpDir,
`socket-cli-e2e-${fixtureName}-${uniqueId}`,
)
await fs.cp(sourceDir, tempDir, { recursive: true })
return {
cleanup: async () => {
try {
await fs.rm(tempDir, { force: true, recursive: true })
} catch (e) {
logger.warn(`Failed to clean up temp dir ${tempDir}:`, e)
}
},
path: tempDir,
}
}
/**
* Create a temporary mono project containing multiple fixture subdirectories.
* This allows testing multi-ecosystem scenarios.
*/
async function createTempMonoProject(
fixtureNames: string[],
): Promise<{ cleanup: () => Promise<void>; path: string }> {
const uniqueId = randomUUID()
const tempDir = path.join(systemTmpDir, `socket-cli-e2e-mono-${uniqueId}`)
await fs.mkdir(tempDir, { recursive: true })
// Copy each fixture into a subdirectory.
await Promise.all(
fixtureNames.map(async fixtureName => {
const sourceDir = path.join(fixtureBaseDir, fixtureName)
const destDir = path.join(tempDir, fixtureName)
await fs.cp(sourceDir, destDir, { recursive: true })
}),
)
return {
cleanup: async () => {
try {
await fs.rm(tempDir, { force: true, recursive: true })
} catch (e) {
logger.warn(`Failed to clean up temp dir ${tempDir}:`, e)
}
},
path: tempDir,
}
}
/**
* Read and parse the .socket.facts.json file from a directory.
*/
async function readSocketFactsJson(dir: string): Promise<SocketFactsJson> {
const factsPath = path.join(dir, constants.DOT_SOCKET_DOT_FACTS_JSON)
const content = await fs.readFile(factsPath, 'utf8')
return JSON.parse(content) as SocketFactsJson
}
/**
* Get components that have vulnerabilities.
*/
function getVulnerableComponents(facts: SocketFactsJson): Component[] {
return facts.components.filter(
c => c.vulnerabilities && c.vulnerabilities.length > 0,
)
}
/**
* Get all unique GHSA IDs from vulnerable components.
*/
function getAllGhsaIds(facts: SocketFactsJson): string[] {
const ghsaIds = new Set<string>()
for (const component of facts.components) {
if (component.vulnerabilities) {
for (const vuln of component.vulnerabilities) {
ghsaIds.add(vuln.ghsaId)
}
}
}
return [...ghsaIds].sort()
}
/**
* Find a component by name and version.
*/
function findComponent(
facts: SocketFactsJson,
name: string,
version: string,
): Component | undefined {
return facts.components.find(c => c.name === name && c.version === version)
}
/**
* Find reachability entry for a specific GHSA ID and workspace path.
*/
function findReachabilityForGhsa(
component: Component,
ghsaId: string,
workspacePath: string,
): ReachabilityEntry | undefined {
if (!component.reachability) {
return undefined
}
const ghsaReachability = component.reachability.find(
r => r.ghsa_id === ghsaId,
)
if (!ghsaReachability) {
return undefined
}
return ghsaReachability.reachability.find(
r => r.workspacePath === workspacePath,
)
}
/**
* Helper to log command output for debugging.
* Logs stdout and stderr to help diagnose test failures.
*/
function logCommandOutput(code: number, stdout: string, stderr: string): void {
logger.error(`Command exited with code ${code}`)
logger.error('stdout:', stdout)
logger.error('stderr:', stderr)
}
/**
* Log reachability entries that have type "error" for debugging.
* Helps diagnose Coana analysis failures in CI.
*/
function logReachabilityErrors(facts: SocketFactsJson): void {
for (const component of facts.components) {
if (!component.reachability) {
continue
}
for (const ghsaEntry of component.reachability) {
for (const entry of ghsaEntry.reachability) {
if (entry.type === 'error') {
logger.error(
`Reachability error for ${ghsaEntry.ghsa_id} in ${component.name}@${component.version} ` +
`(subproject: ${entry.subprojectPath}): ${JSON.stringify(entry)}`,
)
}
}
}
}
}
describe('socket scan reach (E2E tests)', async () => {
const { binCliPath } = constants
// Standard timeout for most tests.
const testTimeout = 120_000
// Longer timeout for full workspace scans which are more resource-intensive.
const longTestTimeout = 300_000
const apiToken = process.env['SOCKET_CLI_API_TOKEN']
const orgSlug = process.env['SOCKET_ORG'] ?? 'SocketDev'
if (!apiToken) {
throw new Error('SOCKET_CLI_API_TOKEN environment variable not set')
}
describe('npm-test-workspace-mono', () => {
cmdit(
[
'scan',
'reach',
'.',
'--reach-debug',
'--no-interactive',
'--reach-disable-analytics',
],
'should run reachability analysis on workspace mono project',
async cmd => {
const tempFixture = await createTempFixtureCopy(
'npm-test-workspace-mono',
)
let stdout = ''
let stderr = ''
let code = -1
try {
const result = await spawnSocketCli(
binCliPath,
[...cmd, '--org', orgSlug],
{
cwd: tempFixture.path,
env: getTestEnv(apiToken),
},
)
stdout = result.stdout
stderr = result.stderr
code = result.code
if (code !== 0) {
logCommandOutput(code, stdout, stderr)
}
expect(code, 'should exit with code 0').toBe(0)
// Verify the .socket.facts.json file was created.
const factsPath = path.join(
tempFixture.path,
constants.DOT_SOCKET_DOT_FACTS_JSON,
)
expect(existsSync(factsPath), '.socket.facts.json should exist').toBe(
true,
)
// Read and validate the facts file structure.
const facts = await readSocketFactsJson(tempFixture.path)
// Verify top-level structure.
expect(facts).toHaveProperty('components')
expect(facts).toHaveProperty('workspaceDiagnostics')
expect(Array.isArray(facts.components)).toBe(true)
expect(Array.isArray(facts.workspaceDiagnostics)).toBe(true)
// Verify workspace diagnostics includes all 3 subprojects.
const subprojectPaths = facts.workspaceDiagnostics.map(
d => d.subprojectPath,
)
expect(subprojectPaths).toContain('.')
expect(subprojectPaths).toContain('packages/package-a')
expect(subprojectPaths).toContain('packages/package-b')
expect(facts.workspaceDiagnostics).toHaveLength(3)
// Verify components count is reasonable (should be > 100 for this workspace).
expect(facts.components.length).toBeGreaterThan(100)
// Verify vulnerable components are detected.
const vulnerableComponents = getVulnerableComponents(facts)
expect(
vulnerableComponents.length,
'should detect vulnerable components',
).toBeGreaterThan(0)
// Verify specific known vulnerabilities are detected.
const ghsaIds = getAllGhsaIds(facts)
// lodash@3.10.1 in package-b should have GHSA-fvqr-27wr-82fm.
expect(ghsaIds).toContain('GHSA-fvqr-27wr-82fm')
// Verify lodash@3.10.1 is present and has vulnerabilities.
const lodash3 = findComponent(facts, 'lodash', '3.10.1')
expect(lodash3, 'lodash@3.10.1 should be present').toBeDefined()
expect(
lodash3?.vulnerabilities?.length,
'lodash@3.10.1 should have vulnerabilities',
).toBeGreaterThan(0)
// Verify reachability analysis was performed on lodash@3.10.1.
expect(
lodash3?.reachability,
'lodash@3.10.1 should have reachability data',
).toBeDefined()
expect(
lodash3?.reachability?.length,
'lodash@3.10.1 should have reachability entries',
).toBeGreaterThan(0)
// Verify GHSA-fvqr-27wr-82fm is reachable in packages/package-b.
const ghsaFvqrReachabilityPkgB = findReachabilityForGhsa(
lodash3!,
'GHSA-fvqr-27wr-82fm',
'packages/package-b',
)
expect(
ghsaFvqrReachabilityPkgB,
'GHSA-fvqr-27wr-82fm should have reachability data for packages/package-b',
).toBeDefined()
expect(
ghsaFvqrReachabilityPkgB?.type,
'GHSA-fvqr-27wr-82fm should be reachable in packages/package-b',
).toBe('reachable')
expect(ghsaFvqrReachabilityPkgB?.analysisLevel).toBe('function-level')
expect(ghsaFvqrReachabilityPkgB?.matches).toBeDefined()
// Verify GHSA-35jh-r3h4-6jhm is unreachable in packages/package-b.
const ghsaFvqrReachabilityPkgA = findReachabilityForGhsa(
lodash3!,
'GHSA-35jh-r3h4-6jhm',
'packages/package-b',
)
expect(
ghsaFvqrReachabilityPkgA,
'GHSA-35jh-r3h4-6jhm should have reachability data for packages/package-b',
).toBeDefined()
expect(
ghsaFvqrReachabilityPkgA?.type,
'GHSA-35jh-r3h4-6jhm should be unreachable in packages/package-b',
).toBe('unreachable')
// Verify component structure.
for (const component of facts.components.slice(0, 5)) {
expect(component).toHaveProperty('id')
expect(component).toHaveProperty('name')
expect(component).toHaveProperty('version')
expect(component).toHaveProperty('type')
expect(component.type).toBe('npm')
}
logger.info('\nReachability analysis completed successfully')
} catch (e) {
logCommandOutput(code, stdout, stderr)
// Log reachability errors from the facts file if it was parsed.
try {
const errorFacts = await readSocketFactsJson(tempFixture.path)
logReachabilityErrors(errorFacts)
} catch {
// Facts file may not exist if the failure was earlier.
}
throw e
} finally {
await tempFixture.cleanup()
}
},
{ retry: 2, timeout: longTestTimeout },
)
cmdit(
[
'scan',
'reach',
'.',
'--reach-debug',
'--no-interactive',
'--reach-disable-analytics',
'--reach-exclude-paths',
'packages/package-b',
],
'should run reachability analysis with excluded paths',
async cmd => {
const tempFixture = await createTempFixtureCopy(
'npm-test-workspace-mono',
)
let stdout = ''
let stderr = ''
let code = -1
try {
const result = await spawnSocketCli(
binCliPath,
[...cmd, '--org', orgSlug],
{
cwd: tempFixture.path,
env: getTestEnv(apiToken),
},
)
stdout = result.stdout
stderr = result.stderr
code = result.code
if (code !== 0) {
logCommandOutput(code, stdout, stderr)
}
expect(code, 'should exit with code 0').toBe(0)
// Verify the .socket.facts.json file was created.
const factsPath = path.join(
tempFixture.path,
constants.DOT_SOCKET_DOT_FACTS_JSON,
)
expect(existsSync(factsPath), '.socket.facts.json should exist').toBe(
true,
)
// Read and validate the facts file structure.
const facts = await readSocketFactsJson(tempFixture.path)
// Verify top-level structure.
expect(facts).toHaveProperty('components')
expect(facts).toHaveProperty('workspaceDiagnostics')
expect(Array.isArray(facts.components)).toBe(true)
expect(Array.isArray(facts.workspaceDiagnostics)).toBe(true)
// Note: --reach-exclude-paths excludes paths from analysis but the
// workspaceDiagnostics may still list all discovered workspaces.
// The key difference is in the reachability analysis results.
// Verify we still have components (analysis ran successfully).
expect(facts.components.length).toBeGreaterThan(50)
// Verify lodash@3.10.1 (from package-b) exists but should have
// different reachability data when package-b is excluded from analysis.
const lodash = findComponent(facts, 'lodash', '3.10.1')
if (lodash) {
// If lodash is present, verify it has the expected structure.
expect(lodash).toHaveProperty('name', 'lodash')
expect(lodash).toHaveProperty('version', '3.10.1')
}
// Verify component structure for sampled components.
for (const component of facts.components.slice(0, 5)) {
expect(component).toHaveProperty('id')
expect(component).toHaveProperty('name')
expect(component).toHaveProperty('version')
expect(component).toHaveProperty('type')
expect(component.type).toBe('npm')
}
logger.info(
'\nReachability analysis with excluded paths completed successfully',
)
} catch (e) {
logCommandOutput(code, stdout, stderr)
throw e
} finally {
await tempFixture.cleanup()
}
},
{ retry: 2, timeout: testTimeout },
)
})
describe('target and cwd flags', () => {
cmdit(
[
'scan',
'reach',
'packages/package-a',
'--reach-debug',
'--no-interactive',
'--reach-disable-analytics',
],
'should only scan files within the target directory',
async cmd => {
const tempFixture = await createTempFixtureCopy(
'npm-test-workspace-mono',
)
let stdout = ''
let stderr = ''
let code = -1
try {
const result = await spawnSocketCli(
binCliPath,
[...cmd, '--org', orgSlug],
{
cwd: tempFixture.path,
env: getTestEnv(apiToken),
},
)
stdout = result.stdout
stderr = result.stderr
code = result.code
if (code !== 0) {
logCommandOutput(code, stdout, stderr)
}
expect(code, 'should exit with code 0').toBe(0)
// Verify the .socket.facts.json file was created.
const factsPath = path.join(
tempFixture.path,
constants.DOT_SOCKET_DOT_FACTS_JSON,
)
expect(existsSync(factsPath), '.socket.facts.json should exist').toBe(
true,
)
// Read and validate the facts file structure.
const facts = await readSocketFactsJson(tempFixture.path)
// Verify top-level structure.
expect(facts).toHaveProperty('components')
expect(facts).toHaveProperty('workspaceDiagnostics')
// When target is packages/package-a, only that subproject should be analyzed.
// The workspaceDiagnostics should only include package-a, not package-b or root.
const subprojectPaths = facts.workspaceDiagnostics.map(
d => d.subprojectPath,
)
expect(
subprojectPaths,
'should have . representing the package-a subproject',
).toContain('.')
expect(
subprojectPaths,
'should NOT have packages/package-b when targeting package-a',
).not.toContain('packages/package-b')
expect(
subprojectPaths,
"should NOT have packages/package-a since it's represented by the . subproject",
).not.toContain('packages/package-a')
// Verify we have components.
expect(
facts.components.length,
'should have components from package-a',
).toBeGreaterThan(0)
// When targeting packages/package-a, we should NOT find lodash@3.10.1
// which is only a dependency of package-b (not package-a).
// package-a depends on lodash@4, not lodash@3.10.1.
const lodash3 = findComponent(facts, 'lodash', '3.10.1')
expect(
lodash3,
'lodash@3.10.1 (from package-b) should NOT be present when targeting package-a',
).toBeUndefined()
// package-a depends on lodash@4, so we should find a lodash version starting with 4.
const lodash4Components = facts.components.filter(
c => c.name === 'lodash' && c.version.startsWith('4'),
)
expect(
lodash4Components.length,
'should have lodash@4.x from package-a',
).toBeGreaterThan(0)
logger.info(
'\nReachability analysis with target restriction completed successfully',
)
} catch (e) {
logCommandOutput(code, stdout, stderr)
throw e
} finally {
await tempFixture.cleanup()
}
},
{ retry: 2, timeout: testTimeout },
)
cmdit(
[
'scan',
'reach',
'.',
'--reach-debug',
'--no-interactive',
'--reach-disable-analytics',
],
'should use --cwd to set the working directory',
async cmd => {
const tempFixture = await createTempFixtureCopy(
'npm-test-workspace-mono',
)
let stdout = ''
let stderr = ''
let code = -1
try {
// Run from system temp dir but point --cwd to the fixture.
const result = await spawnSocketCli(
binCliPath,
[...cmd, '--org', orgSlug, '--cwd', tempFixture.path],
{
cwd: systemTmpDir,
env: getTestEnv(apiToken),
},
)
stdout = result.stdout
stderr = result.stderr
code = result.code
if (code !== 0) {
logCommandOutput(code, stdout, stderr)
}
expect(code, 'should exit with code 0').toBe(0)
// Verify the .socket.facts.json file was created in the --cwd directory, not process.cwd().
const factsInCwd = path.join(
tempFixture.path,
constants.DOT_SOCKET_DOT_FACTS_JSON,
)
expect(
existsSync(factsInCwd),
'.socket.facts.json should exist in --cwd directory',
).toBe(true)
// Read and validate the facts file structure.
const facts = await readSocketFactsJson(tempFixture.path)
// Verify all workspace subprojects are found when using --cwd.
const subprojectPaths = facts.workspaceDiagnostics.map(
d => d.subprojectPath,
)
expect(subprojectPaths).toContain('.')
expect(subprojectPaths).toContain('packages/package-a')
expect(subprojectPaths).toContain('packages/package-b')
// Verify we have components.
expect(facts.components.length).toBeGreaterThan(100)
logger.info(
'\nReachability analysis with --cwd flag completed successfully',
)
} catch (e) {
logCommandOutput(code, stdout, stderr)
throw e
} finally {
await tempFixture.cleanup()
}
},
{ retry: 2, timeout: testTimeout },
)
cmdit(
[
'scan',
'reach',
'packages/package-b',
'--reach-debug',
'--no-interactive',
'--reach-disable-analytics',
],
'should work with --cwd and target together',
async cmd => {
const tempFixture = await createTempFixtureCopy(
'npm-test-workspace-mono',
)
let stdout = ''
let stderr = ''
let code = -1
try {
// Run from system temp dir but point --cwd to the fixture.
// Target is relative to --cwd.
const result = await spawnSocketCli(
binCliPath,
[...cmd, '--org', orgSlug, '--cwd', tempFixture.path],
{
cwd: systemTmpDir,
env: getTestEnv(apiToken),
},
)
stdout = result.stdout
stderr = result.stderr
code = result.code
if (code !== 0) {
logCommandOutput(code, stdout, stderr)
}
expect(code, 'should exit with code 0').toBe(0)
// Verify the .socket.facts.json file was created in the --cwd directory.
const factsPath = path.join(
tempFixture.path,
constants.DOT_SOCKET_DOT_FACTS_JSON,
)
expect(
existsSync(factsPath),
'.socket.facts.json should exist in --cwd directory',
).toBe(true)
// Read and validate the facts file structure.
const facts = await readSocketFactsJson(tempFixture.path)
// When target is packages/package-b with --cwd, only that subproject should be analyzed.
const subprojectPaths = facts.workspaceDiagnostics.map(
d => d.subprojectPath,
)
expect(
subprojectPaths,
'should have . representing the package-b subproject',
).toContain('.')
expect(
subprojectPaths,
'should NOT have packages/package-a when targeting package-b',
).not.toContain('packages/package-a')
expect(
subprojectPaths,
"should NOT have packages/package-b since it's represented by the . subproject",
).not.toContain('packages/package-b')
// Verify we have components.
expect(
facts.components.length,
'should have components when using --cwd and target together',
).toBeGreaterThan(0)
// Verify lodash@3.10.1 (from package-b) IS present.
// This confirms that package-b was scanned when using target with --cwd.
const lodash3 = findComponent(facts, 'lodash', '3.10.1')
expect(
lodash3,
'lodash@3.10.1 should be present when targeting package-b',
).toBeDefined()
logger.info(
'\nReachability analysis with --cwd and target completed successfully',
)
} catch (e) {
logCommandOutput(code, stdout, stderr)
throw e
} finally {
await tempFixture.cleanup()
}
},
{ retry: 2, timeout: testTimeout },
)
cmdit(
[
'scan',
'reach',
'../outside-dir',
'--reach-debug',
'--no-interactive',
'--reach-disable-analytics',
],
'should fail when target is outside cwd',
async cmd => {
const tempFixture = await createTempFixtureCopy(
'npm-test-workspace-mono',
)
let code = -1
try {
const result = await spawnSocketCli(
binCliPath,
[...cmd, '--org', orgSlug],
{
cwd: tempFixture.path,
env: getTestEnv(apiToken),
},
)
code = result.code
// Should fail with a non-zero exit code.
expect(
code,
'should exit with non-zero code when target is outside cwd',
).not.toBe(0)
// Verify no .socket.facts.json file was created.
const factsPath = path.join(
tempFixture.path,
constants.DOT_SOCKET_DOT_FACTS_JSON,
)
expect(
existsSync(factsPath),
'.socket.facts.json should NOT exist when target validation fails',
).toBe(false)
// Check that the error message mentions the target constraint.
expect(
result.stderr + result.stdout,
'should mention target must be inside working directory',
).toMatch(/inside.*working|working.*directory|target.*directory/i)
logger.info('\nTarget outside cwd correctly rejected')
} finally {
await tempFixture.cleanup()
}
},
{ retry: 2, timeout: testTimeout },
)
cmdit(
[
'scan',
'reach',
'.',
'--reach-debug',
'--no-interactive',
'--reach-disable-analytics',
],
'should write output to cwd when running from subdirectory',
async cmd => {
const tempFixture = await createTempFixtureCopy(
'npm-test-workspace-mono',
)
let stdout = ''
let stderr = ''
let code = -1
try {
// Run from packages/package-a subdirectory with target '.'.
const targetPath = path.join(tempFixture.path, 'packages/package-a')
const result = await spawnSocketCli(
binCliPath,
[...cmd, '--org', orgSlug],
{
cwd: targetPath,
env: getTestEnv(apiToken),
},
)
stdout = result.stdout
stderr = result.stderr
code = result.code
if (code !== 0) {
logCommandOutput(code, stdout, stderr)
}
expect(code, 'should exit with code 0').toBe(0)
// Verify the .socket.facts.json file was created in the cwd (packages/package-a).
const factsPath = path.join(
targetPath,
constants.DOT_SOCKET_DOT_FACTS_JSON,
)
expect(
existsSync(factsPath),
'.socket.facts.json should exist in cwd directory',
).toBe(true)
// Read and validate the facts file structure.
const facts = await readSocketFactsJson(targetPath)
// When running from packages/package-a subdirectory with target '.', the
// workspaceDiagnostics should show '.' as the subprojectPath.
const subprojectPaths = facts.workspaceDiagnostics.map(
d => d.subprojectPath,
)
expect(
subprojectPaths,
'should have current directory as subproject',
).toContain('.')
expect(
facts.workspaceDiagnostics.length,
'should only have one workspace diagnostic entry',
).toBe(1)
// Verify we have components.
expect(
facts.components.length,
'should have components',
).toBeGreaterThan(0)
logger.info(
'\nReachability analysis output location verified successfully',
)
} catch (e) {
logCommandOutput(code, stdout, stderr)
throw e
} finally {
await tempFixture.cleanup()
}
},
{ retry: 2, timeout: testTimeout },
)
})
describe('multi-ecosystem filtering', () => {
cmdit(
[
'scan',
'reach',
'.',
'--reach-debug',
'--no-interactive',
'--reach-ecosystems',
'pypi',
'--reach-disable-analytics',
],
'should only analyze pypi ecosystem when --reach-ecosystems pypi is specified',
async cmd => {
// Create a mono project with both npm and pypi projects.
const tempFixture = await createTempMonoProject([
'simple-npm',
'plain-requirements-txt',
])
let stdout = ''
let stderr = ''
let code = -1
try {
const result = await spawnSocketCli(
binCliPath,
[...cmd, '--org', orgSlug],
{
cwd: tempFixture.path,
env: getTestEnv(apiToken),
},
)
stdout = result.stdout
stderr = result.stderr
code = result.code
if (code !== 0) {
logCommandOutput(code, stdout, stderr)
}
expect(code, 'should exit with code 0').toBe(0)
// Verify the .socket.facts.json file was created.
const factsPath = path.join(
tempFixture.path,
constants.DOT_SOCKET_DOT_FACTS_JSON,
)
expect(existsSync(factsPath), '.socket.facts.json should exist').toBe(
true,
)
// Read and validate the facts file structure.
const facts = await readSocketFactsJson(tempFixture.path)