← Effective AI Code Development

Rust Series Part 4: Securing Rust Projects — A Practical Checklist

A practical security checklist for Rust projects: cargo audit, cargo deny, Clippy, Miri, fuzzing, constant-time comparisons, resource limits, minimal unsafe code and dependency vetting.

·15 min read·
#Rust#Security#DevSecOps#Supply Chain#Checklist#AI Engineering#AI-SDLC

Rust provides strong memory-safety guarantees, but developing secure Rust applications requires more than writing code that compiles successfully.

Security vulnerabilities can still emerge through unsafe code, external libraries, application logic, dependencies, and build pipelines.

Fortunately, Rust has an ecosystem of tools that can help teams detect and manage these risks.

In this article, we'll explore a practical security checklist covering:

  • Dependency security: cargo-audit, cargo-deny, cargo-vet, and lockfiles.
  • Static analysis: Clippy and compiler lints.
  • Unsafe-code verification: Miri, sanitizers, and documented safety invariants.
  • Dynamic testing: Fuzzing, property-based testing, and concurrency testing.
  • Application security: Constant-time comparisons, resource limits, checked arithmetic, and secure input handling.
  • Supply-chain security: SBOM generation, build isolation, and CI/CD controls.

We'll also put these practices together into a basic security pipeline.

The goal is to establish a repeatable engineering process that catches vulnerabilities early and makes security checks part of normal software delivery.

Introduction

In the previous three articles, we explored Rust's language fundamentals, its memory-safety advantages, and the vulnerabilities that can still occur in Rust applications.

In Part 3, we examined how unsafe code, FFI boundaries, application logic, and supply-chain dependencies can introduce security risks.

Now let's look at what we can do about them.

Consider a Rust application that uses only safe Rust in its own source code.

It may still depend on third-party crates containing unsafe implementations.

It may accept untrusted input, communicate with external services, process credentials, or execute database queries.

Even if the application is memory-safe, it may contain vulnerabilities that the compiler cannot identify.

This is where secure software development practices become important.

From a DevSecOps perspective, the objective is to integrate security checks into the development lifecycle rather than treating them as a separate activity before production deployment.

Let's build a practical checklist.

1. Start with Dependency and Supply-Chain Security

Most modern applications depend on code developed and maintained by other people.

Rust is no exception.

Cargo makes it straightforward to add dependencies through Cargo.toml.

For example:

[dependencies]
serde = "1"
serde_json = "1"

Cargo resolves the dependency graph and records exact resolved versions in Cargo.lock.

But adding a dependency also introduces a trust relationship.

The dependency may contain vulnerabilities, execute build-time code, or rely on other dependencies.

Commit Cargo.lock

For executable applications, commit Cargo.lock to version control.

This records the resolved dependency versions used by the project.

In CI, use:

cargo build --locked

The --locked flag prevents Cargo from updating the lockfile during the build.

If dependency resolution requires modifying the lockfile, the command fails.

This helps maintain consistency between development, testing, and CI builds.

However, a lockfile does not guarantee that dependencies are secure, nor does it by itself guarantee fully reproducible build artifacts.

Scan known vulnerabilities with cargo-audit

cargo-audit checks dependencies recorded in Cargo.lock against the RustSec Advisory Database.

Install it:

cargo install cargo-audit --locked

Run:

cargo audit

The tool reports relevant known security advisories and can surface other advisory categories depending on its version and configuration.

This helps teams identify vulnerable dependencies before they reach production.

However, cargo-audit cannot detect every malicious crate, undisclosed vulnerability, or insecure implementation.

It is an advisory scanner, not a complete supply-chain security solution.

Enforce dependency policies with cargo-deny

cargo-deny provides additional dependency governance.

It can check:

  • Known security advisories.
  • Dependency licenses.
  • Banned or duplicated crates.
  • Dependency source policies.

Install:

cargo install cargo-deny --locked

Initialize configuration:

cargo deny init

Run:

cargo deny check

The generated deny.toml should be reviewed and customized for the project.

For example, an organization may restrict dependency sources or establish approved license policies.

These decisions should reflect the organization's legal, security, and operational requirements.

Consider cargo-vet for dependency review

cargo-vet supports dependency review workflows.

