devsecops

Performing SCA Dependency Scanning with Snyk

This skill covers implementing Software Composition Analysis (SCA) using Snyk to detect vulnerable open-source dependencies in CI/CD pipelines. It addresses scanning package manifests and lockfiles, automated fix pull request generation, license compliance checking, continuous monitoring of deployed applications, and integration with GitHub, GitLab, and Jenkins pipelines.

cicddependency-scanningdevsecopsscasecure-sdlcsnyk
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

  • When applications use open-source packages that may contain known vulnerabilities
  • When compliance requires tracking and remediating vulnerable dependencies (PCI DSS, SOC 2)
  • When needing automated fix PRs for vulnerable dependencies in CI/CD
  • When license compliance requires visibility into open-source license obligations
  • When continuous monitoring is needed for newly disclosed vulnerabilities in deployed dependencies

Do not use for scanning proprietary application code for logic vulnerabilities (use SAST), for runtime vulnerability detection (use DAST), or for container OS package scanning alone (use Trivy for a free alternative).

Prerequisites

  • Snyk account (free tier covers up to 200 tests per month for open source)
  • Snyk CLI installed or Snyk GitHub/GitLab integration configured
  • SNYK_TOKEN environment variable set with API authentication token
  • Project with supported package manifests: package.json, requirements.txt, pom.xml, go.mod, Gemfile, etc.

Workflow

Step 1: Install and Authenticate Snyk CLI

# Install Snyk CLI
npm install -g snyk
 
# Authenticate with Snyk
snyk auth $SNYK_TOKEN
 
# Test the connection
snyk test --json | jq '.summary'

Step 2: Scan Dependencies in CI/CD Pipeline

# .github/workflows/dependency-scan.yml
name: Dependency Security Scan
 
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
  schedule:
    - cron: '0 8 * * 1'  # Weekly Monday 8am
 
jobs:
  snyk-scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
 
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
 
      - name: Install dependencies
        run: npm ci
 
      - name: Run Snyk to check for vulnerabilities
        uses: snyk/actions/node@master
        env:
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
        with:
          args: >
            --severity-threshold=high
            --fail-on=upgradable
            --json-file-output=snyk-results.json
 
      - name: Upload results to Snyk
        if: always()
        uses: snyk/actions/node@master
        env:
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
        with:
          command: monitor
          args: --project-name=${{ github.repository }}
 
      - name: Upload SARIF
        if: always()
        run: |
          npx snyk-to-html -i snyk-results.json -o snyk-report.html

Step 3: Configure Snyk for Multiple Languages

# Python project scanning
snyk test --file=requirements.txt --severity-threshold=high --json > snyk-python.json
 
# Java/Maven project
snyk test --file=pom.xml --severity-threshold=medium --json > snyk-java.json
 
# Go module scanning
snyk test --file=go.mod --severity-threshold=high --json > snyk-go.json
 
# Docker image dependency scanning
snyk container test myapp:latest --severity-threshold=high --json > snyk-container.json
 
# Monorepo: scan all projects
snyk test --all-projects --severity-threshold=high --json > snyk-all.json
 
# IaC scanning (bonus)
snyk iac test terraform/ --severity-threshold=medium --json > snyk-iac.json

Step 4: Configure Snyk Policies for Organization

# .snyk policy file
version: v1.25.0
ignore:
  SNYK-JS-LODASH-1018905:
    - '*':
        reason: "Prototype pollution in lodash. Not exploitable in our usage - no user input reaches affected function."
        expires: 2026-06-01T00:00:00.000Z
        created: 2026-02-23T00:00:00.000Z
 
  SNYK-PYTHON-REQUESTS-6241864:
    - '*':
        reason: "SSRF in requests redirect handling. Mitigated by allowlist at proxy layer."
        expires: 2026-04-01T00:00:00.000Z
 
patch: {}
 
# Severity threshold for CI failures
failOnSeverity: high

