0
# Vulnerability Testing
1
2
Core vulnerability scanning functionality for detecting security issues in projects and dependencies. Supports multiple content types, package managers, and output formats with extensive configuration options.
3
4
## Capabilities
5
6
### Test Function
7
8
Main programmatic function for vulnerability testing with callback and promise support.
9
10
```javascript { .api }
11
/**
12
* Test a project for vulnerabilities
13
* @param root - Path to project root directory
14
* @param options - Test configuration options
15
* @param callback - Optional callback function for results
16
* @returns Promise resolving to test results
17
*/
18
function test(root: string, options?: TestOptions, callback?: Function): Promise<TestResult | TestResult[]>;
19
20
interface TestOptions {
21
/** Organization ID for testing */
22
org?: string;
23
/** Specific manifest file to test */
24
file?: string;
25
/** Enable Docker container scanning */
26
docker?: boolean;
27
/** Enable Infrastructure as Code scanning */
28
iac?: boolean;
29
/** Enable source code analysis (SAST) */
30
code?: boolean;
31
/** Enable unmanaged C/C++ scanning */
32
unmanaged?: boolean;
33
/** Return results in JSON format */
34
json?: boolean;
35
/** Minimum severity threshold for reporting */
36
severityThreshold?: 'low' | 'medium' | 'high' | 'critical';
37
/** Control vulnerability path display */
38
showVulnPaths?: 'none' | 'some' | 'all';
39
/** Maximum number of vulnerability paths to show */
40
maxVulnPaths?: number;
41
/** Test all detected projects */
42
allProjects?: boolean;
43
/** Enable Yarn workspaces scanning */
44
yarnWorkspaces?: boolean;
45
/** Include development dependencies */
46
dev?: boolean;
47
/** Print dependency tree */
48
'print-deps'?: boolean;
49
/** Print dependency paths */
50
'print-dep-paths'?: boolean;
51
/** Skip dependency pruning for large projects */
52
pruneRepeatedSubdependencies?: boolean;
53
/** Exclude directories/files from scanning */
54
exclude?: string;
55
/** Project detection depth */
56
detectionDepth?: number;
57
/** Fail test execution on specific conditions */
58
failOn?: 'all' | 'upgradable' | 'patchable';
59
/** Target reference for Git projects */
60
'target-reference'?: string;
61
/** Remote repository URL */
62
'remote-repo-url'?: string;
63
/** Custom project name */
64
'project-name'?: string;
65
/** Policy file path */
66
'policy-path'?: string;
67
/** Ignore policy files */
68
'ignore-policy'?: boolean;
69
/** Trust policy files */
70
'trust-policies'?: boolean;
71
/** Enable experimental features */
72
experimental?: boolean;
73
/** Package manager override */
74
packageManager?: SupportedPackageManagers;
75
}
76
77
interface TestResult {
78
/** List of found vulnerabilities */
79
vulnerabilities: Vulnerability[];
80
/** Total number of dependencies analyzed */
81
dependencyCount: number;
82
/** License policy results */
83
licensesPolicy?: LicensesPolicy;
84
/** Detected package manager */
85
packageManager: string;
86
/** Target platform */
87
platform: string;
88
/** Project path */
89
path: string;
90
/** Project name */
91
projectName: string;
92
/** Human-readable summary */
93
summary: string;
94
/** Vulnerability summary counts */
95
uniqueCount?: number;
96
/** Dependency path information */
97
dependencyPaths?: DependencyPath[];
98
/** Remediation advice */
99
remediation?: RemediationAdvice;
100
/** Docker specific information */
101
docker?: DockerMetadata;
102
/** Display target file */
103
displayTargetFile?: string;
104
/** Found project type */
105
foundProjectCount?: number;
106
}
107
108
interface Vulnerability {
109
/** Unique vulnerability identifier */
110
id: string;
111
/** Vulnerability title */
112
title: string;
113
/** Detailed description */
114
description: string;
115
/** Severity level */
116
severity: 'low' | 'medium' | 'high' | 'critical';
117
/** Affected package name */
118
packageName: string;
119
/** Vulnerable package version */
120
version: string;
121
/** Versions that fix the vulnerability */
122
fixedIn?: string[];
123
/** Available patches */
124
patches?: Patch[];
125
/** Upgrade path to fix */
126
upgradePath?: string[];
127
/** When vulnerability was published */
128
publicationTime?: string;
129
/** When vulnerability was disclosed */
130
disclosureTime?: string;
131
/** CVE identifiers */
132
identifiers?: Identifier[];
133
/** CVSS score */
134
cvssScore?: number;
135
/** Vulnerability functions and methods */
136
functions?: VulnFunction[];
137
/** Dependency paths to vulnerability */
138
from: string[];
139
/** Exploit maturity */
140
exploitMaturity?: 'mature' | 'proof-of-concept' | 'no-known-exploit';
141
/** Language specific metadata */
142
language?: string;
143
/** Package manager specific data */
144
packageManager?: string;
145
/** Social trend score */
146
socialTrendAlert?: boolean;
147
/** Malicious package flag */
148
malicious?: boolean;
149
}
150
151
interface RemediationAdvice {
152
/** Unresolved vulnerabilities count */
153
unresolved: number;
154
/** Upgrade recommendations */
155
upgrade: UpgradeRecommendation[];
156
/** Patch recommendations */
157
patch: PatchRecommendation[];
158
/** Ignore recommendations */
159
ignore: IgnoreRecommendation[];
160
/** Pin recommendations for transitive dependencies */
161
pin: PinRecommendation[];
162
}
163
```
164
165
**Usage Examples:**
166
167
```javascript
168
const snyk = require('snyk');
169
170
// Basic vulnerability test
171
const result = await snyk.test('./my-project');
172
console.log(`Found ${result.vulnerabilities.length} vulnerabilities`);
173
174
// Test with options
175
const result = await snyk.test('./my-project', {
176
org: 'my-org-id',
177
severityThreshold: 'high',
178
json: true,
179
showVulnPaths: 'all'
180
});
181
182
// Test all projects in a monorepo
183
const results = await snyk.test('./monorepo', {
184
allProjects: true,
185
exclude: 'node_modules,dist'
186
});
187
188
// Test with callback pattern
189
snyk.test('./my-project', { json: true }, (error, result) => {
190
if (error) {
191
console.error('Test failed:', error);
192
} else {
193
console.log('Test completed:', result);
194
}
195
});
196
```
197
198
### CLI Test Command
199
200
Command-line interface for vulnerability testing with comprehensive options.
201
202
```bash { .api }
203
# Basic usage
204
snyk test # Test current directory
205
snyk test /path/to/project # Test specific path
206
snyk test --org=<org-id> # Test with organization
207
208
# Output options
209
snyk test --json # JSON output
210
snyk test --json-file-output=results.json # Save JSON to file
211
snyk test --sarif # SARIF format output
212
snyk test --sarif-file-output=results.sarif # Save SARIF to file
213
214
# Filtering options
215
snyk test --severity-threshold=high # Filter by severity
216
snyk test --fail-on=upgradable # Fail conditions
217
snyk test --show-vulnerable-paths=all # Show vulnerability paths
218
219
# Project options
220
snyk test --all-projects # Test all detected projects
221
snyk test --yarn-workspaces # Test Yarn workspaces
222
snyk test --file=package.json # Test specific manifest
223
snyk test --exclude=node_modules,dist # Exclude directories
224
225
# Scanning modes
226
snyk test --docker # Docker scanning mode
227
snyk test --iac # Infrastructure as Code mode
228
snyk test --code # Source code analysis mode
229
snyk test --unmanaged # Unmanaged (C/C++) mode
230
231
# Advanced options
232
snyk test --detection-depth=5 # Limit detection depth
233
snyk test --prune-repeated-subdependencies # Prune large dependency trees
234
snyk test --print-deps # Print dependency information
235
snyk test --dev # Include dev dependencies
236
```
237
238
### Error Handling
239
240
```javascript { .api }
241
// Common error scenarios
242
try {
243
const result = await snyk.test('./project');
244
} catch (error) {
245
if (error.code === 'VULNS') {
246
// Vulnerabilities found (expected behavior)
247
console.log('Vulnerabilities detected:', error.message);
248
} else if (error.code === 'NO_SUPPORTED_MANIFESTS') {
249
// No supported manifest files found
250
console.log('No supported package files found');
251
} else if (error.code === 'MISSING_NODE_MODULES') {
252
// Dependencies not installed
253
console.log('Please run npm install first');
254
} else {
255
// Other errors
256
console.error('Test failed:', error.message);
257
}
258
}
259
```
260
261
### Package Manager Detection
262
263
```javascript { .api }
264
// Automatic package manager detection based on manifest files
265
const manifestFiles = {
266
'package.json': 'npm',
267
'yarn.lock': 'yarn',
268
'pnpm-lock.yaml': 'pnpm',
269
'pom.xml': 'maven',
270
'build.gradle': 'gradle',
271
'requirements.txt': 'pip',
272
'Gemfile': 'rubygems',
273
'composer.json': 'composer',
274
'go.mod': 'gomodules',
275
'project.json': 'nuget'
276
};
277
278
// Override detection
279
await snyk.test('./project', {
280
packageManager: 'yarn'
281
});
282
```
283
284
## Types
285
286
### Supporting Types
287
288
```typescript { .api }
289
interface Patch {
290
/** Patch identifier */
291
id: string;
292
/** Patch file URLs */
293
urls: string[];
294
/** Applicable version range */
295
version: string;
296
/** Patch modification time */
297
modificationTime: string;
298
/** Patch comments */
299
comments: string[];
300
}
301
302
interface Identifier {
303
/** Identifier type (CVE, CWE, etc.) */
304
type: string;
305
/** Identifier value */
306
value: string;
307
}
308
309
interface VulnFunction {
310
/** Function/method name */
311
functionId: FunctionId;
312
/** Function version */
313
version: string[];
314
}
315
316
interface FunctionId {
317
/** Function class name */
318
className?: string;
319
/** Function name */
320
functionName: string;
321
}
322
323
interface DependencyPath {
324
/** Path from root to vulnerability */
325
path: string[];
326
}
327
328
interface UpgradeRecommendation {
329
/** Path to vulnerable dependency */
330
path: string[];
331
/** Current version */
332
version: string;
333
/** Recommended upgrade version */
334
upgradeTo: string;
335
/** Issues fixed by upgrade */
336
issues: string[];
337
}
338
339
interface LicensesPolicy {
340
/** License policy results */
341
licenseViolations: LicenseViolation[];
342
/** Total license issues */
343
totalLicenseIssues: number;
344
}
345
346
interface DockerMetadata {
347
/** Base image name */
348
baseImage: string;
349
/** Base image tag */
350
baseImageTag: string;
351
/** Platform architecture */
352
platform: string;
353
}
354
355
interface PatchRecommendation {
356
/** Patch identifier */
357
id: string;
358
/** Patch URLs */
359
urls: string[];
360
/** Patch version */
361
version: string;
362
/** Modification timestamp */
363
modificationTime: string;
364
/** Patch comments */
365
comments: string[];
366
}
367
368
interface IgnoreRecommendation {
369
/** Ignore rule ID */
370
id: string;
371
/** Ignore reason */
372
reason: string;
373
/** Expiration date */
374
expires?: string;
375
/** Ignore path pattern */
376
path?: string;
377
}
378
379
interface PinRecommendation {
380
/** Dependency to pin */
381
name: string;
382
/** Version to pin to */
383
version: string;
384
/** Pin reason */
385
reason: string;
386
}
387
388
interface LicenseViolation {
389
/** License name */
390
license: string;
391
/** Package name */
392
packageName: string;
393
/** Package version */
394
version: string;
395
/** Violation severity */
396
severity: 'low' | 'medium' | 'high';
397
/** Violation instructions */
398
instructions: string;
399
}
400
401
interface Dependency {
402
/** Package name */
403
name: string;
404
/** Package version */
405
version: string;
406
/** Dependencies of this package */
407
dependencies?: Record<string, Dependency>;
408
}
409
```