Answer#
Cargo.toml says which versions are acceptable (serde_json = "1" means any 1.x). Cargo.lock records the exact versions that were chosen. Without a committed lock file, two builds of the same commit can use different dependency versions, and the one you audited is not the one you shipped.
The Cargo Book recommends committing Cargo.lock for executables and services. Libraries have traditionally left it out because their users resolve their own versions.
--locked makes cargo use the lock file as it is and fail if it would need changes:
cargo build --lockedOn a small test project with two dependencies (regex and serde_json) this build succeeded from its lock file. cargo tree then shows the full tree that the lock file pins, including crates you never named:
demo v0.1.0
├── regex v1.13.1
│ ├── aho-corasick v1.1.5
│ │ └── memchr v2.8.3
│ ├── memchr v2.8.3
│ ├── regex-automata v0.4.19
│ │ ├── aho-corasick v1.1.5 (*)
│ │ ├── memchr v2.8.3
│ │ └── regex-syntax v0.8.12
│ └── regex-syntax v0.8.12
└── serde_json v1.0.154
├── itoa v1.0.19
├── memchr v2.8.3
├── serde_core v1.0.229
└── zmij v1.0.23How to do it#
- Commit
Cargo.lockfor every application. - Build in CI and for releases with
cargo build --release --locked. - Update on purpose:
cargo updatefor everything, orcargo update -p serde_jsonfor one crate. Read the diff ofCargo.lockin the pull request. - Run
cargo auditorcargo denyagainst the lock file (see those threads). cargo tree -dlists crates that appear in several versions,cargo tree -i <crate>shows why a crate is in the tree.
Common mistakes#
- Ignoring
.gitignoretemplates that excludeCargo.lock, for a project that is an application. - Running
cargo updateright before a release without testing. - Using version requirements such as
*; cargo-deny'swildcardssetting can forbid them.
Related questions#
Does --locked check what the crates contain?#
No. It fixes the versions, which makes builds repeatable. The checksums in the lock file make cargo detect a registry package that differs from the one that was locked, but they do not say that the package is trustworthy. For that, review dependencies (see the thread on reviewing a new dependency).
Should libraries commit Cargo.lock?#
It is not required for libraries, and consumers ignore it. Some projects commit it anyway to make their own CI repeatable.
Sources#
- The Cargo Book, "Cargo.toml vs Cargo.lock": https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
- The Cargo Book,
cargo build --locked: https://doc.rust-lang.org/cargo/commands/cargo-build.html - The Cargo Book,
cargo tree: https://doc.rust-lang.org/cargo/commands/cargo-tree.html