Step 5: Enable Automated Fix Pull Requests

# Snyk fix: generate fix PRs for vulnerable dependencies
snyk fix --dry-run  # Preview changes
 
# Apply fixes locally
snyk fix
 
# Enable auto-fix PRs via Snyk dashboard:
# 1. Navigate to Organization Settings > Integrations > GitHub
# 2. Enable "Automatic fix pull requests"
# 3. Set "Fix only direct dependencies" or "Fix direct and transitive"
# 4. Configure branch target (main or develop)

Step 6: License Compliance Scanning

# Check license compliance
snyk test --json | jq '.licensesPolicy'
 
# Snyk license policy configuration via organization settings:
# - Approved licenses: MIT, Apache-2.0, BSD-2-Clause, BSD-3-Clause, ISC
# - Restricted licenses: GPL-3.0, AGPL-3.0 (copyleft risk)
# - Unknown licenses: Flag for manual review

Key Concepts

Term Definition
SCA Software Composition Analysis — identifies vulnerabilities and license risks in open-source dependencies
Transitive Dependency A dependency of a direct dependency, often invisible to developers but still a vulnerability vector
Fix PR Automated pull request generated by Snyk that upgrades a vulnerable dependency to a patched version
Snyk Monitor Continuous monitoring mode that watches deployed projects for newly disclosed vulnerabilities
Exploit Maturity Snyk's assessment of whether a vulnerability has known exploits, proof-of-concept, or no known exploit
Reachable Vulnerability A vulnerability in a function that is actually called by the application code, not just present in the dependency
License Policy Organization-level rules defining which open-source licenses are approved, restricted, or require review

Tools & Systems

  • Snyk Open Source: SCA tool for scanning dependencies across 10+ language ecosystems
  • Snyk CLI: Command-line interface for local and CI/CD scanning of dependencies
  • Snyk Advisor: Package health scoring tool evaluating maintenance, popularity, and security signals
  • OWASP Dependency-Check: Free alternative SCA tool using NVD data for vulnerability matching
  • npm audit / pip-audit: Language-specific built-in audit tools for basic vulnerability checking

Common Scenarios

Scenario: Triaging a Critical Transitive Dependency Vulnerability

Context: Snyk reports a critical RCE vulnerability in a transitive dependency (log4j in a Java application). The direct dependency has not released a patch.

Approach:

  1. Use snyk test --json and examine the dependency path to identify which direct dependency pulls in the vulnerable transitive
  2. Check exploit maturity: if "Mature" or "Proof of Concept", prioritize immediately
  3. If no direct fix exists, use Snyk's patch mechanism or override the transitive version in the build config
  4. For Maven: add <dependencyManagement> section to force the safe version of the transitive dependency
  5. For npm: add an overrides section in package.json to pin the safe version
  6. Add a Snyk ignore with expiration date if no patch is available yet
  7. Monitor the direct dependency for a release that updates the transitive

Pitfalls: Ignoring transitive vulnerabilities because "we don't use that function directly" is risky. Attackers can chain vulnerabilities across dependency boundaries. Version overrides can break API compatibility between the direct and transitive dependency.

Output Format

Snyk Dependency Scan Report
=============================
Project: org/web-application
Manifest: package.json
Dependencies: 342 (47 direct, 295 transitive)
Scan Date: 2026-02-23
 
VULNERABILITY SUMMARY:
  Critical: 1  (1 fixable)
  High: 4      (3 fixable)
  Medium: 12   (8 fixable)
  Low: 23      (15 fixable)
 
CRITICAL:
  SNYK-JS-EXPRESS-1234567
    Package: express@4.17.1 (direct)
    Severity: Critical (CVSS 9.8)
    Exploit: Mature
    Fix: Upgrade to express@4.21.0
    Path: express@4.17.1
 
