TExcelTAD
Home › Software Supply Chain Security: SBOM, SLSA & Sigstore › Pinning by Hash: npm, pip, Go & Cargo

Pinning by Hash: npm, pip, Go & Cargo

A version number is a name; the registry decides what bytes it means. A hash is the bytes. Pinning dependencies by hash makes every install check that it received exactly what was reviewed when the lockfile was written, whatever happens to the registry, a mirror or the network in between. Most ecosystems now do this by default in their lockfiles; the gaps are in the tools that don't, and in the habits that bypass them.

Ecosystem Where hashes live Checked by Course lesson
npm integrity (SRI, usually sha512-…) in package-lock.json npm ci / npm install, always package-lock.json
pnpm / Yarn integrity / checksum in pnpm-lock.yaml / yarn.lock every install JS field notes
pip --hash=sha256:… in requirements.txt pip install --require-hashes (automatic once any hash is present) requirements.txt
uv / Poetry hashes in uv.lock / poetry.lock uv sync, poetry install Pinning & Lockfiles
Go go.sum (h1: hashes of module zips and go.mod files) + the checksum database every go command go.sum
Cargo checksum in Cargo.lock every build Cargo.lock
Maven / Gradle not by default; Gradle dependency verification (gradle/verification-metadata.xml) Gradle when the file exists Maven & Gradle
NuGet contentHash in packages.lock.json dotnet restore --locked-mode Lock Files
Container images @sha256: digests the registry client Tags vs Digests

npm's integrity strings

An SRI (Subresource Integrity) string is <algorithm>-<base64 of the digest>. The lockfile in the sample project records one for each tarball:

bash · try it yourself
jq -r '.packages | to_entries[] | select(.value.integrity) | "\(.key | sub("node_modules/"; ""))  \(.value.integrity[0:40])…"' /opt/samples/node-app/package-lock.json
mkdir pkg && cd pkg
printf 'pretend this is lodash-4.17.15.tgz\n' > lodash-4.17.15.tgz
sri() { echo "sha512-$(openssl dgst -sha512 -binary "$1" | base64 -w0)"; }
expected=$(sri lodash-4.17.15.tgz)
echo "recorded: ${expected:0:40}…"
printf 'pretend this is lodash-4.17.15.tgz, with a backdoor\n' > lodash-4.17.15.tgz
actual=$(sri lodash-4.17.15.tgz)
[ "$actual" = "$expected" ] && echo "integrity ok" || echo "EINTEGRITY: sha512 mismatch, refusing to install"
lodash  sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE…
minimist  sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNm…
recorded: sha512-mteQD8fkkER0eoqiHPB9lZSE9RkPLfifF…
EINTEGRITY: sha512 mismatch, refusing to install

That's the check npm ci performs for every package before unpacking it. The failure is loud and unambiguous, which is what you want from a supply-chain control.

pip: --require-hashes

pip only checks hashes when the requirements file contains them, and then insists on them for every requirement, including transitive ones; a single unhashed line fails the install. Generate the file rather than writing it:

text
# requirements.txt, generated by:  uv pip compile requirements.in --generate-hashes
#                              or:  pip-compile --generate-hashes requirements.in
requests==2.32.4 \
    --hash=sha256:<64 hex digits of the wheel> \
    --hash=sha256:…
certifi==2026.10.23 \
    --hash=sha256:…
bash
pip install --require-hashes -r requirements.txt     # hashes are also enforced without the flag once present

Each package may list several hashes (one per wheel or sdist it may download). A mismatch prints THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE and installs nothing.

A model: what a hash-checking installer enforces

python · try it yourself
import hashlib

def sha256(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()

downloads = {   # what the index served today
    "requests-2.32.4-py3-none-any.whl": b"requests wheel bytes",
    "urllib3-2.8.0-py3-none-any.whl": b"urllib3 wheel bytes (replaced on a mirror)",
    "certifi-2026.10.23-py3-none-any.whl": b"certifi wheel bytes",
}
lock = {        # what the lockfile recorded when it was reviewed
    "requests-2.32.4-py3-none-any.whl": [sha256(b"requests wheel bytes")],
    "urllib3-2.8.0-py3-none-any.whl": [sha256(b"urllib3 wheel bytes")],
    "certifi-2026.10.23-py3-none-any.whl": [],   # someone added it by hand, without a hash
}

def install(lock, downloads, require_hashes=True):
    errors = []
    for name, data in downloads.items():
        allowed = lock.get(name, [])
        if require_hashes and not allowed:
            errors.append(f"{name}: no hash pinned (all requirements need one in hash-checking mode)")
        elif allowed and sha256(data) not in allowed:
            errors.append(f"{name}: expected {allowed[0][:12]}…, got {sha256(data)[:12]}…")
    return errors

problems = install(lock, downloads)
print("install refused:" if problems else "installed")
for p in problems:
    print("  " + p)
install refused:
  urllib3-2.8.0-py3-none-any.whl: expected e571080c4597…, got 9a7750bc3db1…
  certifi-2026.10.23-py3-none-any.whl: no hash pinned (all requirements need one in hash-checking mode)

Both kinds of failure matter: the swapped wheel is the attack, the missing hash is the hole in the policy. Installers refuse both, which is why hand-editing hashed requirement files doesn't work.

Go and Cargo

Go's go.sum stores two hashes per module version (h1: = SHA-256 over a sorted list of file hashes): one for the zip, one for go.mod. On first download the go command also checks them against the public checksum database (sum.golang.org), a transparency log, so even the first download of a module version is verified against what everyone else got:

bash · try it yourself
cat /opt/samples/go-app/go.sum
golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=

Cargo records the SHA-256 of each .crate file in Cargo.lock (checksum = "…") and verifies it on every fetch; crates.io itself is immutable (a version can be yanked but never replaced).

What pinning by hash doesn't do

  • It doesn't choose well: a hash of a malicious package is still a valid pin (Typosquatting).
  • It doesn't update: pins need a bot and review (next lesson).
  • It doesn't cover what the lockfile doesn't see: curl | sh in a Dockerfile, a tool downloaded in CI, a GitHub Action referenced by tag. Those need their own hash or digest pins (echo "<sha256> tool.tgz" | sha256sum -c -, uses: …@<sha>, FROM …@sha256:).
  • In CI, use the commands that refuse to change the lockfile: npm ci, pnpm install --frozen-lockfile, yarn install --immutable, uv sync --locked, poetry install with poetry check --lock, cargo build --locked, go build (with the default -mod=readonly), dotnet restore --locked-mode.

Test yourself

What happens when a pip requirements file has hashes for some requirements but not others?

  1. pip checks only the hashed ones
  2. pip fails: in hash-checking mode every requirement needs a hash
  3. pip ignores all hashes
  4. pip downloads the hashes automatically

What does Go's checksum database add beyond go.sum?

  1. Faster downloads
  2. Verification of a module version's hash on its first download against a public transparency log
  3. Vulnerability data
  4. Version selection

Which npm command is right for CI because it installs exactly the lockfile and fails if package.json and the lockfile disagree?

  1. npm install
  2. npm ci
  3. npm update
  4. npm audit fix