How to Use cargo deny for Dependency Auditing

`cargo-deny` is a powerful tool for auditing Rust dependencies to detect security vulnerabilities, license violations, and banned crates directly in your CI/CD pipeline or local development environment.

cargo-deny is a powerful tool for auditing Rust dependencies to detect security vulnerabilities, license violations, and banned crates directly in your CI/CD pipeline or local development environment. You configure it via a deny.toml file and run it as a pre-commit hook or CI step to enforce your project's security and compliance policies.

First, install the tool using cargo install cargo-deny. Once installed, initialize a configuration file in your project root with cargo deny init. This generates a default deny.toml where you can define specific rules for bans, advisories, licenses, and sources.

Here is a practical example of a deny.toml configuration that bans a specific crate (e.g., rand version 0.8.0 due to a known issue) and requires all licenses to be permissive:

[graph]
targets = [
    { triple = "x86_64-unknown-linux-gnu" },
    { triple = "x86_64-pc-windows-msvc" },
]

[advisories]
version = 2
ignore = []

[bans]
multiple-versions = "warn"
wildcards = "warn"
highlight = "all"

[[bans.deny]]
name = "rand"
version = "=0.8.0"
reason = "Known vulnerability in this specific version"

[licenses]
unlicensed = "deny"
confidence-threshold = 0.8
allow = [
    "MIT",
    "Apache-2.0",
    "BSD-3-Clause",
]

After configuring the file, run the audit locally to verify your setup:

cargo deny check

To integrate this into your workflow, you can add it to your CI configuration. For example, in a GitHub Actions workflow, you would install and run the check as a single step:

- name: Check dependencies
  uses: EmbarkStudios/cargo-deny-action@v1
  with:
    command: check
    # Optional: fail only on specific categories
    # args: bans licenses

If you want to generate a report for review rather than failing the build immediately, you can output results to JSON or HTML:

cargo deny check --format json --output report.json
cargo deny check --format html --output report.html

The tool checks the entire dependency graph, including transitive dependencies, against the National Vulnerability Database (NVD) and other sources for security advisories. It also ensures that no banned crates are present and that all licenses meet your organization's requirements. By default, cargo deny treats violations as errors, causing the command to exit with a non-zero status code, which is ideal for blocking bad code from merging. You can adjust the severity of specific checks in deny.toml to warn instead of deny if you need to allow certain exceptions temporarily while still getting notified.