HIGH:
  SNYK-JS-JSONWEBTOKEN-5678901
    Package: jsonwebtoken@8.5.1 (transitive)
    Severity: High (CVSS 7.6)
    Exploit: Proof of Concept
    Fix: Upgrade passport@0.7.0 (which upgrades jsonwebtoken)
    Path: passport@0.6.0 > jsonwebtoken@8.5.1
 
LICENSE ISSUES:
  [RESTRICTED] GPL-3.0: some-package@1.2.3 (transitive via other-pkg)
 
QUALITY GATE: FAILED (1 Critical with fix available)
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md2.3 KB

SCA Dependency Scanning with Snyk - API Reference

Snyk CLI Commands

snyk test

Scans project dependencies for known vulnerabilities.

snyk test --json --severity-threshold=high
snyk test --json --all-projects          # Monorepo support
snyk test --json --file=package-lock.json

Exit codes:

  • 0: No vulnerabilities found
  • 1: Vulnerabilities found
  • 2: Failure (missing manifest, auth error)

snyk monitor

Creates a project snapshot for continuous monitoring on snyk.io.

snyk monitor --json --project-name="my-app"

snyk auth

Authenticate with Snyk API token.

snyk auth <API_TOKEN>
export SNYK_TOKEN=<API_TOKEN>

JSON Output Structure

Test Result Fields

Field Type Description
vulnerabilities array List of vulnerability objects
ok boolean True if no vulns found
dependencyCount int Total dependencies scanned
packageManager string npm, pip, maven, etc.
uniqueCount int Unique vulnerability count

Vulnerability Object

Field Type Description
id string Snyk vulnerability ID (e.g., SNYK-JS-LODASH-590103)
title string Human-readable title
severity string critical, high, medium, low
cvssScore float CVSS v3.1 score (0-10)
packageName string Affected package name
version string Installed version
fixedIn array Versions with fix available
exploit string Exploit maturity: Mature, Proof of Concept, Not Defined
isUpgradable boolean Can be fixed by upgrading direct dependency
isPatchable boolean Snyk patch available
from array Dependency path from root

SARIF Integration

Snyk results can be converted to SARIF 2.1.0 for GitHub Code Scanning. The SARIF schema is at: https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json

Severity Mapping

Snyk Severity CVSS Range SARIF Level
critical 9.0 - 10.0 error
high 7.0 - 8.9 error
medium 4.0 - 6.9 warning
low 0.1 - 3.9 warning

CLI Usage

python agent.py --project /app --severity high --max-critical 0 --max-high 5 --output report.json
standards.md2.7 KB

Standards Reference: SCA Dependency Scanning with Snyk

OWASP Top 10 - A06:2021 Vulnerable and Outdated Components

  • Applications using components with known vulnerabilities may be exploitable
  • SCA tools like Snyk identify vulnerable versions and provide upgrade paths
  • Includes both direct and transitive dependency scanning

NIST SSDF (SP 800-218)

PW.4: Reuse Existing, Well-Secured Software

  • PW.4.1: Verify that acquired software meets security requirements
  • PW.4.2: Review, analyze, and test software to identify vulnerabilities
  • SCA scanning of all third-party components before integration

PW.4.4: Maintain Provenance Data

  • Track the origin and version of all third-party software components
  • Snyk monitor provides continuous tracking of dependency versions

CIS Software Supply Chain Security

Dependencies (DP) Controls

  • DP-1: Pin dependencies to specific versions
  • DP-2: Automate dependency vulnerability scanning in CI/CD
  • DP-3: Review and approve new dependency additions
  • DP-4: Monitor deployed dependencies for newly disclosed vulnerabilities

OWASP SAMM - Software Security

Security Testing - Maturity Level 1

  • Automated dependency scanning using default configurations
  • Visibility of vulnerable components to development teams

Security Testing - Maturity Level 2

  • Custom policies for severity thresholds and license compliance
  • Automated fix PRs for upgradable vulnerabilities
  • Tracking of exploit maturity to prioritize remediation