It allows teams to record evidence that particular crate versions have been reviewed against defined criteria.

This can be useful for organizations that need stronger dependency assurance.

However, a review record is not proof that a crate is vulnerability-free.

It represents review evidence that should be maintained as dependencies change.

Review crates before adoption

Before adding a dependency, consider:

  • Is the crate actively maintained?
  • Who maintains it?
  • Does it have published security advisories?
  • Does it introduce substantial transitive dependencies?
  • Does it contain unsafe code?
  • Does it execute build scripts?
  • Is the crate name correct?
  • Is the dependency necessary?

Avoid introducing dependencies for functionality that can be implemented simply and safely without them.

At the same time, don't replace well-maintained security libraries with custom implementations merely to reduce dependency counts.

The objective is to make dependency decisions deliberately.

2. Use Compiler Lints and Static Analysis

Rust's compiler already catches many programming mistakes.

Clippy extends this by identifying suspicious patterns, inefficient constructs, and potentially problematic coding practices.

Run Clippy

cargo clippy --all-targets -- -D warnings

This treats reported warnings as errors.

For a workspace:

cargo clippy --workspace --all-targets -- -D warnings

Clippy can identify common problems such as unnecessary conversions, suspicious code patterns, and certain error-prone constructs.

However, Clippy is not a comprehensive security vulnerability scanner.

It should be part of a broader analysis and testing process.

Enable stricter lints

Some projects benefit from stricter lint policies.

Examples include:

#![warn(clippy::unwrap_used)]
#![warn(clippy::expect_used)]
#![warn(clippy::arithmetic_side_effects)]

These lints can highlight:

  • Potentially unchecked error handling.
  • Panics caused by incorrect assumptions.
  • Arithmetic that deserves additional review.

Stricter linting may introduce noise, particularly in tests or prototypes.

Apply policies based on the application's risk profile.

For example, code processing untrusted financial transactions may require stricter arithmetic and error-handling rules than a small local utility.

Restrict unsafe code

If a crate does not require unsafe code, explicitly forbid it:

#![forbid(unsafe_code)]

This prevents unsafe code from being introduced into that crate without changing the policy.

It does not prevent dependencies from containing unsafe code.

For crates that require unsafe operations, enable:

#![deny(unsafe_op_in_unsafe_fn)]

This requires unsafe operations within unsafe functions to be placed inside explicit unsafe blocks.

The lint is already warn-by-default in the Rust 2024 edition, but explicitly denying it can establish a consistent project policy.

3. Review and Contain Unsafe Code

Unsafe Rust deserves additional attention because it allows operations whose memory-safety requirements cannot be fully verified by the compiler.

The objective is not necessarily to eliminate all unsafe code.

Some low-level operations require it.

Instead, unsafe code should be minimized, isolated, documented, and tested.

Keep unsafe operations small

Prefer narrowly scoped unsafe blocks rather than large sections of code containing unrelated operations.

For example:

fn read_pointer(pointer: *const i32) -> Option<i32> {
    if pointer.is_null() {
        return None;
    }

    // SAFETY:
    // A null check alone does not establish pointer validity.
    // This function would need additional caller guarantees
    // about alignment, initialization, and object lifetime.

    None
}

This example deliberately avoids dereferencing the pointer.

Why?

Because checking whether a raw pointer is null is not sufficient to establish that dereferencing it is safe.

A pointer may be non-null but still dangling, misaligned, or otherwise invalid.

A real implementation must establish the complete safety contract.

Document safety invariants

Unsafe operations should include comments explaining why they are valid.

A useful safety review should answer:

  • What makes the pointer valid?
  • Who owns the memory?
  • How long does the allocation remain alive?
  • Can another thread modify or free the object?
  • What alignment and initialization guarantees apply?
  • What happens if an external function violates its contract?

Documentation is particularly important when unsafe code is wrapped in a safe public API.

The wrapper must preserve memory safety for every valid use of that API.

Be careful with Send and Sync

Rust uses Send and Sync to express important thread-safety properties.

Manually implementing these unsafe traits makes promises about how values can be transferred or shared across threads.

Incorrect implementations can introduce data races or other undefined behavior.

This is especially important when wrapping C libraries or low-level data structures.

4. Test Unsafe Code with Miri

