0
# Source Code Analysis
1
2
Static Application Security Testing (SAST) for identifying security vulnerabilities in application source code across multiple programming languages with real-time analysis and AI-powered detection.
3
4
## Capabilities
5
6
### Code Testing
7
8
Command-line interface for static analysis of application source code to detect security vulnerabilities.
9
10
```bash { .api }
11
# Basic code testing
12
snyk code test # Test current directory
13
snyk code test <path> # Test specific path
14
snyk code test ./src/ # Test source directory
15
16
# Testing with options
17
snyk code test <path> --org=<org-id> # Test with organization
18
snyk code test <path> --json # JSON output format
19
snyk code test <path> --sarif # SARIF format output
20
snyk code test <path> --severity-threshold=high # Filter by severity
21
22
# Output options
23
snyk code test <path> --json-file-output=results.json # Save JSON results
24
snyk code test <path> --sarif-file-output=results.sarif # Save SARIF results
25
26
# Project identification
27
snyk code test <path> --project-name="MyApp Code" # Custom project name
28
snyk code test <path> --target-reference=main # Git reference
29
30
# Advanced options
31
snyk code test <path> --exclude="**/test/**" # Exclude directories
32
snyk code test <path> --include="**/*.js,**/*.py" # Include patterns
33
snyk code test <path> --max-depth=5 # Limit directory depth
34
```
35
36
### Supported Languages
37
38
Programming languages and frameworks supported by Snyk Code analysis.
39
40
```bash { .api }
41
# JavaScript and TypeScript
42
snyk code test ./frontend/ # React, Angular, Vue.js
43
snyk code test ./backend/ # Node.js, Express
44
45
# Python
46
snyk code test ./python-app/ # Django, Flask, FastAPI
47
snyk code test ./ml-project/ # NumPy, TensorFlow
48
49
# Java
50
snyk code test ./java-app/ # Spring, Spring Boot
51
snyk code test ./android-app/ # Android applications
52
53
# C# and .NET
54
snyk code test ./dotnet-app/ # ASP.NET, .NET Core
55
snyk code test ./webapi/ # Web APIs
56
57
# PHP
58
snyk code test ./php-app/ # Laravel, Symfony, WordPress
59
60
# Go
61
snyk code test ./go-service/ # Go applications and services
62
63
# Ruby
64
snyk code test ./rails-app/ # Ruby on Rails applications
65
66
# C and C++
67
snyk code test ./c-project/ # C/C++ applications
68
69
# Kotlin
70
snyk code test ./kotlin-app/ # Kotlin applications
71
72
# Scala
73
snyk code test ./scala-service/ # Scala applications
74
75
# Swift
76
snyk code test ./ios-app/ # iOS applications
77
```
78
79
### Security Vulnerability Categories
80
81
Types of security vulnerabilities detected by static code analysis.
82
83
```bash { .api }
84
# Common vulnerability categories detected:
85
# - SQL Injection (CWE-89)
86
# - Cross-Site Scripting (XSS) (CWE-79)
87
# - Cross-Site Request Forgery (CSRF) (CWE-352)
88
# - Path Traversal (CWE-22)
89
# - Command Injection (CWE-78)
90
# - Code Injection (CWE-94)
91
# - LDAP Injection (CWE-90)
92
# - XML Injection (CWE-91)
93
# - Hardcoded Secrets (CWE-798)
94
# - Insecure Randomness (CWE-330)
95
# - Weak Cryptography (CWE-327)
96
# - Authentication Bypass (CWE-287)
97
# - Authorization Issues (CWE-863)
98
# - Information Disclosure (CWE-200)
99
# - Denial of Service (CWE-400)
100
# - Buffer Overflow (CWE-120)
101
# - Use After Free (CWE-416)
102
# - Null Pointer Dereference (CWE-476)
103
```
104
105
### AI-Powered Analysis
106
107
Advanced AI-driven analysis capabilities for accurate vulnerability detection.
108
109
```bash { .api }
110
# AI analysis features:
111
# - Context-aware vulnerability detection
112
# - Low false-positive rates
113
# - Flow analysis across function boundaries
114
# - Inter-procedural analysis
115
# - Framework-specific security patterns
116
# - Custom rule creation based on codebase patterns
117
# - Real-time analysis during development
118
119
# AI-enhanced detection includes:
120
# - Data flow analysis for injection vulnerabilities
121
# - Control flow analysis for logic flaws
122
# - Taint analysis for input validation issues
123
# - Symbolic execution for complex conditions
124
# - Machine learning models trained on security vulnerabilities
125
```
126
127
## Integration Patterns
128
129
### IDE Integration
130
131
Integration with popular development environments for real-time security feedback.
132
133
```bash { .api }
134
# IDE integrations available:
135
# - Visual Studio Code (Snyk extension)
136
# - IntelliJ IDEA / WebStorm / PyCharm (JetBrains plugin)
137
# - Visual Studio (Snyk extension)
138
# - Eclipse (Snyk plugin)
139
# - Vim/Neovim (command-line integration)
140
141
# Real-time scanning features:
142
# - Inline vulnerability highlighting
143
# - Security issue tooltips
144
# - Fix suggestions and guidance
145
# - Severity indicators
146
# - Integration with code completion
147
```
148
149
### CI/CD Pipeline Integration
150
151
```bash { .api }
152
# GitHub Actions example
153
- name: Code Security Scan
154
run: |
155
snyk code test --severity-threshold=high
156
snyk code test --sarif-file-output=code-results.sarif
157
158
# GitLab CI example
159
code-security-scan:
160
script:
161
- snyk code test --json > code-scan-results.json
162
artifacts:
163
reports:
164
sast: code-scan-results.json
165
166
# Jenkins pipeline
167
stage('Code Security') {
168
steps {
169
sh 'snyk code test --sarif-file-output=code-results.sarif'
170
recordIssues enabledForFailure: true, tools: [sarif(pattern: 'code-results.sarif')]
171
}
172
}
173
174
# Azure DevOps pipeline
175
- task: SnykSecurityScan@1
176
inputs:
177
serviceConnectionEndpoint: 'Snyk'
178
testType: 'code'
179
severityThreshold: 'high'
180
monitorWhen: 'always'
181
```
182
183
### Pre-commit Hooks
184
185
```bash { .api }
186
# Pre-commit integration
187
# .pre-commit-config.yaml
188
repos:
189
- repo: local
190
hooks:
191
- id: snyk-code
192
name: Snyk Code Security Scan
193
entry: snyk code test
194
language: system
195
files: \.(js|ts|py|java|cs|php|go|rb)$
196
stages: [commit]
197
198
# Git hooks setup
199
#!/bin/bash
200
# .git/hooks/pre-commit
201
snyk code test --severity-threshold=high
202
if [ $? -ne 0 ]; then
203
echo "Security vulnerabilities found. Commit blocked."
204
exit 1
205
fi
206
```
207
208
### Developer Workflow Integration
209
210
```bash { .api }
211
# Development workflow patterns
212
git checkout -b feature/new-feature # Create feature branch
213
# ... develop code ...
214
snyk code test ./src/ # Test changes locally
215
git add . # Stage changes
216
git commit -m "Add new feature" # Commit triggers pre-commit scan
217
git push origin feature/new-feature # Push triggers CI scan
218
# ... create pull request ...
219
# PR checks include automated code security scan
220
```
221
222
## Advanced Code Analysis Features
223
224
### Custom Security Rules
225
226
Configuration of custom security rules for organization-specific requirements.
227
228
```bash { .api }
229
# Custom rule configuration
230
# .snyk policy file for code analysis
231
version: v1.0.0
232
code:
233
ignore:
234
SNYK-JS-AXIOS-572124: # Ignore specific vulnerability
235
- "*":
236
reason: "False positive - validated input"
237
expires: "2024-12-31T23:59:59.999Z"
238
239
custom-rules: # Custom security rules
240
- rule-id: "CUSTOM-001"
241
description: "Detect custom authentication bypass"
242
pattern: "bypassAuth\\(.*\\)"
243
severity: "high"
244
languages: ["javascript", "typescript"]
245
```
246
247
### Framework-Specific Analysis
248
249
Specialized analysis for popular frameworks and libraries.
250
251
```bash { .api }
252
# Framework-specific security patterns:
253
254
# React/JSX
255
snyk code test ./react-app/ # JSX injection, state management issues
256
# - Dangerous dangerouslySetInnerHTML usage
257
# - XSS through React component props
258
# - State injection vulnerabilities
259
260
# Angular
261
snyk code test ./angular-app/ # Template injection, service security
262
# - Template injection in Angular templates
263
# - Unsafe HTTP client usage
264
# - Angular service security issues
265
266
# Spring Framework
267
snyk code test ./spring-app/ # Spring-specific vulnerabilities
268
# - Spring Expression Language injection
269
# - Unsafe Spring Data queries
270
# - Spring Security misconfigurations
271
272
# Django
273
snyk code test ./django-app/ # Django-specific patterns
274
# - Django ORM injection vulnerabilities
275
# - Template injection in Django templates
276
# - Django middleware security issues
277
278
# Express.js
279
snyk code test ./express-app/ # Express middleware security
280
# - Middleware security vulnerabilities
281
# - Route parameter injection
282
# - Session management issues
283
```
284
285
### Performance and Scalability
286
287
Optimization for large codebases and enterprise-scale analysis.
288
289
```bash { .api }
290
# Performance optimization options
291
snyk code test <path> --max-depth=3 # Limit directory traversal depth
292
snyk code test <path> --exclude="**/node_modules/**,**/vendor/**" # Exclude deps
293
snyk code test <path> --file-limit=1000 # Limit number of files analyzed
294
295
# Parallel processing
296
snyk code test <path> --parallel=4 # Use multiple analysis threads
297
snyk code test <path> --cache # Enable analysis caching
298
299
# Incremental analysis
300
snyk code test <path> --incremental # Only analyze changed files
301
snyk code test <path> --baseline=main # Compare against baseline branch
302
```
303
304
### Reporting and Analytics
305
306
Comprehensive reporting capabilities for security metrics and trends.
307
308
```bash { .api }
309
# Report generation
310
snyk code test <path> --report # Generate detailed report
311
snyk code test <path> --html-report=security-report.html # HTML report
312
snyk code test <path> --pdf-report=security-report.pdf # PDF report
313
314
# Metrics and analytics
315
# - Vulnerability trends over time
316
# - Security debt metrics
317
# - Developer security training insights
318
# - Code quality correlation
319
# - Framework security adoption metrics
320
```
321
322
## Error Handling and Troubleshooting
323
324
```bash { .api }
325
# Common code analysis scenarios
326
snyk code test ./large-project/ # May require performance tuning
327
snyk code test ./mixed-languages/ # Multi-language project support
328
snyk code test ./legacy-code/ # Legacy code pattern detection
329
330
# Error handling
331
if ! snyk code test --severity-threshold=high; then
332
echo "High-severity vulnerabilities found"
333
exit 1
334
fi
335
336
# Debug analysis issues
337
snyk code test --debug # Enable debug output
338
snyk code test --verbose # Verbose analysis information
339
```
340
341
## Types
342
343
### Code Analysis Types
344
345
```typescript { .api }
346
interface CodeTestResult {
347
/** Code security issues found */
348
issues: CodeIssue[];
349
/** Analysis summary */
350
summary: CodeSummary;
351
/** Project information */
352
projectName: string;
353
/** Organization ID */
354
org: string;
355
/** Scan timestamp */
356
timestamp: string;
357
}
358
359
interface CodeIssue {
360
/** Issue identifier */
361
id: string;
362
/** Issue title */
363
title: string;
364
/** Detailed description */
365
description: string;
366
/** Severity level */
367
severity: 'critical' | 'high' | 'medium' | 'low';
368
/** CWE (Common Weakness Enumeration) ID */
369
cwe: string[];
370
/** File path */
371
filePath: string;
372
/** Line number where issue starts */
373
startLine: number;
374
/** Line number where issue ends */
375
endLine: number;
376
/** Column number where issue starts */
377
startColumn: number;
378
/** Column number where issue ends */
379
endColumn: number;
380
/** Code snippet showing the issue */
381
codeSnippet: string;
382
/** Data flow information */
383
dataFlow?: DataFlowStep[];
384
/** Fix suggestions */
385
fixSuggestions?: FixSuggestion[];
386
/** Priority score */
387
priorityScore: number;
388
/** Issue categories */
389
categories: string[];
390
/** Language of the affected file */
391
language: string;
392
/** Rule that detected the issue */
393
rule: string;
394
}
395
396
interface CodeSummary {
397
/** Total issues found */
398
total: number;
399
/** Issues by severity */
400
bySeverity: {
401
critical: number;
402
high: number;
403
medium: number;
404
low: number;
405
};
406
/** Files analyzed */
407
filesAnalyzed: number;
408
/** Lines of code analyzed */
409
linesOfCode: number;
410
/** Analysis duration */
411
analysisDuration: number;
412
/** Languages detected */
413
languages: string[];
414
}
415
416
interface DataFlowStep {
417
/** Step number in data flow */
418
stepNumber: number;
419
/** File path */
420
filePath: string;
421
/** Line number */
422
lineNumber: number;
423
/** Column number */
424
columnNumber: number;
425
/** Flow step description */
426
description: string;
427
/** Code snippet */
428
snippet: string;
429
}
430
431
interface FixSuggestion {
432
/** Fix description */
433
description: string;
434
/** Fix type */
435
type: 'replace' | 'insert' | 'delete';
436
/** Line number to apply fix */
437
lineNumber: number;
438
/** Original code */
439
originalCode: string;
440
/** Suggested replacement */
441
suggestedCode: string;
442
}
443
444
interface SecurityPattern {
445
/** Pattern identifier */
446
id: string;
447
/** Pattern name */
448
name: string;
449
/** Pattern description */
450
description: string;
451
/** Applicable languages */
452
languages: string[];
453
/** Pattern regex */
454
pattern: string;
455
/** Severity level */
456
severity: 'critical' | 'high' | 'medium' | 'low';
457
/** CWE categories */
458
cwe: string[];
459
}
460
```