Security Testing - Maturity Level 3

  • Reachability analysis to identify actually exploitable vulnerabilities
  • Integration with vulnerability management for SLA tracking
  • Correlation with runtime monitoring for risk-based prioritization

PCI DSS v4.0

  • 6.2.4: Use automated methods to prevent common software attacks
  • 6.3.2: Maintain an inventory of custom and third-party software components
  • 6.3.3: Software components not needed for operation removed or identified

Executive Order 14028 (US Federal)

  • Section 4(e): Agencies shall employ automated tools for continuous monitoring of vulnerabilities in software
  • SBOM requirement: All software suppliers must provide SBOMs listing all components including open-source
  • Aligns with Snyk's SBOM generation and continuous monitoring capabilities

License Compliance Framework

License Type Risk Level Policy Examples
Permissive Low Auto-approve MIT, BSD-2, BSD-3, ISC, Apache-2.0
Weak Copyleft Medium Review LGPL-2.1, LGPL-3.0, MPL-2.0
Strong Copyleft High Restrict GPL-2.0, GPL-3.0, AGPL-3.0
Unknown/Custom High Manual Review Proprietary, SSPL, BSL
workflows.md3.8 KB

Workflow Reference: SCA Dependency Scanning with Snyk

Dependency Scanning Pipeline

Code Push / PR


┌──────────────────┐
│ Install Deps     │
│ (npm ci, pip     │
│  install, etc.)  │
└──────┬───────────┘


┌──────────────────┐
│ Snyk Test        │──── Report JSON ───> Artifact Storage
│ (vuln scan)      │
└──────┬───────────┘

  ┌────┴────┐
  │         │
PASS      FAIL ──────> PR Comment with vuln details
  │                     │
  │                     ▼
  │              ┌──────────────┐
  │              │ Snyk Fix PR  │
  │              │ (auto-gen)   │
  │              └──────────────┘

┌──────────────────┐
│ Snyk Monitor     │
│ (continuous)     │
└──────┬───────────┘


  Ongoing alerts for
  new disclosures

Snyk CLI Command Reference

Scanning Commands

# Basic vulnerability test
snyk test
 
# Test with severity filter
snyk test --severity-threshold=high
 
# Test with exploit maturity filter
snyk test --severity-threshold=high
 
# Test specific manifest
snyk test --file=package-lock.json
 
# Test all projects in monorepo
snyk test --all-projects
 
# Test with dev dependencies excluded
snyk test --production
 
# Output in JSON
snyk test --json --json-file-output=results.json
 
# Output in SARIF
snyk test --sarif --sarif-file-output=results.sarif

Monitoring Commands

# Monitor project for new vulnerabilities
snyk monitor --project-name="my-app-prod"
 
# Monitor specific branch
snyk monitor --target-reference=main
 
# Monitor with tags
snyk monitor --project-tags=env=production,team=platform

Fix Commands

# Preview available fixes
snyk fix --dry-run
 
# Apply fixes to direct dependencies
snyk fix
 
# Apply fixes including dev dependencies
snyk fix --dev

Vulnerability Prioritization Matrix

Factor Score Weight Description
CVSS Score 30% Base vulnerability severity
Exploit Maturity 25% Mature > POC > No Known Exploit
Reachability 20% Function called > Imported > Present
Fix Availability 15% Upgrade available > Patch > None
Dependency Depth 10% Direct > Transitive (1 hop) > Deep transitive

Snyk Integration Options

Platform Integration Method Features
GitHub GitHub App Auto-scan PRs, fix PRs, SARIF upload
GitLab GitLab Integration MR comments, dependency scanning
Jenkins Snyk Plugin Pipeline step, HTML reports
Azure DevOps Extension Pipeline task, dashboard widget
Bitbucket Bitbucket App PR checks, fix PRs
CLI npm/binary Local scanning, CI/CD integration