Miri is an interpreter for Rust's intermediate representation.

It can detect several forms of undefined behavior when executing supported Rust programs.

These include certain:

  • Use-after-free errors.
  • Out-of-bounds accesses.
  • Invalid pointer operations.
  • Aliasing violations.
  • Other undefined behaviors.

Install Miri

Miri is typically used with a nightly Rust toolchain.

rustup toolchain install nightly
rustup +nightly component add miri

Run:

cargo +nightly miri test

Miri executes supported test paths and checks for undefined behavior.

This is particularly valuable for crates containing unsafe code.

However, Miri has limitations.

It does not explore every possible execution path, and some operating-system interactions or FFI operations may not be supported.

Passing Miri tests does not prove that an unsafe implementation is sound.

For FFI-heavy applications, consider complementary testing with AddressSanitizer and ThreadSanitizer where supported.

5. Use Fuzz Testing for Untrusted Input

Fuzz testing repeatedly executes code using generated or mutated inputs.

It is particularly useful for software that processes data from untrusted sources.

Examples include:

  • File parsers.
  • Network protocols.
  • Serialization and deserialization.
  • Binary formats.
  • Command-line input processing.
  • FFI wrappers.
  • Security-sensitive data structures.

Install cargo-fuzz

cargo install cargo-fuzz --locked

Initialize fuzzing in a project:

cargo fuzz init

This creates a fuzzing setup that can be extended with application-specific targets.

For example, suppose our application parses a custom input format.

A fuzz target might look like:

#![no_main]

use libfuzzer_sys::fuzz_target;

fuzz_target!(|data: &[u8]| {
    let _ = my_crate::parse_input(data);
});

Here, parse_input() represents a function in our application that accepts arbitrary bytes.

The fuzzing engine generates different inputs and repeatedly calls the function.

The goal is to discover unexpected panics, hangs, crashes, and other failures.

Run the target using:

cargo +nightly fuzz run fuzz_target_1

This assumes the target is named fuzz_target_1 and the required nightly toolchain and fuzzing dependencies are installed.

What fuzzing cannot guarantee

Fuzzing does not prove the absence of vulnerabilities.

Its effectiveness depends on target design, input coverage, execution time, and the properties being tested.

A parser may survive millions of generated inputs and still contain a vulnerability in an untested path.

For production projects, preserve crash-triggering inputs as regression tests.

6. Add Property-Based and Concurrency Testing

Traditional unit tests check specific inputs and expected outputs.

Property-based testing checks whether general rules hold across many generated inputs.

For example, consider a function that sorts a list of numbers.

A useful property is that the resulting list must always be sorted.

Another property is that sorting must preserve the original elements and their counts.

Crates such as proptest and quickcheck can help generate inputs for these tests.

For concurrent Rust applications, consider tools such as loom.

loom can explore possible thread interleavings in suitably modeled concurrent code.

This helps identify concurrency bugs that may rarely occur during normal testing.

However, neither property-based testing nor concurrency testing replaces careful design and code review.

7. Protect Against Application-Level Vulnerabilities

Even a completely memory-safe Rust application can contain serious security vulnerabilities.

Let's look at several practical controls.

Use constant-time comparisons for secrets

Ordinary equality operations are not guaranteed to be constant-time.

For security-sensitive values such as message authentication codes or secret tokens, use established constant-time comparison primitives.

The subtle crate provides ConstantTimeEq.

For example:

use subtle::ConstantTimeEq;

fn verify_token(
    provided: &[u8; 32],
    expected: &[u8; 32],
) -> bool {
    bool::from(provided.ct_eq(expected))
}

This example assumes both values are fixed-length 32-byte arrays.

It does not solve token generation, expiration, storage, replay prevention, or authentication design.

Prefer vetted cryptographic libraries and protocols rather than building custom authentication mechanisms.

For passwords, use established password-hashing algorithms such as Argon2 rather than direct equality checks against stored plaintext or unsalted hashes.

Enforce resource limits

Applications processing untrusted input should define explicit limits.

Examples include:

  • Maximum request body size.
  • Maximum file upload size.
  • Maximum collection length.
  • Maximum parsing depth.
  • Request timeouts.
  • Connection limits.
  • Memory allocation limits.

