Skip to content

Commit

Permalink
Add an optional sha256 parameter to builtins.fetchGit
Browse files Browse the repository at this point in the history
This is particularly useful to ensure the purity e.g. of a repo which is
pinned to a git tag (tags can be force-pushed which makes builds
silently irreproducible) or when trying to evaluate a nix expression without internet
connectivity (if the cache-entry is expired, the eval will break as the
git repo can't be re-fetched).

This change adds an optional `sha256` parameter to the builtin
`fetchGit` and checks if there's a fixed-output derivation which matches
the hash (the hash can be determined using `nix-prefetch-git`).

If no such fixed-output derivation exists, it will be attempted to fetch
the Git repository in order to compare the sha256 hashes. Please note
that caching is still used here, so if the repo is already fetched and
the only sha256 in the expression changes, the evaluation will fail pretty
fast.
  • Loading branch information
Ma27 committed Nov 9, 2019
1 parent d1db7fa commit 0872bb5
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 14 deletions.
31 changes: 31 additions & 0 deletions doc/manual/expressions/builtins.xml
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,15 @@ stdenv.mkDerivation { … }
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>sha256</term>
<listitem>
<para>
The sha256 hash of the output. Please note that this can only
be used in conjunction with <varname>rev</varname> or <varname>ref</varname>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>ref</term>
<listitem>
Expand Down Expand Up @@ -504,6 +513,28 @@ stdenv.mkDerivation { … }
<programlisting>builtins.fetchGit {
url = "ssh://git@github.com/nixos/nix.git";
ref = "master";
}</programlisting>
</example>

<example>
<title>Fetching a given revision from a repo and validate its sha256</title>
<para>
<function>builtins.fetchGit</function> can create a fixed-output
derivation to ensure that the content doesn't change.
</para>
<programlisting>builtins.fetchGit {
url = "git://github.com/NixOS/nix";
rev = "a08f35392256b1ef23947857e41a9b12b1591245";
sha256 = "0rvb78lrxr9841z045fidk3lxsqn20505n5xgzya28xwbk7543l6";
}</programlisting>
</example>

<example>
<title>Fetching a given tag from a repo and validate its sha256</title>
<programlisting>builtins.fetchGit {
url = "git://github.com/NixOS/nix";
ref = "refs/tags/2.2.2";
sha256 = "15scrql151nhjh00lfxhy07nfc5x00qrbkfm24scpw5882flqrf0";
}</programlisting>
</example>
</listitem>
Expand Down
59 changes: 45 additions & 14 deletions src/libexpr/primops/fetchGit.cc
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,28 @@ std::regex revRegex("^[0-9a-fA-F]{40}$");

GitInfo exportGit(ref<Store> store, const std::string & uri,
std::optional<std::string> ref, std::string rev,
const std::string & name)
const std::string & name, std::optional<Hash> sha256)
{
if (evalSettings.pureEval && rev == "")
throw Error("in pure evaluation mode, 'fetchGit' requires a Git revision");

Path expectedStorePath;
GitInfo gitInfo;
if (sha256) {
// Disallow `sha256` usage if no rev/ref is given.
if (rev == "" && !ref) {
throw Error("Cannot create a fixed-output derivation for a git repo without a git revision or ref");
}

expectedStorePath = store->makeFixedOutputPath(true, *sha256, name);
if (store->isValidPath(expectedStorePath)) {
gitInfo.storePath = expectedStorePath;
gitInfo.rev = rev;
gitInfo.shortRev = std::string(gitInfo.rev, 0, 7);
return gitInfo;
}
}

if (!ref && rev == "" && hasPrefix(uri, "/") && pathExists(uri + "/.git")) {

bool clean = true;
Expand Down Expand Up @@ -138,7 +155,6 @@ GitInfo exportGit(ref<Store> store, const std::string & uri,
}

// FIXME: check whether rev is an ancestor of ref.
GitInfo gitInfo;
gitInfo.rev = rev != "" ? rev : chomp(readFile(localRefFile));
gitInfo.shortRev = std::string(gitInfo.rev, 0, 7);

Expand All @@ -148,20 +164,25 @@ GitInfo exportGit(ref<Store> store, const std::string & uri,
Path storeLink = cacheDir + "/" + storeLinkName + ".link";
PathLocks storeLinkLock({storeLink}, fmt("waiting for lock on '%1%'...", storeLink)); // FIXME: broken

try {
auto json = nlohmann::json::parse(readFile(storeLink));
// Only return cached git repo if no sha256 is set. If a sha256 exists,
// the proper store path would've been returned earlier, otherwise the hash
// needs to be validated.
if (!sha256) {
try {
auto json = nlohmann::json::parse(readFile(storeLink));

assert(json["name"] == name && json["rev"] == gitInfo.rev);
assert(json["name"] == name && json["rev"] == gitInfo.rev);

gitInfo.storePath = json["storePath"];
gitInfo.storePath = json["storePath"];

if (store->isValidPath(gitInfo.storePath)) {
gitInfo.revCount = json["revCount"];
return gitInfo;
}
if (store->isValidPath(gitInfo.storePath)) {
gitInfo.revCount = json["revCount"];
return gitInfo;
}

} catch (SysError & e) {
if (e.errNo != ENOENT) throw;
} catch (SysError & e) {
if (e.errNo != ENOENT) throw;
}
}

// FIXME: should pipe this, or find some better way to extract a
Expand All @@ -173,7 +194,14 @@ GitInfo exportGit(ref<Store> store, const std::string & uri,

runProgram("tar", true, { "x", "-C", tmpDir }, tar);

gitInfo.storePath = store->addToStore(name, tmpDir);
auto storePath = store->addToStore(name, tmpDir);
if (expectedStorePath != "" && storePath != expectedStorePath) {
unsigned int status = resUntrustedPath;
Hash got = hashPath(sha256->type, store->toRealPath(storePath)).first;
throw Error(status, "hash mismatch in git repo (%s, rev %s):\n wanted: %s\n got: %s", uri, gitInfo.rev, sha256->to_string(), got.to_string());
}

gitInfo.storePath = storePath;

gitInfo.revCount = std::stoull(runProgram("git", true, { "-C", cacheDir, "rev-list", "--count", gitInfo.rev }));

Expand All @@ -194,6 +222,7 @@ static void prim_fetchGit(EvalState & state, const Pos & pos, Value * * args, Va
std::string url;
std::optional<std::string> ref;
std::string rev;
std::optional<Hash> sha256;
std::string name = "source";
PathSet context;

Expand All @@ -213,6 +242,8 @@ static void prim_fetchGit(EvalState & state, const Pos & pos, Value * * args, Va
rev = state.forceStringNoCtx(*attr.value, *attr.pos);
else if (n == "name")
name = state.forceStringNoCtx(*attr.value, *attr.pos);
else if (n == "sha256")
sha256 = Hash(state.forceStringNoCtx(*attr.value, *attr.pos), htSHA256);
else
throw EvalError("unsupported argument '%s' to 'fetchGit', at %s", attr.name, *attr.pos);
}
Expand All @@ -227,7 +258,7 @@ static void prim_fetchGit(EvalState & state, const Pos & pos, Value * * args, Va
// whitelist. Ah well.
state.checkURI(url);

auto gitInfo = exportGit(state.store, url, ref, rev, name);
auto gitInfo = exportGit(state.store, url, ref, rev, name, sha256);

state.mkAttrs(v, 8);
mkString(*state.allocAttr(v, state.sOutPath), gitInfo.storePath, PathSet({gitInfo.storePath}));
Expand Down
6 changes: 6 additions & 0 deletions tests/fetchGit.sh
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,12 @@ path3=$(nix eval --raw "(builtins.fetchGit { url = $repo; ref = \"master\"; }).o
path3=$(nix eval --raw "(builtins.fetchGit { url = $repo; rev = \"$rev2\"; }).outPath")
[[ $path = $path3 ]]

path4=$(nix eval --raw "(builtins.fetchGit { url = $repo; rev = \"$rev2\"; sha256 = \"0vycvr96zr194n9zw6pwlvfvyclyaznpmg3xm7qvsdc01bl21gqy\"; }).outPath")
[[ $path = $path4 ]]

nix eval --raw "(builtins.fetchGit { url = $repo; rev = \"$rev2\"; sha256 = \"0000000000000000000000000000000000000000000000000000\"; }).outPath" || status=$?
[[ "$status" = "102" ]]

# Committing should not affect the store path.
git -C $repo commit -m 'Bla3' -a

Expand Down

0 comments on commit 0872bb5

Please sign in to comment.