Remediation Strategy by Vulnerability Type

Direct Dependency Vulnerability

  1. Check if upgrade is available: snyk test --json | jq '.vulnerabilities[] | select(.isUpgradable)'
  2. If upgradable: run snyk fix or manually upgrade
  3. Verify no breaking changes in the upgrade
  4. If not upgradable: check for patch or accept risk with ignore

Transitive Dependency Vulnerability

  1. Identify the dependency chain: snyk test --json | jq '.vulnerabilities[].from'
  2. Check if upgrading the direct dependency resolves it
  3. If not: use version overrides in package manager
  4. npm: overrides in package.json
  5. Maven: dependencyManagement in pom.xml
  6. Gradle: constraints in build.gradle
  7. Poetry: tool.poetry.extras or constraint resolution

Scripts 2

agent.py6.3 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""SCA Dependency Scanning with Snyk agent — runs Snyk CLI to test
project dependencies for known vulnerabilities, generates SARIF output,
and enforces quality gates."""

import argparse
import json
import subprocess
from datetime import datetime
from pathlib import Path


def run_snyk_test(project_path: str, severity_threshold: str = "low",
                  extra_args: list = None) -> dict:
    """Run snyk test and return parsed JSON results."""
    cmd = ["snyk", "test", "--json", f"--severity-threshold={severity_threshold}"]
    if extra_args:
        cmd.extend(extra_args)
    try:
        result = subprocess.run(cmd, capture_output=True, text=True,
                                cwd=project_path, timeout=300)
        if result.stdout:
            return json.loads(result.stdout)
        return {"error": result.stderr, "exit_code": result.returncode}
    except subprocess.TimeoutExpired:
        return {"error": "Snyk test timed out after 300s"}
    except FileNotFoundError:
        return {"error": "snyk CLI not found. Install: npm install -g snyk"}
    except json.JSONDecodeError:
        return {"error": "Failed to parse Snyk output", "raw": result.stdout[:2000]}


def run_snyk_monitor(project_path: str) -> dict:
    """Run snyk monitor to create a snapshot for continuous monitoring."""
    cmd = ["snyk", "monitor", "--json"]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True,
                                cwd=project_path, timeout=300)
        if result.stdout:
            return json.loads(result.stdout)
        return {"error": result.stderr}
    except (subprocess.TimeoutExpired, FileNotFoundError, json.JSONDecodeError) as e:
        return {"error": str(e)}


def parse_vulnerabilities(snyk_result: dict) -> list[dict]:
    """Extract and normalize vulnerability findings."""
    vulns = snyk_result.get("vulnerabilities", [])
    findings = []
    for v in vulns:
        findings.append({
            "id": v.get("id", ""),
            "title": v.get("title", ""),
            "severity": v.get("severity", "unknown"),
            "cvss_score": v.get("cvssScore", 0),
            "package": v.get("packageName", ""),
            "version": v.get("version", ""),
            "fixed_in": v.get("fixedIn", []),
            "exploit_maturity": v.get("exploit", "Not Defined"),
            "is_upgradable": v.get("isUpgradable", False),
            "is_patchable": v.get("isPatchable", False),
            "from_path": v.get("from", []),
        })
    return findings


def apply_quality_gate(findings: list[dict], max_critical: int = 0,
                       max_high: int = 5) -> dict:
    """Apply quality gate based on severity counts."""
    counts = {"critical": 0, "high": 0, "medium": 0, "low": 0}
    for f in findings:
        sev = f.get("severity", "low").lower()
        counts[sev] = counts.get(sev, 0) + 1

    passed = counts["critical"] <= max_critical and counts["high"] <= max_high
    return {
        "passed": passed,
        "severity_counts": counts,
        "gate_criteria": {"max_critical": max_critical, "max_high": max_high},
        "reason": "PASS" if passed else f"FAIL: {counts['critical']} critical (max {max_critical}), {counts['high']} high (max {max_high})",
    }


def generate_sarif(findings: list[dict], project_path: str) -> dict:
    """Convert findings to SARIF 2.1.0 format for GitHub integration."""
    rules = []
    results = []
    seen_ids = set()
    for f in findings:
        rule_id = f["id"]
        if rule_id not in seen_ids:
            rules.append({
                "id": rule_id,
                "shortDescription": {"text": f["title"]},
                "defaultConfiguration": {
                    "level": "error" if f["severity"] in ("critical", "high") else "warning"
                },
            })
            seen_ids.add(rule_id)
        results.append({
            "ruleId": rule_id,
            "message": {"text": f"{f['title']} in {f['package']}@{f['version']}"},
            "level": "error" if f["severity"] in ("critical", "high") else "warning",
        })

    return {
        "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json",
        "version": "2.1.0",
        "runs": [{
            "tool": {"driver": {"name": "Snyk", "rules": rules}},
            "results": results,
        }],
    }


def generate_report(project_path: str, severity_threshold: str,
                    max_critical: int, max_high: int) -> dict:
    """Run full scan and build consolidated report."""
    snyk_result = run_snyk_test(project_path, severity_threshold)
    if "error" in snyk_result and "vulnerabilities" not in snyk_result:
        return {"report": "sca_dependency_scan", "error": snyk_result["error"]}

    findings = parse_vulnerabilities(snyk_result)
    gate = apply_quality_gate(findings, max_critical, max_high)
    sarif = generate_sarif(findings, project_path)

    return {
        "report": "sca_dependency_scan",
        "generated_at": datetime.utcnow().isoformat() + "Z",
        "project_path": project_path,
        "total_vulnerabilities": len(findings),
        "quality_gate": gate,
        "unique_packages_affected": len(set(f["package"] for f in findings)),
        "upgradable_count": sum(1 for f in findings if f["is_upgradable"]),
        "patchable_count": sum(1 for f in findings if f["is_patchable"]),
        "findings": findings,
        "sarif": sarif,
    }


def main():
    parser = argparse.ArgumentParser(description="SCA Dependency Scanning with Snyk Agent")
    parser.add_argument("--project", required=True, help="Project directory to scan")
    parser.add_argument("--severity", default="low", choices=["low", "medium", "high", "critical"])
    parser.add_argument("--max-critical", type=int, default=0, help="Max critical vulns for quality gate")
    parser.add_argument("--max-high", type=int, default=5, help="Max high vulns for quality gate")
    parser.add_argument("--output", help="Output JSON file path")
    args = parser.parse_args()

    report = generate_report(args.project, args.severity, args.max_critical, args.max_high)
    output = json.dumps(report, indent=2)
    if args.output:
        Path(args.output).write_text(output, encoding="utf-8")
        print(f"Report written to {args.output}")
    else:
        print(output)


if __name__ == "__main__":
    main()
process.py8.8 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Snyk SCA Dependency Scanning Pipeline Script

Orchestrates Snyk dependency scans, evaluates quality gates,
and generates consolidated vulnerability reports.

Usage:
    python process.py --project-path /path/to/project --severity-threshold high
    python process.py --project-path . --manifest package.json --output report.json
"""