These controls help reduce denial-of-service risks.

For example, a network service should not blindly trust a client-supplied Content-Length value when allocating memory.

Limits should be enforced at appropriate layers, including reverse proxies, application frameworks, and parsing logic.

Handle integer overflow deliberately

Rust provides several arithmetic methods.

For example:

fn calculate_total(
    price: u32,
    quantity: u32,
) -> Result<u32, &'static str> {
    price
        .checked_mul(quantity)
        .ok_or("Total amount overflow")
}

Here, checked_mul() returns None if multiplication overflows.

The function converts that condition into an error.

Other methods include:

  • saturating_* for arithmetic that clamps to numeric bounds.
  • wrapping_* for deliberate modular arithmetic.
  • overflowing_* for obtaining the result and an overflow indicator.

Choose the behavior that matches the application's requirements.

For financial applications, also consider whether integer units, decimal representations, and rounding rules are appropriate.

Avoid uncontrolled panics

A panic does not necessarily terminate an entire service.

Depending on the panic strategy and execution environment, it may unwind a thread, be caught at an appropriate boundary, or abort the process.

However, unexpected panics can still affect availability.

Avoid using unwrap() or expect() on untrusted input unless the required invariant has already been established.

Prefer explicit error handling using Result and Option.

Prevent injection vulnerabilities

Rust does not automatically prevent SQL injection, cross-site scripting, or SSRF.

For database access, use parameterized queries through established libraries such as sqlx or Diesel.

For web applications, apply output encoding appropriate to the rendering context.

For outbound requests, validate destinations, restrict network access where appropriate, and account for redirects and DNS resolution behavior.

Security controls must reflect the application's actual threat model.

8. Generate a Software Bill of Materials

A Software Bill of Materials, or SBOM, provides an inventory of software components and dependencies.

This is useful when teams need to determine whether an application is affected by a newly disclosed vulnerability.

For Rust projects, tools such as cargo-cyclonedx can generate SBOMs.

Install:

cargo install cargo-cyclonedx --locked

Generate a CycloneDX SBOM using the options supported by the installed version:

cargo cyclonedx

The resulting artifact can be stored alongside build outputs.

For production use, verify the generated format, dependency coverage, and metadata.

An SBOM does not prove that an application is secure.

It provides visibility that supports vulnerability management, compliance, and incident response.

9. Integrate Security Checks into CI/CD

Running security tools manually is useful during development.

But repeatability becomes important when applications are maintained by teams or released frequently.

A basic Rust CI pipeline can run formatting, compilation, linting, tests, and dependency checks.

Baseline pipeline

# Validate formatting
cargo fmt --all -- --check

# Check compilation
cargo check --workspace --all-targets --locked

# Run Clippy
cargo clippy --workspace --all-targets -- -D warnings

# Execute tests
cargo test --workspace --locked

# Scan known dependency advisories
cargo audit

# Enforce dependency policies
cargo deny check

This assumes the required tools are installed and configured.

For applications using optional features, add feature-specific checks or --all-features where compatible.

Separate fast checks from deeper security testing

Not every security check needs to run on every pull request.

A practical approach is to organize checks by execution cost and risk.

StageSuggested checksFrequency
Developer workstationFormat, Clippy, unit testsDuring development
Pull requestBuild, tests, dependency advisories, policy checksEvery PR
Scheduled security pipelineMiri, fuzzing, deeper dependency reviewNightly or weekly
Release pipelineSBOM, artifact integrity, vulnerability gatesEvery release
Production operationsAdvisory monitoring, vulnerability response, dependency updatesContinuous or scheduled

This approach keeps developer feedback fast while ensuring deeper security checks are not forgotten.

Protect the build environment

Remember that Rust build scripts and procedural macros can execute code during compilation.

Therefore, the CI environment itself must be secured.

Recommended practices include:

  • Use least-privilege CI permissions.
  • Avoid exposing production credentials to pull-request builds.
  • Use short-lived credentials where possible.
  • Restrict access to protected release environments.
  • Review third-party CI actions and build dependencies.
  • Preserve build logs and security reports.
  • Apply artifact signing and provenance controls where appropriate.

Security checks are only useful if the environment executing them can be trusted.

10. A Practical Rust Security Checklist

