CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-snyk

Developer-first, cloud-native security tool to scan and monitor your software development projects for security vulnerabilities

Pending
Overview
Eval results
Files

source-code-analysis.mddocs/

Source Code Analysis

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.

Capabilities

Code Testing

Command-line interface for static analysis of application source code to detect security vulnerabilities.

# Basic code testing
snyk code test                           # Test current directory
snyk code test <path>                    # Test specific path
snyk code test ./src/                    # Test source directory

# Testing with options
snyk code test <path> --org=<org-id>     # Test with organization
snyk code test <path> --json             # JSON output format
snyk code test <path> --sarif            # SARIF format output
snyk code test <path> --severity-threshold=high # Filter by severity

# Output options
snyk code test <path> --json-file-output=results.json # Save JSON results
snyk code test <path> --sarif-file-output=results.sarif # Save SARIF results

# Project identification
snyk code test <path> --project-name="MyApp Code" # Custom project name
snyk code test <path> --target-reference=main   # Git reference

# Advanced options
snyk code test <path> --exclude="**/test/**"    # Exclude directories
snyk code test <path> --include="**/*.js,**/*.py" # Include patterns
snyk code test <path> --max-depth=5             # Limit directory depth

Supported Languages

Programming languages and frameworks supported by Snyk Code analysis.

# JavaScript and TypeScript
snyk code test ./frontend/               # React, Angular, Vue.js
snyk code test ./backend/                # Node.js, Express

# Python
snyk code test ./python-app/             # Django, Flask, FastAPI
snyk code test ./ml-project/             # NumPy, TensorFlow

# Java
snyk code test ./java-app/               # Spring, Spring Boot
snyk code test ./android-app/            # Android applications

# C# and .NET
snyk code test ./dotnet-app/             # ASP.NET, .NET Core
snyk code test ./webapi/                 # Web APIs

# PHP
snyk code test ./php-app/                # Laravel, Symfony, WordPress

# Go
snyk code test ./go-service/             # Go applications and services

# Ruby
snyk code test ./rails-app/              # Ruby on Rails applications

# C and C++
snyk code test ./c-project/              # C/C++ applications

# Kotlin
snyk code test ./kotlin-app/             # Kotlin applications

# Scala
snyk code test ./scala-service/          # Scala applications

# Swift
snyk code test ./ios-app/                # iOS applications

Security Vulnerability Categories

Types of security vulnerabilities detected by static code analysis.

# Common vulnerability categories detected:
# - SQL Injection (CWE-89)
# - Cross-Site Scripting (XSS) (CWE-79) 
# - Cross-Site Request Forgery (CSRF) (CWE-352)
# - Path Traversal (CWE-22)
# - Command Injection (CWE-78)
# - Code Injection (CWE-94)
# - LDAP Injection (CWE-90)
# - XML Injection (CWE-91)
# - Hardcoded Secrets (CWE-798)
# - Insecure Randomness (CWE-330)
# - Weak Cryptography (CWE-327)
# - Authentication Bypass (CWE-287)
# - Authorization Issues (CWE-863)
# - Information Disclosure (CWE-200)
# - Denial of Service (CWE-400)
# - Buffer Overflow (CWE-120)
# - Use After Free (CWE-416)
# - Null Pointer Dereference (CWE-476)

AI-Powered Analysis

Advanced AI-driven analysis capabilities for accurate vulnerability detection.

# AI analysis features:
# - Context-aware vulnerability detection
# - Low false-positive rates
# - Flow analysis across function boundaries
# - Inter-procedural analysis
# - Framework-specific security patterns
# - Custom rule creation based on codebase patterns
# - Real-time analysis during development

# AI-enhanced detection includes:
# - Data flow analysis for injection vulnerabilities
# - Control flow analysis for logic flaws
# - Taint analysis for input validation issues
# - Symbolic execution for complex conditions
# - Machine learning models trained on security vulnerabilities

Integration Patterns

IDE Integration

Integration with popular development environments for real-time security feedback.

# IDE integrations available:
# - Visual Studio Code (Snyk extension)
# - IntelliJ IDEA / WebStorm / PyCharm (JetBrains plugin)
# - Visual Studio (Snyk extension)
# - Eclipse (Snyk plugin)
# - Vim/Neovim (command-line integration)

