reproducible cargo locks
Files
README.md

nix2cargo #

nix2cargo wraps cargo to read a local pinned copy of the crates.io index. This allows generating & updating Cargo.lock reproducibly and without network access, for instance inside the Nix sandbox. This works on the observation that Cargo.lock can be seen as a pure function of the project manifests and the index revision.

Instructions #

1. Import this repository #

For instance with npins:

npins add git https://tangled.org/pnm.tf/nix2cargo --branch main

2. Add nix2cargo to your shell #

Pass the path to your project's nix2cargo.lock. The file does not need to exist yet:

# shell.nix
let
  sources = import ./npins;
  pkgs = import sources.nixpkgs { };
  nix2cargo = pkgs.callPackage "${sources.nix2cargo}" { lockfile = ./nix2cargo.lock; };
in
pkgs.mkShell {
  # nix2cargo provides `cargo`: don't also add `pkgs.cargo`
  packages = [ nix2cargo ];
}

This provides two commands: nix2cargo, and a cargo wrapper.

3. Pin the index #

nix2cargo lock # writes ./nix2cargo.lock

This downloads the whole index (a few hundred MB) so it can take a while. Reload your shell once this is done. You can also add watch_file nix2cargo.lock to .envrc if you use direnv.

4. Use cargo as usual #

cargo generate-lockfile

To move to a new version of the index, run nix2cargo lock again and then cargo update.

Example #

You can keep Cargo.lock committed for other tools (it's still compatible with an unwrapped cargo) and check that it matches what nix2cargo produces:

{ stdenvNoCC, nix2cargo }:
stdenvNoCC.mkDerivation {
  name = "Cargo.lock";
  # make sure to not include Cargo.lock
  src = builtins.filterSource (path: type: !builtins.elem (baseNameOf path) [ "Cargo.lock" "target" ]) ./.;
  nativeBuildInputs = [ nix2cargo ];
  buildPhase = ''
    CARGO_HOME=$(pwd) cargo generate-lockfile
    diff ${./Cargo.lock} Cargo.lock
  '';
  installPhase = "touch $out";
}

How it works #

nix2cargo introduces a lockfile (nix2cargo.lock) that pins a revision of the crates.io index. This copy is served by a local server implementing the sparse protocol. cargo is then wrapped to point to that registry instead of https://index.crates.io/. The exact invocation looks like this:

cargo \
	--config source.crates-io.replace-with='nix2cargo' \
	--config source.nix2cargo.registry='sparse+http://<revision>.nix2cargo.invalid/' \
	--config http.proxy='http://127.0.0.1:<port>/' \
	"$@"

Limitations #

nix2cargo will not interact cleanly with setups that use the cargo settings it relies on to work. For instance, nix2cargo doesn't support going through a real proxy. If this becomes a problem, you can probably still use nix2cargo to modify the lockfile, and an unwrapped cargo for other operations.