Use this checklist when preparing a Rust application for production.

Dependencies and supply chain

  • Commit Cargo.lock for executable applications.
  • Use --locked in CI.
  • Run RustSec advisory checks.
  • Enforce dependency license and source policies.
  • Review new crates before adoption.
  • Examine build scripts and procedural macros.
  • Generate an SBOM for release artifacts.

Source code

  • Run Clippy and compiler warnings.
  • Restrict unsafe code where possible.
  • Document unsafe-code invariants.
  • Review manually implemented Send and Sync traits.
  • Validate external FFI contracts.
  • Use explicit error handling for untrusted input.

Testing

  • Maintain unit and integration tests.
  • Fuzz input parsers and other exposed interfaces.
  • Use Miri for applicable unsafe-code tests.
  • Apply sanitizers where supported.
  • Test concurrency-sensitive components.
  • Preserve regression tests for discovered failures.

Application security

  • Validate authentication and authorization.
  • Apply input and resource limits.
  • Handle arithmetic overflow deliberately.
  • Use established cryptographic libraries.
  • Prevent injection and SSRF.
  • Avoid uncontrolled panics.
  • Protect secrets and sensitive data.

CI/CD and operations

  • Run security checks automatically.
  • Apply least privilege to CI jobs.
  • Protect release credentials.
  • Track dependency advisories after deployment.
  • Maintain vulnerability remediation procedures.
  • Preserve security evidence and release artifacts.

Not every project requires the same level of assurance.

A small local CLI utility and a network-facing service handling sensitive financial information have different threat models.

The checklist should be adapted to the system's exposure, criticality, and operational requirements.

Conclusion

Rust gives developers a strong foundation for building memory-safe software.

However, secure software delivery requires more than language-level guarantees.

We still need to understand our dependencies, review unsafe-code boundaries, test application behavior, protect build pipelines, and monitor vulnerabilities after release.

Tools such as Clippy, cargo-audit, cargo-deny, Miri, cargo-fuzz, and SBOM generators help automate parts of this process.

But tools alone do not establish security.

They need to be integrated into a repeatable software development lifecycle, supported by code review, architecture decisions, testing, and operational practices.

For teams adopting Rust, the practical goal should be to use the language's safety guarantees while continuing to apply the engineering discipline required for production software.

Rust helps prevent certain classes of vulnerabilities by design. Secure software delivery ensures the remaining risks are identified, managed, and continuously reviewed.

Key Takeaways

  • Rust's memory-safety guarantees do not replace application and supply-chain security.
  • Use cargo-audit and cargo-deny to monitor known advisories and enforce dependency policies.
  • Treat build scripts and procedural macros as executable supply-chain dependencies.
  • Use Clippy and compiler lints to identify suspicious coding patterns.
  • Minimize unsafe code, document its safety contracts, and test it with Miri and appropriate sanitizers.
  • Use fuzzing and property-based testing to explore unexpected inputs.
  • Apply secure application practices for authentication, authorization, input handling, resource limits, and cryptography.
  • Generate SBOMs and integrate security checks into CI/CD.
  • Continue vulnerability monitoring and remediation after release.

References

  1. The Cargo Book
  2. RustSec Advisory Database
  3. cargo-audit
  4. cargo-deny
  5. cargo-vet
  6. Clippy Documentation
  7. Miri
  8. Rust Fuzz Book
  9. Rustonomicon
  10. CycloneDX Rust Plugin

Public profile lookup

Ask AI About the Author

Open this query in ChatGPT, Claude, or Perplexity.

Comments

Comments are open to confirmed email subscribers. Use the email you subscribed with. To edit a comment, delete it and post a new one.

0/2000
Verify:

    Subscribe to get the new blogs.

    Field notes from someone who ships before they write about it. Sovereign AI, AI-SDLC, DevOps, and what 59 production deployments teach you. No spam. Unsubscribe anytime.

    More in this series

    1. Part 1
      Rust Series Part 1: Getting Started with Rust — Immutability and Type Safety
    2. Part 2
      Rust Series Part 2: Is Rust Really Safer? What the Data Says
    3. Part 3
      Rust Series Part 3: Rust Is Not Immune — Real Security Risks in Rust Code

    Related field notes