RamG
RamG

Reputation: 89

How to ensure my dependencies use Safe Rust?

Is there a way to declare in the Cargo.toml that my project depend only on 3rd-party crates that guaranteed to be using Safe Rust transitively?

I am new to Rust and Rust is new to me. I haven't had a chance to try anything out yet.

Upvotes: 6

Views: 640

Answers (1)

Péter Szilvási
Péter Szilvási

Reputation: 2009

Analyzing Dependencies

First, check the crates.io documentation whenever the author(s) mention the usage of unsafe code. You can double-check it by searching for the unsafe keyword in the source code.

However, inspecting the crate's and its dependencies' source code is a tedious job. The tool called cargo-geiger provide statistics about unsafe usage in the crate and all its dependencies. After installing it, navigate to your Cargo.toml file and analyze it:

cargo geiger

It will download and scans all dependencies, then assigns one of the three symbols to a crate:

Symbols: 
    🔒  = No `unsafe` usage found, declares #![forbid(unsafe_code)]
    ❓  = No `unsafe` usage found, missing #![forbid(unsafe_code)]
    ☢️   = `unsafe` usage found

Note that it provides only the usage of unsafe keyword. But for more thorough analysis, review the code with cargo-crev to verify the trustworthiness and the security vulnerabilities of package dependencies. Additionally, if you found an unsafe code, you can report to the safety-dance repository.

Analyzing Project

Once you checked your dependencies, it is time to assess your project as well. For start, catch common mistakes using the clippy linter tool:

cargo clippy

Moreover, add the #![forbid(unsafe_code)] attribute to your files to communicate that unsafe code blocks are forbidden. I don't know if you can declare that your package (is guaranteed) to use safe Rust. But you can show a badge in the README.md file after eliminating all unsafe code:

[![unsafe forbidden](https://img.shields.io/badge/unsafe-forbidden-success.svg)](https://github.com/rust-secure-code/safety-dance/)

It will help others to discover that your crate is safe.

Note that there is no 100% memory safety in Rust because the standard libraries use (with great caution) unsafe blocks. Sometimes it is unavoidable. In any case, you should always try to implement safe code, even if you lose a little performance gain.

Less bug, less maintenance pain, more tRust.

Further readings:

Upvotes: 9

Related Questions