# Vulnerability Scanning

Tools, commands, and practices for detecting, triaging, and remediating dependency vulnerabilities.

## Scanning Tools by Ecosystem

### Node.js / npm

```bash
# Built-in audit
npm audit                        # Full audit report
npm audit --json                 # JSON output for CI parsing
npm audit --audit-level=high     # Fail only on high/critical
npm audit fix                    # Auto-fix compatible updates
npm audit fix --force            # Fix with major version updates (review carefully)
npm audit signatures             # Verify package provenance signatures

# Snyk (more comprehensive, needs account)
npx snyk test
npx snyk monitor                 # Continuous monitoring
```

**npm audit output interpretation:**

| Severity | Action | SLA |
|---|---|---|
| Critical | Immediate fix or workaround | Same day |
| High | Fix within sprint | 1 week |
| Moderate | Fix when convenient | 1 month |
| Low | Track, fix in next maintenance window | Quarterly |

### Python / pip

```bash
# pip-audit (official, maintained by PyPA)
pip install pip-audit
pip-audit                        # Scan current environment
pip-audit -r requirements.txt    # Scan requirements file
pip-audit --fix                  # Auto-fix where possible
pip-audit -f json                # JSON output for CI
pip-audit --desc                 # Include vulnerability descriptions

# Safety (alternative)
pip install safety
safety check
safety check -r requirements.txt

# Using osv-scanner (Google OSV database)
osv-scanner --lockfile=requirements.txt
```

### Rust / Cargo

```bash
# cargo-audit (maintained by RustSec)
cargo install cargo-audit
cargo audit                      # Scan Cargo.lock
cargo audit fix                  # Auto-fix (updates Cargo.lock)
cargo audit --json               # JSON output for CI

# cargo-deny (broader: licenses + vulnerabilities + bans)
cargo install cargo-deny
cargo deny check advisories      # Vulnerability check
cargo deny check licenses        # License compliance
cargo deny check bans            # Banned crate check
cargo deny check sources         # Source verification
```

### Go

```bash
# govulncheck (official Go vulnerability scanner)
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...                # Scan all packages
govulncheck -json ./...          # JSON output
govulncheck -mode=binary ./app   # Scan compiled binary

# Key advantage: govulncheck checks if vulnerable functions are actually called
# (reduces false positives significantly)
```

### Multi-Ecosystem

```bash
# OSV-Scanner (Google, supports all ecosystems)
osv-scanner -r .                 # Recursive scan
osv-scanner --lockfile=package-lock.json
osv-scanner --sbom=sbom.cdx.json

# Trivy (Aqua Security, supports code + containers + IaC)
trivy fs .                       # Scan filesystem
trivy image ghcr.io/org/app:tag  # Scan container image
trivy sbom sbom.cdx.json         # Scan SBOM

# Grype (Anchore, fast vulnerability scanner)
grype dir:.                      # Scan directory
grype sbom:sbom.cdx.json         # Scan SBOM
```

## CI/CD Integration

### GitHub Actions

```yaml
name: Dependency Security
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
  schedule:
    - cron: '0 9 * * 1'  # Weekly Monday 9am

jobs:
  audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version-file: '.nvmrc'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Security audit
        run: npm audit --audit-level=high

      - name: Verify provenance signatures
        run: npm audit signatures

      - name: Check for known vulnerabilities (OSV)
        uses: google/osv-scanner-action/osv-scanner-action@v1
        with:
          scan-args: |-
            --lockfile=package-lock.json
```

### GitLab CI

```yaml
dependency-audit:
  stage: security
  script:
    - npm ci
    - npm audit --audit-level=high
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
    - if: '$CI_COMMIT_BRANCH == "main"'
    - if: '$CI_PIPELINE_SOURCE == "schedule"'
```

## Triage and Prioritization

Not all vulnerabilities are equal. Use this framework to prioritize:

### Reachability Analysis

A vulnerability only matters if the vulnerable code path is reachable from your application. Fewer than 10% of reported dependency vulnerabilities are actually exploitable.