import argparse
import json
import os
import subprocess
import sys
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Optional


SEVERITY_ORDER = {"critical": 0, "high": 1, "medium": 2, "low": 3}


@dataclass
class VulnFinding:
    snyk_id: str
    title: str
    severity: str
    cvss_score: float
    package_name: str
    installed_version: str
    fixed_version: str
    exploit_maturity: str
    is_upgradable: bool
    is_patchable: bool
    dependency_path: list = field(default_factory=list)
    cwe: list = field(default_factory=list)


@dataclass
class LicenseIssue:
    package_name: str
    version: str
    license_id: str
    severity: str
    dependency_type: str


def run_snyk_test(project_path: str, manifest: Optional[str] = None,
                  severity_threshold: str = "low",
                  all_projects: bool = False) -> dict:
    """Execute Snyk test and return JSON results."""
    cmd = ["snyk", "test", "--json"]

    if manifest:
        cmd.extend(["--file", manifest])
    if all_projects:
        cmd.append("--all-projects")
    cmd.extend(["--severity-threshold", severity_threshold])

    try:
        proc = subprocess.run(
            cmd,
            cwd=project_path,
            capture_output=True,
            text=True,
            timeout=300
        )

        if proc.stdout:
            try:
                return json.loads(proc.stdout)
            except json.JSONDecodeError:
                return {"error": "Failed to parse Snyk JSON output"}
        return {"error": proc.stderr[:500]}

    except subprocess.TimeoutExpired:
        return {"error": "Snyk test timed out after 300 seconds"}
    except FileNotFoundError:
        return {"error": "snyk CLI not found. Install with: npm install -g snyk"}