# Real-time scanning features:
# - Inline vulnerability highlighting
# - Security issue tooltips
# - Fix suggestions and guidance
# - Severity indicators
# - Integration with code completion

CI/CD Pipeline Integration

# GitHub Actions example
- name: Code Security Scan
  run: |
    snyk code test --severity-threshold=high
    snyk code test --sarif-file-output=code-results.sarif

# GitLab CI example
code-security-scan:
  script:
    - snyk code test --json > code-scan-results.json
  artifacts:
    reports:
      sast: code-scan-results.json

# Jenkins pipeline
stage('Code Security') {
  steps {
    sh 'snyk code test --sarif-file-output=code-results.sarif'
    recordIssues enabledForFailure: true, tools: [sarif(pattern: 'code-results.sarif')]
  }
}

# Azure DevOps pipeline
- task: SnykSecurityScan@1
  inputs:
    serviceConnectionEndpoint: 'Snyk'
    testType: 'code'
    severityThreshold: 'high'
    monitorWhen: 'always'

Pre-commit Hooks

# Pre-commit integration
# .pre-commit-config.yaml
repos:
  - repo: local
    hooks:
      - id: snyk-code
        name: Snyk Code Security Scan
        entry: snyk code test
        language: system
        files: \.(js|ts|py|java|cs|php|go|rb)$
        stages: [commit]

# Git hooks setup
#!/bin/bash
# .git/hooks/pre-commit
snyk code test --severity-threshold=high
if [ $? -ne 0 ]; then
  echo "Security vulnerabilities found. Commit blocked."
  exit 1
fi

Developer Workflow Integration

# Development workflow patterns
git checkout -b feature/new-feature      # Create feature branch
# ... develop code ...
snyk code test ./src/                    # Test changes locally
git add .                                # Stage changes
git commit -m "Add new feature"          # Commit triggers pre-commit scan
git push origin feature/new-feature      # Push triggers CI scan
# ... create pull request ...
# PR checks include automated code security scan

Advanced Code Analysis Features

Custom Security Rules

Configuration of custom security rules for organization-specific requirements.

# Custom rule configuration
# .snyk policy file for code analysis
version: v1.0.0
code:
  ignore:
    SNYK-JS-AXIOS-572124:              # Ignore specific vulnerability
      - "*":
          reason: "False positive - validated input"
          expires: "2024-12-31T23:59:59.999Z"
  
  custom-rules:                        # Custom security rules
    - rule-id: "CUSTOM-001"
      description: "Detect custom authentication bypass"
      pattern: "bypassAuth\\(.*\\)"
      severity: "high"
      languages: ["javascript", "typescript"]

Framework-Specific Analysis

Specialized analysis for popular frameworks and libraries.

# Framework-specific security patterns:

# React/JSX
snyk code test ./react-app/             # JSX injection, state management issues
# - Dangerous dangerouslySetInnerHTML usage
# - XSS through React component props
# - State injection vulnerabilities

# Angular
snyk code test ./angular-app/           # Template injection, service security
# - Template injection in Angular templates
# - Unsafe HTTP client usage
# - Angular service security issues

# Spring Framework  
snyk code test ./spring-app/            # Spring-specific vulnerabilities
# - Spring Expression Language injection
# - Unsafe Spring Data queries
# - Spring Security misconfigurations

# Django
snyk code test ./django-app/            # Django-specific patterns
# - Django ORM injection vulnerabilities
# - Template injection in Django templates
# - Django middleware security issues

# Express.js
snyk code test ./express-app/           # Express middleware security
# - Middleware security vulnerabilities
# - Route parameter injection
# - Session management issues

Performance and Scalability

Optimization for large codebases and enterprise-scale analysis.

# Performance optimization options
snyk code test <path> --max-depth=3     # Limit directory traversal depth
snyk code test <path> --exclude="**/node_modules/**,**/vendor/**" # Exclude deps
snyk code test <path> --file-limit=1000 # Limit number of files analyzed