```bash
# Go: govulncheck automatically checks reachability
govulncheck ./...
# Output distinguishes "called" vs "imported but not called"

# Node.js: check if vulnerable function is used
# 1. Identify the vulnerable function from the advisory
# 2. Search your codebase and the dependency tree for calls to it
npm ls <vulnerable-package>  # See where it appears in tree
```

### Prioritization Matrix

| Factor | Weight | How to Assess |
|---|---|---|
| Severity (CVSS) | High | Advisory rating (Critical/High/Medium/Low) |
| Reachability | Critical | Is the vulnerable function called? |
| Exposure | High | Is it in a public-facing service or internal tool? |
| Exploitability | High | Is there a known exploit? Is it actively exploited? |
| Fix availability | Medium | Is a patched version available? |
| Dependency depth | Low | Direct dependency vs deep transitive |

### Decision Tree

```
Is the vulnerable function reachable from your code?
├── NO: Log as informational, monitor for changes
└── YES: Is there a patched version available?
    ├── YES: Is upgrading a breaking change?
    │   ├── NO: Upgrade immediately
    │   └── YES: Is the vulnerability actively exploited?
    │       ├── YES: Emergency upgrade + code changes
    │       └── NO: Plan upgrade within SLA
    └── NO: Is there a workaround?
        ├── YES: Apply workaround, monitor for upstream fix
        └── NO: Consider replacing the dependency or forking + patching
```

## Remediation Strategies

### Strategy 1: Direct Upgrade

The simplest fix -- update to a patched version:

```bash
# npm
npm install <package>@<patched-version>
npm audit fix

# pip
pip install <package>==<patched-version>

# cargo
cargo update -p <package>
```

### Strategy 2: Transitive Dependency Override

When the vulnerability is in a transitive dependency and the direct dependency has not updated:

```json
// npm: package.json overrides
{
  "overrides": {
    "vulnerable-transitive-pkg": ">=2.0.1"
  }
}
```

```toml
# Cargo.toml: patch section
[patch.crates-io]
vulnerable-crate = { git = "https://github.com/org/patched-fork" }
```

### Strategy 3: Replace the Dependency

When no fix is available and the dependency is replaceable:

1. Identify alternative packages that provide the same functionality
2. Evaluate alternatives using the Package Health Assessment
3. Plan migration (wrapper pattern makes this easier)
4. Replace and verify

### Strategy 4: Fork and Patch

When no fix is available and the dependency cannot be replaced:

1. Fork the dependency repository
2. Apply the security patch
3. Publish under your org scope or use git dependency
4. Open PR upstream to contribute the fix back
5. Monitor upstream for official fix and plan to un-fork

## Vulnerability Database Sources

| Database | Coverage | URL |
|---|---|---|
| **OSV** (Google) | All ecosystems | https://osv.dev |
| **NVD** (NIST) | All software | https://nvd.nist.gov |
| **GitHub Advisory** | npm, pip, Go, Rust, etc. | https://github.com/advisories |
| **RustSec** | Rust crates | https://rustsec.org |
| **npm Advisories** | npm packages | via `npm audit` |
| **PyPI Advisory** | Python packages | via `pip-audit` |
| **Snyk Vulnerability DB** | All ecosystems | https://security.snyk.io |

## Reporting Template

```markdown
## Vulnerability Report: <date>

### Summary
- Total dependencies scanned: <count>
- Vulnerabilities found: <count>
- Critical: <count> | High: <count> | Medium: <count> | Low: <count>
- Reachable vulnerabilities: <count>

### Critical/High Findings

| Package | Version | CVE | Severity | Reachable | Fix Available | Action |
|---|---|---|---|---|---|---|
| | | | | | | |

### Remediation Plan

| Finding | Action | Owner | Due Date | Status |
|---|---|---|---|---|
| | | | | |

### Metrics

- Mean time to remediate critical: <days>
- Dependencies more than 1 major behind: <count>
- Last full audit date: <date>
```