def parse_vulnerabilities(snyk_json: dict) -> list:
    """Parse Snyk JSON output into VulnFinding objects."""
    vulns = []
    vuln_list = snyk_json.get("vulnerabilities", [])

    for v in vuln_list:
        vulns.append(VulnFinding(
            snyk_id=v.get("id", ""),
            title=v.get("title", ""),
            severity=v.get("severity", "low"),
            cvss_score=v.get("cvssScore", 0.0),
            package_name=v.get("packageName", ""),
            installed_version=v.get("version", ""),
            fixed_version=v.get("fixedIn", ["none"])[0] if v.get("fixedIn") else "none",
            exploit_maturity=v.get("exploit", "No Known Exploit"),
            is_upgradable=v.get("isUpgradable", False),
            is_patchable=v.get("isPatchable", False),
            dependency_path=v.get("from", []),
            cwe=v.get("identifiers", {}).get("CWE", [])
        ))

    return vulns


def deduplicate_vulns(vulns: list) -> list:
    """Remove duplicate vulnerability entries (same ID + package)."""
    seen = set()
    unique = []
    for v in vulns:
        key = f"{v.snyk_id}:{v.package_name}:{v.installed_version}"
        if key not in seen:
            seen.add(key)
            unique.append(v)
    return unique


def evaluate_quality_gate(vulns: list, threshold: str,
                          fail_on: str = "all") -> dict:
    """Evaluate quality gate based on vulnerability severity."""
    threshold_level = SEVERITY_ORDER.get(threshold.lower(), 1)

    blocking = []
    for v in vulns:
        if SEVERITY_ORDER.get(v.severity.lower(), 3) <= threshold_level:
            if fail_on == "upgradable" and not v.is_upgradable:
                continue
            blocking.append(v)

    severity_counts = {}
    for v in vulns:
        sev = v.severity.lower()
        severity_counts[sev] = severity_counts.get(sev, 0) + 1

    fixable_count = sum(1 for v in vulns if v.is_upgradable or v.is_patchable)

    return {
        "passed": len(blocking) == 0,
        "threshold": threshold,
        "fail_on": fail_on,
        "total_vulnerabilities": len(vulns),
        "blocking_count": len(blocking),
        "fixable_count": fixable_count,
        "severity_counts": severity_counts,
        "blocking_details": [
            {
                "id": v.snyk_id,
                "title": v.title,
                "severity": v.severity,
                "package": f"{v.package_name}@{v.installed_version}",
                "fix": v.fixed_version,
                "upgradable": v.is_upgradable,
                "exploit": v.exploit_maturity
            }
            for v in blocking[:20]
        ]
    }