# Parallel processing
snyk code test <path> --parallel=4      # Use multiple analysis threads
snyk code test <path> --cache           # Enable analysis caching

# Incremental analysis
snyk code test <path> --incremental     # Only analyze changed files
snyk code test <path> --baseline=main   # Compare against baseline branch

Reporting and Analytics

Comprehensive reporting capabilities for security metrics and trends.

# Report generation
snyk code test <path> --report          # Generate detailed report
snyk code test <path> --html-report=security-report.html # HTML report
snyk code test <path> --pdf-report=security-report.pdf   # PDF report

# Metrics and analytics
# - Vulnerability trends over time
# - Security debt metrics
# - Developer security training insights
# - Code quality correlation
# - Framework security adoption metrics

Error Handling and Troubleshooting

# Common code analysis scenarios
snyk code test ./large-project/         # May require performance tuning
snyk code test ./mixed-languages/       # Multi-language project support
snyk code test ./legacy-code/           # Legacy code pattern detection

# Error handling
if ! snyk code test --severity-threshold=high; then
  echo "High-severity vulnerabilities found"
  exit 1
fi

# Debug analysis issues
snyk code test --debug                  # Enable debug output
snyk code test --verbose                # Verbose analysis information

Types

Code Analysis Types

interface CodeTestResult {
  /** Code security issues found */
  issues: CodeIssue[];
  /** Analysis summary */
  summary: CodeSummary;
  /** Project information */
  projectName: string;
  /** Organization ID */
  org: string;
  /** Scan timestamp */
  timestamp: string;
}

interface CodeIssue {
  /** Issue identifier */
  id: string;
  /** Issue title */
  title: string;
  /** Detailed description */
  description: string;
  /** Severity level */
  severity: 'critical' | 'high' | 'medium' | 'low';
  /** CWE (Common Weakness Enumeration) ID */
  cwe: string[];
  /** File path */
  filePath: string;
  /** Line number where issue starts */
  startLine: number;
  /** Line number where issue ends */
  endLine: number;
  /** Column number where issue starts */
  startColumn: number;
  /** Column number where issue ends */
  endColumn: number;
  /** Code snippet showing the issue */
  codeSnippet: string;
  /** Data flow information */
  dataFlow?: DataFlowStep[];
  /** Fix suggestions */
  fixSuggestions?: FixSuggestion[];
  /** Priority score */
  priorityScore: number;
  /** Issue categories */
  categories: string[];
  /** Language of the affected file */
  language: string;
  /** Rule that detected the issue */
  rule: string;
}

interface CodeSummary {
  /** Total issues found */
  total: number;
  /** Issues by severity */
  bySeverity: {
    critical: number;
    high: number;
    medium: number;
    low: number;
  };
  /** Files analyzed */
  filesAnalyzed: number;
  /** Lines of code analyzed */
  linesOfCode: number;
  /** Analysis duration */
  analysisDuration: number;
  /** Languages detected */
  languages: string[];
}

interface DataFlowStep {
  /** Step number in data flow */
  stepNumber: number;
  /** File path */
  filePath: string;
  /** Line number */
  lineNumber: number;
  /** Column number */
  columnNumber: number;
  /** Flow step description */
  description: string;
  /** Code snippet */
  snippet: string;
}

interface FixSuggestion {
  /** Fix description */
  description: string;
  /** Fix type */
  type: 'replace' | 'insert' | 'delete';
  /** Line number to apply fix */
  lineNumber: number;
  /** Original code */
  originalCode: string;
  /** Suggested replacement */
  suggestedCode: string;
}

interface SecurityPattern {
  /** Pattern identifier */
  id: string;
  /** Pattern name */
  name: string;
  /** Pattern description */
  description: string;
  /** Applicable languages */
  languages: string[];
  /** Pattern regex */
  pattern: string;
  /** Severity level */
  severity: 'critical' | 'high' | 'medium' | 'low';
  /** CWE categories */
  cwe: string[];
}

Install with Tessl CLI

npx tessl i tessl/npm-snyk

docs

cli-commands.md

configuration.md

container-security.md

index.md

infrastructure-as-code.md

project-monitoring.md

source-code-analysis.md

vulnerability-testing.md

tile.json