def generate_report(vulns: list, quality_gate: dict, snyk_json: dict,
                    project_path: str) -> dict:
    """Generate consolidated SCA report."""
    dep_count = snyk_json.get("dependencyCount", 0)

    exploit_summary = {}
    for v in vulns:
        exploit_summary[v.exploit_maturity] = exploit_summary.get(v.exploit_maturity, 0) + 1

    return {
        "report_metadata": {
            "project": project_path,
            "scan_date": datetime.now(timezone.utc).isoformat(),
            "total_dependencies": dep_count
        },
        "quality_gate": quality_gate,
        "exploit_maturity_breakdown": exploit_summary,
        "vulnerabilities": [
            {
                "id": v.snyk_id,
                "title": v.title,
                "severity": v.severity,
                "cvss": v.cvss_score,
                "package": v.package_name,
                "version": v.installed_version,
                "fixed_in": v.fixed_version,
                "exploit": v.exploit_maturity,
                "upgradable": v.is_upgradable,
                "path": " > ".join(v.dependency_path[:4]),
                "cwe": v.cwe
            }
            for v in sorted(vulns, key=lambda x: SEVERITY_ORDER.get(x.severity.lower(), 3))
        ]
    }


def main():
    parser = argparse.ArgumentParser(description="Snyk SCA Dependency Scanning Pipeline")
    parser.add_argument("--project-path", required=True, help="Path to project")
    parser.add_argument("--manifest", default=None, help="Manifest file (e.g., package.json)")
    parser.add_argument("--output", default="snyk-report.json", help="Output report path")
    parser.add_argument("--severity-threshold", default="high",
                        choices=["critical", "high", "medium", "low"])
    parser.add_argument("--fail-on", default="all", choices=["all", "upgradable"],
                        help="Fail on all vulns or only upgradable ones")
    parser.add_argument("--fail-on-findings", action="store_true")
    parser.add_argument("--all-projects", action="store_true",
                        help="Scan all projects in monorepo")
    parser.add_argument("--monitor", action="store_true",
                        help="Also run snyk monitor for continuous tracking")
    args = parser.parse_args()

    project_path = os.path.abspath(args.project_path)
    print(f"[*] Scanning dependencies in {project_path}")

    snyk_json = run_snyk_test(
        project_path,
        manifest=args.manifest,
        severity_threshold="low",
        all_projects=args.all_projects
    )

    if "error" in snyk_json:
        print(f"[ERROR] {snyk_json['error']}")
        sys.exit(2)

    vulns = parse_vulnerabilities(snyk_json)
    vulns = deduplicate_vulns(vulns)

    quality_gate = evaluate_quality_gate(vulns, args.severity_threshold, args.fail_on)
    report = generate_report(vulns, quality_gate, snyk_json, project_path)

    output_path = os.path.abspath(args.output)
    with open(output_path, "w") as f:
        json.dump(report, f, indent=2)
    print(f"[*] Report: {output_path}")

    print(f"\n[*] Dependencies: {snyk_json.get('dependencyCount', 'N/A')}")
    print(f"[*] Vulnerabilities: {len(vulns)} (fixable: {quality_gate['fixable_count']})")
    for sev, count in sorted(quality_gate["severity_counts"].items(),
                             key=lambda x: SEVERITY_ORDER.get(x[0], 3)):
        print(f"    {sev.upper()}: {count}")

    if quality_gate["passed"]:
        print(f"\n[PASS] Quality gate passed.")
    else:
        print(f"\n[FAIL] {quality_gate['blocking_count']} blocking vulnerabilities.")
        for d in quality_gate["blocking_details"][:10]:
            fix_info = f"fix: {d['fix']}" if d['upgradable'] else "no fix available"
            print(f"  [{d['severity'].upper()}] {d['id']}: {d['package']} ({fix_info})")

    if args.monitor:
        print("\n[*] Running Snyk monitor for continuous tracking...")
        subprocess.run(
            ["snyk", "monitor", "--project-name", os.path.basename(project_path)],
            cwd=project_path
        )

    if args.fail_on_findings and not quality_gate["passed"]:
        sys.exit(1)


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 3.0 KB
Keep exploring