TRENDING
Three Japanese emergency triage tags fanned out on a dark wooden table, with black, red, yellow and green priority bands along the bottom edge of the center tag
December 1, 2026
How to Triage Vulnerabilities in Python With CVSS, EPSS, and CISA KEV: Build a Decision Engine, Replay It on 71 Real KEV Additions, and See What Each Signal Missed
Three goats standing on top of a rusty steam locomotive boiler like winners on a podium, inside a roofed shed in Don Khon, Laos
December 1, 2026
The Register Gives China Mobile Credit for the “Most Capable” All-Domestic Open-Weight Model, but It Is China Telecom’s Xing4.1-Preview, Its Report Has No Capability Scores, the 4.68x Is a Simulation, and the Model Card’s Own Table Has It First or Tied for First on 2 of 18 Rows
A glass sugar dispenser with a steel lid beside a salt shaker and a pepper shaker with brass caps on a diner table
December 1, 2026
easyDNS Says Customer Records, Stored AWS Keys and Unsalted Mailbox Password Hashes Were Exposed, but the Public Notice Gives No Counts, the Entry Point Appears Only in the CEO’s Comments to a Reporter, and It Is the Second Security Incident Its Blog Has Posted This Year
Brass combination lock with three number wheels and a hinged latch on a black case
December 1, 2026
How to Lock Python Dependencies With Hashes So pip Refuses a Swapped File: Run a Tamper Test, Read pip’s Hash Errors, Build a Lock That Works on Windows and Linux, and Lint It in CI
A pair of unfinished pale wooden clogs, called sabots, on a clogmaker's workbench among wood shavings and hand tools.
December 1, 2026
Anthropic Denies Claude Is Trained to Sabotage Work, and Its Documents Fit the Denial but Show a Silent Safeguard Retired After About Two Days in June, a Training Cap on Kernel and LLM-Architecture Skills With No Released-Model Score, and Viral Evidence That Cannot Tell Them Apart
01 Dec 2026
SXZ.io SXZ.io
  • Home
Search the Site
Popular Searches:
Technology Amazon AI
Recent Posts
A bicycle chain with a missing link lying on an open palm beside the loose pin and clip that should have joined it
How to Fix SSL CERTIFICATE_VERIFY_FAILED in Python Without Turning Verification Off: Read the Error Code, Find Who Has to Fix It, Trust Your Own CA, and Catch Broken Chains in CI
November 30, 2026
Pale church wall with an arched window filled with a star-pattern stone lattice screen
The Unpublished Lattice Paper Attributed to Anthropic Reached the Public as Two Title Hashes That Match One Guessable String, the Coverage Splits on What It Breaks Because the Title Names Quantum Algorithms, Not a Key Recovery, and 21 of 24 Sites We Tested Still Pair ML-KEM With X25519
November 30, 2026
A tall cardon cactus with many upright arms stands in front of a field of cardon cacti under a blue sky with white clouds in the Sonoran Desert
Cacti’s 4HTTP2SHELL Chain Drew 1,793 Attack Attempts on One Honeypot Sensor in Four Days, but the Fix Is Still Only Source Patches With No 1.2.32 Release or CVE ID, the Advisory Calls It “Authenticated,” and on Our Reading of the Code the Guest Route Hinges on One Setting That Ships as “No User”
November 30, 2026
SXZ.io SXZ.io
  • Home

Categories

Articles 325 Posts
News 331 Posts
Learning Hub 297 Posts
Home/Learning Hub/How to Lock Python Dependencies With Hashes So pip Refuses a Swapped File: Run a Tamper Test, Read pip’s Hash Errors, Build a Lock That Works on Windows and Linux, and Lint It in CI
Learning Hub

How to Lock Python Dependencies With Hashes So pip Refuses a Swapped File: Run a Tamper Test, Read pip’s Hash Errors, Build a Lock That Works on Windows and Linux, and Lint It in CI

A hands-on pip 26.3 lab: a local index swaps a wheel under a pinned name, plain pip installs it, and hash pinning makes pip refuse it. Then pip’s hash errors, a 180-hash lock for requests, the...

November 29, 2026 28 Min Read
16

Every pip install is an act of trust. You name a package and a version, pip asks an index for the file, and whatever bytes come back are unpacked into your environment and, soon after, run. In this tutorial you will watch that trust fail on purpose and then close the gap with hashes. A hash is a fingerprint of the exact file you reviewed, so pip can refuse any other file that turns up under the same name and version.

Table Of Content

  • The idea in plain words
  • Key terms
  • What a hash pin stops, and what it does not
  • Prerequisites
  • Step 1: Make the folder and build three tiny packages
  • Step 2: Start a package index and read its page
  • Step 3: Install normally and see what pip trusts
  • Step 4: Swap the file and watch pip install it
  • A page with a stale hash
  • A page that matches the swapped file
  • Step 5: Pin the hashes and see pip refuse the swap
  • How to read the error
  • What to do when it fires
  • Step 6: Learn pip’s other hash errors
  • A dependency you did not list
  • Pinned but without a hash
  • Turning the all-or-nothing rule off
  • A range with a hash
  • More than one hash for a requirement
  • Skipping dependencies
  • Hash algorithms
  • Version-control requirements
  • Step 7: Generate a real lock with pip-compile
  • Step 8: The lock that works on Windows and breaks on Linux
  • Step 9: A gap hash checking does not close, the build tools
  • Closing the gap
  • Option one: refuse source distributions
  • Option two: install the build tools yourself
  • Step 10: Check the file in CI before pip runs
  • Step 11: Keep the lock fresh without losing the seal
  • Check that everything works end to end
  • Common mistakes
  • Where to go next

You will build a tiny package index on your own machine and three throwaway packages. You will swap a file behind pip’s back and see a plain install run the swapped code, then see the same swap refused once the hashes are pinned. You will meet the error messages pip prints when a hashed install goes wrong, make a real hashed lock for requests with pip-compile (180 hashes), hit the trap that breaks a lock built on Windows when it runs on Linux, find a gap that hash checking does not close, and finish with an 86-line linter and 16 tests that check requirements files before pip runs. Everything below ran on Windows 11 with Python 3.13.14 and pip 26.3, and every transcript is copied from that run.

The idea in plain words

Key terms

  • Index: a web server that lists the files of each project. PyPI is the default one; a company mirror or a caching proxy is another.
  • Wheel and source distribution: a wheel (.whl) is a built package, a zip file that pip unpacks. A source distribution (sdist, .tar.gz) is source code that pip must build first.
  • Pin: naming one exact version with ==, for example requests==2.34.2.
  • Hash: here always a SHA-256 digest, 64 hexadecimal characters computed from every byte of a file. Change one byte and the digest is completely different.
  • Requirements file: a text file you give to pip install -r. A lock is a requirements file that pins every package, dependencies included, and carries hashes.

What a hash pin stops, and what it does not

pip’s documentation says hash-checking mode uses “local hashes, embedded in a requirements.txt file, to protect against remote tampering and network issues.” Its repeatable installs page adds that this “protects against a compromise of PyPI or the HTTPS certificate chain” and “guards against a package changing without its version number changing (on indexes that allow this).” The same page says that PyPI itself does not allow such a change: “PyPI does protect against this.” So the attacker a hash pin is built for sits between you and the file: a compromised mirror, a caching proxy, a private index with weak write access.

A hash does not tell you whether the file you pinned is good. If you lock a release that was already poisoned, the hash faithfully protects the poison. The incidents in our posts on the poisoned LiteLLM 1.107.0 and on Microsoft’s agent-framework were new versions published on PyPI, not an old file swapped under its old name. A lock written before the upload would never have fetched them; a lock refreshed during the window would have pinned them. Think of hashes as a tamper seal, not a safety inspection. The inspection side is covered in our tutorials on SBOMs and pip-audit, dependency cooldowns and a package-name gate; the newer lock format is in the pylock.toml tutorial.

Prerequisites

  • Python 3.13 and pip 26.3. Hash checking has existed since pip 8.0 (the docs say “Added in version 8.0”), but I ran everything on pip 26.3, and the --no-require-hashes flag in Step 6 needs pip 26.2 or newer.
  • A shell. The transcripts use Git Bash on Windows 11, so cp, cat, curl, head and ls appear as typed. On PowerShell use Copy-Item, Get-Content, curl.exe and Select-Object -First 14.
  • Internet access for Steps 7 to 9, which use the real PyPI. Steps 1 to 6 need only your own machine.
  • About 40 minutes, and no prior knowledge beyond running commands and making a virtual environment.

A line in square brackets such as [exit code 1] is not pip output. My lab runner adds it to show that pip reports the failure to scripts and CI through a non-zero exit code.

Step 1: Make the folder and build three tiny packages

Create a folder, a virtual environment and the tools this tutorial uses. The virtual environment keeps everything away from your real Python.

mkdir hashlab
cd hashlab
python -m venv .venv
source .venv/Scripts/activate
python -m pip install --upgrade pip
python -m pip install pip-tools packaging pytest

On macOS and Linux the activation line is source .venv/bin/activate; on PowerShell it is .venv\Scripts\Activate.ps1. Check the interpreter:

$ python -V
Python 3.13.14

The packages come from a script instead of PyPI for a reason: every byte is fixed (a fixed timestamp, fixed file modes, no random order), so the hashes are repeatable. Save this as mkwheel.py. It builds sxzlab-lib 2.0, sxzlab-app 1.0 (which depends on the library), an sdist called sxzlab-src that Step 9 needs, and a tampered twin of sxzlab-app that has the same file name and different code.

# mkwheel.py
"""Build the lab's tiny packages by hand so every byte, and every hash, is reproducible.

Usage: python mkwheel.py            (writes clean files into dist/ and a tampered copy into tampered/)
"""
import base64
import csv
import gzip
import hashlib
import io
import tarfile
import zipfile
from pathlib import Path

LIB = '''VERSION = "2.0"


def greet(who):
    return "hello from " + who
'''

APP = '''from sxzlab_lib import greet

VERSION = "1.0"


def hello():
    return greet("sxzlab_app " + VERSION)
'''

APP_TAMPERED = APP.replace(
    'VERSION = "1.0"\n',
    'VERSION = "1.0"\nprint("TAMPERED CODE RAN: a swapped file just executed on import")\n',
)

SRC = '''VERSION = "1.0"
'''

PYPROJECT = """[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"

[project]
name = "sxzlab-src"
version = "1.0"
"""


def b64(digest):
    return base64.urlsafe_b64encode(digest).rstrip(b"=").decode()


def build_wheel(outdir, name, version, body, requires=()):
    dist = name.replace("-", "_")
    info = f"{dist}-{version}.dist-info"
    metadata = f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n"
    metadata += "".join(f"Requires-Dist: {r}\n" for r in requires)
    files = {
        f"{dist}/__init__.py": body.encode(),
        f"{info}/METADATA": metadata.encode(),
        f"{info}/WHEEL": b"Wheel-Version: 1.0\nGenerator: mkwheel\nRoot-Is-Purelib: true\nTag: py3-none-any\n",
    }
    record = io.StringIO()
    writer = csv.writer(record, lineterminator="\n")
    for path, data in files.items():
        writer.writerow([path, "sha256=" + b64(hashlib.sha256(data).digest()), len(data)])
    writer.writerow([f"{info}/RECORD", "", ""])
    files[f"{info}/RECORD"] = record.getvalue().encode()
    out = Path(outdir) / f"{dist}-{version}-py3-none-any.whl"
    out.parent.mkdir(parents=True, exist_ok=True)
    with zipfile.ZipFile(out, "w") as z:
        for path, data in files.items():
            member = zipfile.ZipInfo(path, (2026, 11, 29, 0, 0, 0))
            member.create_system = 3
            member.external_attr = 0o644 << 16
            z.writestr(member, data)
    return out


def build_sdist(outdir):
    root = "sxzlab_src-1.0"
    files = {
        f"{root}/pyproject.toml": PYPROJECT.encode(),
        f"{root}/sxzlab_src/__init__.py": SRC.encode(),
        f"{root}/PKG-INFO": b"Metadata-Version: 2.1\nName: sxzlab-src\nVersion: 1.0\n",
    }
    raw = io.BytesIO()
    with tarfile.open(fileobj=raw, mode="w", format=tarfile.PAX_FORMAT) as tar:
        for path, data in files.items():
            member = tarfile.TarInfo(path)
            member.size, member.mtime, member.mode = len(data), 1796000000, 0o644
            tar.addfile(member, io.BytesIO(data))
    out = Path(outdir) / "sxzlab_src-1.0.tar.gz"
    with open(out, "wb") as handle:
        with gzip.GzipFile(fileobj=handle, mode="wb", mtime=0) as gz:
            gz.write(raw.getvalue())
    return out


def sha256_of(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


if __name__ == "__main__":
    built = [
        build_wheel("dist", "sxzlab-lib", "2.0", LIB),
        build_wheel("dist", "sxzlab-app", "1.0", APP, requires=["sxzlab-lib>=2"]),
        build_sdist("dist"),
        build_wheel("tampered", "sxzlab-app", "1.0", APP_TAMPERED, requires=["sxzlab-lib>=2"]),
    ]
    for path in built:
        print(f"{path.as_posix():45} {path.stat().st_size:5} bytes  sha256 {sha256_of(path)}")

The tampered module is harmless on purpose: it only prints a line when imported. That line stands in for whatever a real attacker would run.

$ python mkwheel.py
dist/sxzlab_lib-2.0-py3-none-any.whl           1037 bytes  sha256 3478432a21be9328701997214c7b436fe56ad6ff6ddb8ee00ed407c4609d5257
dist/sxzlab_app-1.0-py3-none-any.whl           1105 bytes  sha256 5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7
dist/sxzlab_src-1.0.tar.gz                      340 bytes  sha256 7953d0a672e3a16e64b07135fdce6d8edb6ee0413ca5be5c559d77646acce0d3
tampered/sxzlab_app-1.0-py3-none-any.whl       1172 bytes  sha256 495e0dca49776caacd4308e161880149065966fe723059ae25adc7e2740df7c0

Each line shows the file, its size and its SHA-256. If your hashes differ from mine, use yours everywhere below; nothing else changes. Now keep a pristine copy of the good files so you can switch back after each experiment:

cp -r dist clean

Step 2: Start a package index and read its page

pip finds files by asking an index for a project page and picking a link. The next script is a complete, tiny index that follows PEP 503, the standard for the “simple” repository page. Save it as index.py.

# index.py
"""A tiny PEP 503 package index for the lab.

Usage: python index.py ROOT PORT [--freeze]

Every file in ROOT is served under /files/. Each project page lists its files with a
#sha256=... fragment, the way PyPI does. By default the fragment is computed from the
file's current bytes on every request, so swapping a file in ROOT also "updates the
index". With --freeze the fragments are computed once at start-up and never change.
"""
import hashlib
import re
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path


def normalize(name):
    return re.sub(r"[-_.]+", "-", name).lower()


def project_of(filename):
    if filename.endswith(".whl"):
        return normalize(filename.split("-")[0])
    return normalize(filename[: -len(".tar.gz")].rsplit("-", 1)[0])


def sha256_of(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def make_handler(root, frozen):
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, fmt, *args):
            sys.stdout.write("index: " + (fmt % args) + "\n")
            sys.stdout.flush()

        def reply(self, code, body, content_type):
            self.send_response(code)
            self.send_header("Content-Type", content_type)
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def do_GET(self):
            path = self.path.split("?")[0]
            files = sorted(p for p in root.iterdir() if p.is_file())
            if path.startswith("/files/"):
                target = root / path[len("/files/"):]
                if target.is_file():
                    return self.reply(200, target.read_bytes(), "application/octet-stream")
            elif path.rstrip("/") == "/simple":
                names = sorted({project_of(p.name) for p in files})
                links = "".join(f'<a href="/simple/{n}/">{n}</a>\n' for n in names)
                return self.reply(200, f"<!DOCTYPE html><html><body>\n{links}</body></html>".encode(), "text/html")
            elif path.startswith("/simple/"):
                project = normalize(path[len("/simple/"):].strip("/"))
                mine = [p for p in files if project_of(p.name) == project]
                if mine:
                    links = ""
                    for p in mine:
                        digest = frozen[p.name] if frozen is not None else sha256_of(p)
                        links += f'<a href="/files/{p.name}#sha256={digest}">{p.name}</a>\n'
                    return self.reply(200, f"<!DOCTYPE html><html><body>\n{links}</body></html>".encode(), "text/html")
            self.reply(404, b"not found", "text/plain")

    return Handler


if __name__ == "__main__":
    root = Path(sys.argv[1]).resolve()
    port = int(sys.argv[2])
    frozen = {p.name: sha256_of(p) for p in root.iterdir() if p.is_file()} if "--freeze" in sys.argv else None
    ThreadingHTTPServer(("127.0.0.1", port), make_handler(root, frozen)).serve_forever()

Two details matter. It listens on 127.0.0.1, not localhost, which avoids slow name lookups on some Windows machines. And each link carries a hash fragment: PEP 503 says the link “SHOULD include a hash in the form of a URL fragment”. By default the script computes that fragment from the file’s current bytes on every request. That models a hostile mirror, which controls both the file and the page that describes it. The --freeze option models a page whose hashes were published earlier and never change.

Open a second terminal in the same folder, activate the environment there too, and start the index. Leave it running; each request it serves is printed in that terminal.

python index.py dist 8765

Back in the first terminal, fetch the project page the way pip will:

$ curl -s http://127.0.0.1:8765/simple/sxzlab-app/
<!DOCTYPE html><html><body>
<a href="/files/sxzlab_app-1.0-py3-none-any.whl#sha256=5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7">sxzlab_app-1.0-py3-none-any.whl</a>
</body></html>

Both links point at /files/ and end in #sha256= followed by the digest of the file that is in dist right now.

Step 3: Install normally and see what pip trusts

The --target option installs into a throwaway folder, so nothing touches your environment. --no-cache-dir keeps pip from reading or writing its cache, so every run really downloads the file from the index. show.py imports the package from that folder and calls it:

# show.py
"""Import the demo package from a folder and call it: python show.py FOLDER"""
import sys

sys.path.insert(0, sys.argv[1])
import sxzlab_app

print(sxzlab_app.hello())
$ python -m pip install sxzlab-app==1.0 --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_plain
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-app==1.0
  Downloading sxzlab_app-1.0-py3-none-any.whl (1.1 kB)
Collecting sxzlab-lib>=2 (from sxzlab-app==1.0)
  Downloading sxzlab_lib-2.0-py3-none-any.whl (1.0 kB)
Installing collected packages: sxzlab-lib, sxzlab-app

Successfully installed sxzlab-app-1.0 sxzlab-lib-2.0
$ python show.py t_plain
hello from sxzlab_app 1.0

pip found sxzlab-app, read its dependency on sxzlab-lib>=2 from the wheel’s metadata, fetched both and installed them. You never listed the library, and you never said which file you expected. That is the trust we are about to test.

Step 4: Swap the file and watch pip install it

Imagine something between you and the real file: a compromised mirror, a proxy that rewrites downloads, a private index whose storage someone else can write to. The file keeps its name and version and the bytes change. We will do it twice, once with a stale hash on the page and once with a fresh one.

A page with a stale hash

Stop the index with Ctrl+C and start it again with the hashes frozen at start-up, then put the tampered wheel in place and install:

python index.py dist 8765 --freeze
$ cp tampered/sxzlab_app-1.0-py3-none-any.whl dist/
$ python -m pip install sxzlab-app==1.0 --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_stale
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-app==1.0
  Downloading sxzlab_app-1.0-py3-none-any.whl (1.2 kB)
ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them.
    sxzlab-app==1.0 from http://127.0.0.1:8765/files/sxzlab_app-1.0-py3-none-any.whl#sha256=5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7:
        Expected sha256 5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7
             Got        495e0dca49776caacd4308e161880149065966fe723059ae25adc7e2740df7c0
[exit code 1]

This is already a useful result. You gave pip no hashes at all, and it still refused: pip compared the download with the hash in the link on the index page and they differed. The message talks about “THE REQUIREMENTS FILE” although there is none: pip prints the same text whether the expected hash came from a requirements file or from the index page. Hold on to this, though: pip trusted the page here, and the page was only right because we froze it before the swap.

A page that matches the swapped file

A real attacker who controls the file also controls the page. Restart the index without --freeze, so the page describes whatever file is in dist, and run the same install:

python index.py dist 8765
$ python -m pip install sxzlab-app==1.0 --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_swap
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-app==1.0
  Downloading sxzlab_app-1.0-py3-none-any.whl (1.2 kB)
Collecting sxzlab-lib>=2 (from sxzlab-app==1.0)
  Downloading sxzlab_lib-2.0-py3-none-any.whl (1.0 kB)
Installing collected packages: sxzlab-lib, sxzlab-app

Successfully installed sxzlab-app-1.0 sxzlab-lib-2.0
$ python show.py t_swap
TAMPERED CODE RAN: a swapped file just executed on import
hello from sxzlab_app 1.0

The install succeeded, reported nothing unusual, and the first line printed by show.py is code you never wrote. The hash on the page matched the swapped file because it came from the same place as the file. A hash delivered together with the thing it protects proves only that the download was not damaged on the way. To catch a swap you need a hash that you recorded earlier, somewhere the attacker cannot reach. That is what a pinned requirements file is.

Put the good wheel back before moving on:

cp clean/sxzlab_app-1.0-py3-none-any.whl dist/

Step 5: Pin the hashes and see pip refuse the swap

pip can compute the hash of a file for you with pip hash. Run it on the two good wheels:

$ python -m pip hash dist/sxzlab_lib-2.0-py3-none-any.whl dist/sxzlab_app-1.0-py3-none-any.whl
dist/sxzlab_lib-2.0-py3-none-any.whl:
--hash=sha256:3478432a21be9328701997214c7b436fe56ad6ff6ddb8ee00ed407c4609d5257
dist/sxzlab_app-1.0-py3-none-any.whl:
--hash=sha256:5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7

Now create requirements.txt with one pinned line per package and the hash under it. The first command in the next transcript prints the file with cat, so copy that content and use your own hashes if they differ. The trailing backslash continues the line, and --hash is a per-requirement option. Then install with --require-hashes, which turns the checking on explicitly:

$ cat requirements.txt
sxzlab-app==1.0 \
    --hash=sha256:5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7
sxzlab-lib==2.0 \
    --hash=sha256:3478432a21be9328701997214c7b436fe56ad6ff6ddb8ee00ed407c4609d5257
$ python -m pip install --require-hashes -r requirements.txt --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_hash
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-app==1.0 (from -r requirements.txt (line 1))
  Downloading sxzlab_app-1.0-py3-none-any.whl (1.1 kB)
Collecting sxzlab-lib==2.0 (from -r requirements.txt (line 3))
  Downloading sxzlab_lib-2.0-py3-none-any.whl (1.0 kB)
Installing collected packages: sxzlab-lib, sxzlab-app

Successfully installed sxzlab-app-1.0 sxzlab-lib-2.0
$ python show.py t_hash
hello from sxzlab_app 1.0

The file lists both packages, the dependency too. The install works, and show.py prints the clean greeting. Now repeat the swap, with the index still serving a page that matches whatever file is in dist, and run the same install command:

$ cp tampered/sxzlab_app-1.0-py3-none-any.whl dist/
$ python -m pip install --require-hashes -r requirements.txt --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_hash2
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-app==1.0 (from -r requirements.txt (line 1))
  Downloading sxzlab_app-1.0-py3-none-any.whl (1.2 kB)
ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them.
    sxzlab-app==1.0 from http://127.0.0.1:8765/files/sxzlab_app-1.0-py3-none-any.whl#sha256=495e0dca49776caacd4308e161880149065966fe723059ae25adc7e2740df7c0 (from -r requirements.txt (line 1)):
        Expected sha256 5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7
             Got        495e0dca49776caacd4308e161880149065966fe723059ae25adc7e2740df7c0
[exit code 1]

How to read the error

pip downloaded the swapped file, hashed it, compared the result with the line in your file, and stopped before unpacking anything. No target folder was created. Read the two lines at the bottom: Expected is the hash you pinned and Got is the hash of what arrived. The URL in the message still ends in the swapped file’s own fragment, the one the index published, and pip ignored it, because in this mode the only hash that counts is yours.

What to do when it fires

When you see this error in real life, do not paste the “Got” hash into the file to make it go away. First work out why the file changed: a new build with the same version number, a proxy, a different index. Then decide which file is the right one.

Restore the good wheel with the cp command from Step 4 before the next step.

Step 6: Learn pip’s other hash errors

A lock goes wrong in more ways than a swapped file. Each case below uses the same two packages and prints exactly what pip said. Every transcript starts with cat of the small requirements file it uses; create that file with the content shown, using your own hashes if they differ, and run the pip command that follows.

A dependency you did not list

Suppose the file names only sxzlab-app. The library is still needed, but nobody pinned or hashed it. Notice that no --require-hashes flag is given:

$ cat reqs_missing.txt
sxzlab-app==1.0 --hash=sha256:5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7
$ python -m pip install -r reqs_missing.txt --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_x2
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-app==1.0 (from -r reqs_missing.txt (line 1))
  Downloading sxzlab_app-1.0-py3-none-any.whl (1.1 kB)
Collecting sxzlab-lib>=2 (from sxzlab-app==1.0->-r reqs_missing.txt (line 1))
ERROR: In --require-hashes mode, all requirements must have their versions pinned with ==. These do not:
    sxzlab-lib>=2 from http://127.0.0.1:8765/files/sxzlab_lib-2.0-py3-none-any.whl#sha256=3478432a21be9328701997214c7b436fe56ad6ff6ddb8ee00ed407c4609d5257 (from sxzlab-app==1.0->-r reqs_missing.txt (line 1))
[exit code 1]

Two things to learn. First, one hash in the file switched hash checking on for the whole installation. The documentation calls this “an all-or-nothing proposition” and says “Hashes are required for all dependencies” and that a dependency “not spelled out and hashed in the requirements file” will “result in an error”. Second, the complaint is about versions, not hashes: pip found sxzlab-lib>=2, a range, which cannot be hashed ahead of time. The message names the requirement and the project that asked for it (sxzlab-app==1.0), which is how you find the missing line.

Pinned but without a hash

List the library with an exact version and no hash:

$ cat reqs_nohash.txt
sxzlab-app==1.0 --hash=sha256:5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7
sxzlab-lib==2.0
$ python -m pip install -r reqs_nohash.txt --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_x2b
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-app==1.0 (from -r reqs_nohash.txt (line 1))
  Downloading sxzlab_app-1.0-py3-none-any.whl (1.1 kB)
Collecting sxzlab-lib==2.0 (from -r reqs_nohash.txt (line 2))
  Downloading sxzlab_lib-2.0-py3-none-any.whl (1.0 kB)
ERROR: Hashes are required in --require-hashes mode, but they are missing from some requirements. Here is a list of those requirements along with the hashes their downloaded archives actually had. Add lines like these to your requirements files to prevent tampering. (If you did not enable --require-hashes manually, note that it turns on automatically when any package has a hash.)
    sxzlab-lib==2.0 --hash=sha256:3478432a21be9328701997214c7b436fe56ad6ff6ddb8ee00ed407c4609d5257
[exit code 1]

This message is the helpful one. pip prints the line to add, with the hash of the file it just downloaded. The documentation notes that this is “a convenient way to bootstrap your list of hashes”. Treat it with care: that hash describes what arrived at this moment, from this index. If the file was already swapped, you would be locking the swap. Compare it with a source you trust, such as a build of your own or a second network path, before you commit it.

Turning the all-or-nothing rule off

pip 26.2 added a flag for projects that mix hashed requirements with local folders or VCS URLs. The docs explain that “when at least one requirement has hashes, hashes become required for all requirements”, and that with --no-require-hashes “Hashes are then verified only for requirements where they are provided.” Here it is on the same file as before, once with the good wheel and once with the swapped one:

$ cat reqs_nohash.txt
sxzlab-app==1.0 --hash=sha256:5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7
sxzlab-lib==2.0
$ python -m pip install --no-require-hashes -r reqs_nohash.txt --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_x2c
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-app==1.0 (from -r reqs_nohash.txt (line 1))
  Downloading sxzlab_app-1.0-py3-none-any.whl (1.1 kB)
Collecting sxzlab-lib==2.0 (from -r reqs_nohash.txt (line 2))
  Downloading sxzlab_lib-2.0-py3-none-any.whl (1.0 kB)
Installing collected packages: sxzlab-lib, sxzlab-app

Successfully installed sxzlab-app-1.0 sxzlab-lib-2.0
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x2c\sxzlab_app already exists. Specify --upgrade to force replacement.
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x2c\sxzlab_app-1.0.dist-info already exists. Specify --upgrade to force replacement.
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x2c\sxzlab_lib already exists. Specify --upgrade to force replacement.
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x2c\sxzlab_lib-2.0.dist-info already exists. Specify --upgrade to force replacement.
$ cp tampered/sxzlab_app-1.0-py3-none-any.whl dist/
$ cat reqs_nohash.txt
sxzlab-app==1.0 --hash=sha256:5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7
sxzlab-lib==2.0
$ python -m pip install --no-require-hashes -r reqs_nohash.txt --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_x2d
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-app==1.0 (from -r reqs_nohash.txt (line 1))
  Downloading sxzlab_app-1.0-py3-none-any.whl (1.2 kB)
ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them.
    sxzlab-app==1.0 from http://127.0.0.1:8765/files/sxzlab_app-1.0-py3-none-any.whl#sha256=495e0dca49776caacd4308e161880149065966fe723059ae25adc7e2740df7c0 (from -r reqs_nohash.txt (line 1)):
        Expected sha256 5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7
             Got        495e0dca49776caacd4308e161880149065966fe723059ae25adc7e2740df7c0
[exit code 1]

The unhashed library installed without complaint, which is exactly the hole the default rule was closing. The hashed package was still verified, and the swapped file was still refused. Use the flag only when you must, and keep the unhashed requirements to a minimum.

A range with a hash

The documentation says requirements must be pinned. Here is a top-level line that is not:

$ cat reqs_range.txt
sxzlab-app>=1.0 --hash=sha256:5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7
sxzlab-lib==2.0 --hash=sha256:3478432a21be9328701997214c7b436fe56ad6ff6ddb8ee00ed407c4609d5257
$ python -m pip install --require-hashes -r reqs_range.txt --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_x1
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-app==1.0 (from -r reqs_range.txt (line 1))
  Downloading sxzlab_app-1.0-py3-none-any.whl (1.1 kB)
Collecting sxzlab-lib==2.0 (from -r reqs_range.txt (line 2))
  Downloading sxzlab_lib-2.0-py3-none-any.whl (1.0 kB)
Installing collected packages: sxzlab-lib, sxzlab-app

Successfully installed sxzlab-app-1.0 sxzlab-lib-2.0
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x1\sxzlab_app already exists. Specify --upgrade to force replacement.
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x1\sxzlab_app-1.0.dist-info already exists. Specify --upgrade to force replacement.
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x1\sxzlab_lib already exists. Specify --upgrade to force replacement.
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x1\sxzlab_lib-2.0.dist-info already exists. Specify --upgrade to force replacement.

In this run pip 26.3 accepted sxzlab-app>=1.0: the only matching file carried the pinned hash, and pip printed the requirement as sxzlab-app==1.0. I would not rely on that: a range tells pip it may choose another version, and a hash can belong to only one of them. The linter in Step 10 flags such lines.

More than one hash for a requirement

A requirement may carry several hashes and a download passes if it matches any of them. That is how a lock covers several files for one version, and it is the key to Step 8. Here the first hash is wrong on purpose:

$ cat reqs_two.txt
sxzlab-app==1.0 --hash=sha256:0000000000000000000000000000000000000000000000000000000000000000 --hash=sha256:5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7
sxzlab-lib==2.0 --hash=sha256:3478432a21be9328701997214c7b436fe56ad6ff6ddb8ee00ed407c4609d5257
$ python -m pip install -r reqs_two.txt --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_x3
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-app==1.0 (from -r reqs_two.txt (line 1))
  Downloading sxzlab_app-1.0-py3-none-any.whl (1.1 kB)
Collecting sxzlab-lib==2.0 (from -r reqs_two.txt (line 2))
  Downloading sxzlab_lib-2.0-py3-none-any.whl (1.0 kB)
Installing collected packages: sxzlab-lib, sxzlab-app

Successfully installed sxzlab-app-1.0 sxzlab-lib-2.0
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x3\sxzlab_app already exists. Specify --upgrade to force replacement.
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x3\sxzlab_app-1.0.dist-info already exists. Specify --upgrade to force replacement.
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x3\sxzlab_lib already exists. Specify --upgrade to force replacement.
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x3\sxzlab_lib-2.0.dist-info already exists. Specify --upgrade to force replacement.

Skipping dependencies

The --no-deps option tells pip not to install dependencies, which sidesteps the rule that every dependency must be listed. It also leaves you with a package that cannot import (I trimmed the file-path lines from the traceback):

$ cat reqs_app_only.txt
sxzlab-app==1.0 --hash=sha256:5ac15b6f38c34250fafaa15ee65d180817eb73b8b66f8df045a92b83d16f4eb7
$ python -m pip install --no-deps -r reqs_app_only.txt --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_x4
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-app==1.0 (from -r reqs_app_only.txt (line 1))
  Downloading sxzlab_app-1.0-py3-none-any.whl (1.1 kB)
Installing collected packages: sxzlab-app
Successfully installed sxzlab-app-1.0
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x4\sxzlab_app already exists. Specify --upgrade to force replacement.
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x4\sxzlab_app-1.0.dist-info already exists. Specify --upgrade to force replacement.
$ python show.py t_x4
Traceback (most recent call last):
    import sxzlab_app
    from sxzlab_lib import greet
ModuleNotFoundError: No module named 'sxzlab_lib'
[exit code 1]

Prefer a complete lock to --no-deps.

Hash algorithms

pip accepts sha256, sha384 and sha512. A weak algorithm is rejected before any download. Uppercase hexadecimal, on the other hand, worked in this run:

$ cat reqs_md5.txt
sxzlab-lib==2.0 --hash=md5:cccccccccccccccccccccccccccccccc
$ python -m pip install -r reqs_md5.txt --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_x5
Usage: __main__.py [options]

ERROR: Invalid requirement: sxzlab-lib==2.0 --hash=md5:cccccccccccccccccccccccccccccccc
__main__.py: error: Allowed hash algorithms for --hash are sha256, sha384, sha512.
[exit code 1]
$ cat reqs_upper.txt
sxzlab-lib==2.0 --hash=sha256:3478432A21BE9328701997214C7B436FE56AD6FF6DDB8EE00ED407C4609D5257
$ python -m pip install -r reqs_upper.txt --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_x6
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-lib==2.0 (from -r reqs_upper.txt (line 1))
  Downloading sxzlab_lib-2.0-py3-none-any.whl (1.0 kB)
Installing collected packages: sxzlab-lib
Successfully installed sxzlab-lib-2.0
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x6\sxzlab_lib already exists. Specify --upgrade to force replacement.
WARNING: Target directory C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\t_x6\sxzlab_lib-2.0.dist-info already exists. Specify --upgrade to force replacement.

The “Usage: __main__.py” line appears because the command was started with python -m pip.

Version-control requirements

A hash needs a file, and a Git repository is not a file:

$ cat reqs_vcs.txt
sxzlab-lib==2.0 --hash=sha256:3478432a21be9328701997214c7b436fe56ad6ff6ddb8ee00ed407c4609d5257
sxzlab-vcs @ git+https://127.0.0.1:9/none.git@main
$ python -m pip install -r reqs_vcs.txt --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_x7
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-vcs @ git+https://127.0.0.1:9/none.git@main (from -r reqs_vcs.txt (line 2))
ERROR: Can't verify hashes for these requirements because we don't have a way to hash version control repositories:
    sxzlab-vcs @ git+https://127.0.0.1:9/none.git@main from git+https://127.0.0.1:9/none.git@main (from -r reqs_vcs.txt (line 2))
[exit code 1]

Step 7: Generate a real lock with pip-compile

Writing hashes by hand does not scale. pip-compile, from the pip-tools package, resolves your top-level requirements into a full pinned list, and its --generate-hashes flag adds the hashes. Put what you want in requirements.in, compile it, look at the top of the result and count the hashes with this small script, hashcount.py, which you save in the lab folder:

# hashcount.py
"""Count the hashes per pinned package in a requirements file: python hashcount.py FILE"""
import re
import sys

text = open(sys.argv[1], encoding="utf-8").read()
total = 0
for block in re.split(r"\n(?=\S)", text):
    match = re.match(r"([A-Za-z0-9_.-]+)==(\S+)", block)
    if match:
        count = len(re.findall(r"--hash=sha256:", block))
        total += count
        print(f"{match.group(1):20} {match.group(2):12} {count:3} hashes")
print(f"{'total':33} {total:3} hashes")
mkdir real
cd real
echo "requests==2.34.2" > requirements.in
$ cat requirements.in
requests==2.34.2
$ pip-compile --quiet --strip-extras --generate-hashes requirements.in
$ head -n 14 requirements.txt
#
# This file is autogenerated by pip-compile with Python 3.13
# by the following command:
#
#    pip-compile --generate-hashes --strip-extras requirements.in
#
certifi==2026.11.20 \
    --hash=sha256:7422df25243767b9877031a2248cb14d09ddac9beee846f4cef3d5c9191d488f \
    --hash=sha256:af1cb240a8133f105aa52684a3a3258339d7f2fd0bd4e2812698ff5cf5588c4e
    # via requests
charset-normalizer==3.5.3 \
    --hash=sha256:00edb7682962c596f774bfa126e6b6f885b7af2319f448d327591c284a482de8 \
    --hash=sha256:01b35bec964b92b89bdf94adf931d2e80a15f1c7b93bf850b4430cca23f7a2a2 \
    --hash=sha256:020cabbb90926b2d8b022a5e057ab349f28844b61f34117323fc08c2971915e3 \
$ python ../hashcount.py requirements.txt
certifi              2026.11.20     2 hashes
charset-normalizer   3.5.3        172 hashes
idna                 3.20           2 hashes
requests             2.34.2         2 hashes
urllib3              2.8.0          2 hashes
total                             180 hashes

One requirement turned into five pinned packages, with comments saying which package pulled each one in. Notice the count: two hashes for most packages, and 172 for charset-normalizer. The lock lists a hash for each file the index offers for that version, so that whichever wheel a machine picks will match one of them. PyPI’s JSON API (for example https://pypi.org/pypi/charset-normalizer/3.5.3/json) lists 172 files for that release, 171 wheels and one sdist, which matches the count. The whole file carries 180. Now install from the lock, with checking on, and then again with --only-binary=:all:, which also forbids source builds (more on that in Step 9):

$ python -m pip install --require-hashes -r requirements.txt --no-cache-dir --target t_real
Collecting certifi==2026.11.20 (from -r requirements.txt (line 7))
  Downloading certifi-2026.11.20-py3-none-any.whl (127 kB)
Collecting charset-normalizer==3.5.3 (from -r requirements.txt (line 11))
  Downloading charset_normalizer-3.5.3-cp313-cp313-win_amd64.whl (213 kB)
Collecting idna==3.20 (from -r requirements.txt (line 185))
  Downloading idna-3.20-py3-none-any.whl (69 kB)
Collecting requests==2.34.2 (from -r requirements.txt (line 189))
  Downloading requests-2.34.2-py3-none-any.whl (73 kB)
Collecting urllib3==2.8.0 (from -r requirements.txt (line 193))
  Downloading urllib3-2.8.0-py3-none-any.whl (135 kB)
Installing collected packages: urllib3, idna, charset-normalizer, certifi, requests

Successfully installed certifi-2026.11.20 charset-normalizer-3.5.3 idna-3.20 requests-2.34.2 urllib3-2.8.0
Installing collected packages: urllib3, idna, charset-normalizer, certifi, requests

Successfully installed certifi-2026.11.20 charset-normalizer-3.5.3 idna-3.20 requests-2.34.2 urllib3-2.8.0

Step 8: The lock that works on Windows and breaks on Linux

Wheels are built for an operating system, a CPU and a Python version. Your Windows machine and a Linux server download different files for the same version, and different files have different hashes. So a lock made from the files on one machine can fail on another. Here is the failure with markupsafe 3.0.3. Go back to the lab folder, make a scratch folder for this experiment, download the wheel for this machine, pin its hash, install it here, then ask pip to resolve the same file for Linux without installing anything (--dry-run with --platform):

cd ..
mkdir plat
cd plat
$ python -m pip download markupsafe==3.0.3 --no-deps --only-binary=:all: --no-cache-dir -d wheels
Collecting markupsafe==3.0.3
  Downloading markupsafe-3.0.3-cp313-cp313-win_amd64.whl.metadata (2.8 kB)
Downloading markupsafe-3.0.3-cp313-cp313-win_amd64.whl (15 kB)
Saved .\wheels\markupsafe-3.0.3-cp313-cp313-win_amd64.whl
Successfully downloaded markupsafe
$ cat requirements.txt
markupsafe==3.0.3 --hash=sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5
$ python -m pip install --require-hashes -r requirements.txt --no-cache-dir --target here
Collecting markupsafe==3.0.3 (from -r requirements.txt (line 1))
  Downloading markupsafe-3.0.3-cp313-cp313-win_amd64.whl (15 kB)
Installing collected packages: markupsafe
Successfully installed markupsafe-3.0.3
$ python -m pip install --target linux --dry-run --platform manylinux2014_x86_64 --python-version 3.13 --only-binary=:all: --require-hashes -r requirements.txt --no-cache-dir
Collecting markupsafe==3.0.3 (from -r requirements.txt (line 1))
  Downloading markupsafe-3.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (22 kB)
ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them.
    markupsafe==3.0.3 from https://files.pythonhosted.org/packages/a9/21/9b05698b46f218fc0e118e1f8168395c65c8a2c750ae2bab54fc4bd4e0e8/markupsafe-3.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (from -r requirements.txt (line 1)):
        Expected sha256 9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5
             Got        ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676
[exit code 1]

On this machine pip picked the win_amd64 wheel and everything matched. For Linux it picked a manylinux wheel and the hash was different, so pip refused. The message looks like tampering and is not; the file is genuine and simply not the one you pinned. The fix is to let pip-compile record every file:

$ pip-compile --quiet --strip-extras --generate-hashes markupsafe.in -o all.txt
$ python ../hashcount.py all.txt
markupsafe           3.0.3         89 hashes
total                              89 hashes
$ python -m pip install --target linux --dry-run --platform manylinux2014_x86_64 --python-version 3.13 --only-binary=:all: --require-hashes -r all.txt --no-cache-dir
Collecting markupsafe==3.0.3 (from -r all.txt (line 7))
  Downloading markupsafe-3.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (22 kB)
Would install MarkupSafe-3.0.3

The lock for this one release holds 89 hashes (PyPI lists 89 files for it, 88 wheels and one sdist), including both wheels, and the Linux resolution now ends in Would install MarkupSafe-3.0.3. The rule to remember: generate locks with --generate-hashes, not by hashing the files you happened to download.

Step 9: A gap hash checking does not close, the build tools

Hash checking covers the files pip downloads for the requirements in your file. A source distribution is not ready to run; pip has to build it first, and the tools for that build are themselves packages, named in the sdist’s pyproject.toml under build-system.requires. The lab sdist sxzlab-src asks for setuptools>=61. To let the build find it, the next command copies a real setuptools wheel from PyPI into dist, where the local index serves it. Then the requirements file pins only the sdist, with its hash, and pip installs it with checking on. Run this from the lab folder that holds dist (use cd .. to leave the scratch folder), with the index from Step 2 still running:

$ python -m pip download setuptools --no-deps --only-binary=:all: --no-cache-dir -d dist
Collecting setuptools
  Downloading setuptools-84.2.1-py3-none-any.whl.metadata (6.6 kB)
Downloading setuptools-84.2.1-py3-none-any.whl (876 kB)
Saved .\dist\setuptools-84.2.1-py3-none-any.whl
Successfully downloaded setuptools
$ cat reqs_src.txt
sxzlab-src==1.0 --hash=sha256:7953d0a672e3a16e64b07135fdce6d8edb6ee0413ca5be5c559d77646acce0d3
$ python -m pip install --require-hashes -r reqs_src.txt --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_src
Looking in indexes: http://127.0.0.1:8765/simple/
Collecting sxzlab-src==1.0 (from -r reqs_src.txt (line 1))
  Downloading sxzlab_src-1.0.tar.gz (340 bytes)
  Installing build dependencies: started
  Installing build dependencies: finished with status 'done'
  Getting requirements to build wheel: started
  Getting requirements to build wheel: finished with status 'done'
  Preparing metadata (pyproject.toml): started
  Preparing metadata (pyproject.toml): finished with status 'done'
Building wheels for collected packages: sxzlab-src
  Building wheel for sxzlab-src (pyproject.toml): started
  Building wheel for sxzlab-src (pyproject.toml): finished with status 'done'
Successfully built sxzlab-src
Installing collected packages: sxzlab-src
Successfully installed sxzlab-src-1.0

The install succeeded. Here are the requests the index received while pip worked on it:

"GET /simple/sxzlab-src/" 200
"GET /files/sxzlab_src-1.0.tar.gz" 200
"GET /simple/setuptools/" 200
"GET /files/setuptools-84.2.1-py3-none-any.whl" 200

pip fetched setuptools 84.2.1 in the middle of a hash-checked install. That build requirement is neither pinned nor hashed, and nothing complained: the line “Installing build dependencies” in the transcript is the point where it was fetched. The sdist itself was verified; its build tools were not. A swapped build tool could run code during installation.

Closing the gap

There are two ways to close it.

Option one: refuse source distributions

This is the simple one, and the pip documentation recommends it next to hash checking. Add --only-binary=:all::

$ python -m pip install --require-hashes --only-binary=:all: -r reqs_src.txt --index-url http://127.0.0.1:8765/simple/ --no-cache-dir --target t_src2
Looking in indexes: http://127.0.0.1:8765/simple/
ERROR: Could not find a version that satisfies the requirement sxzlab-src==1.0 (from versions: none)
ERROR: No matching distribution found for sxzlab-src==1.0
[exit code 1]

The error is blunt, “from versions: none”, but it is the right outcome: the only file for that version is an sdist and you said no builds.

Option two: install the build tools yourself

If you cannot avoid building from source, pip’s help text for --no-build-isolation says “Build dependencies specified by PEP 518 must be already installed if this option is used.” You can install those build tools yourself from a hashed requirements file first. I did not test that route in this lab, so try it on a throwaway environment before you depend on it.

Step 10: Check the file in CI before pip runs

Most of the mistakes above are visible in the text of the file. A linter can catch them in a pull request, long before a deployment fails. This one, lockcheck.py, parses each line with the packaging library and reports five kinds of problem (plus LK0 for a line it cannot parse): a version that is not pinned with a single == (LK1), no hash (LK2), an unusable hash (LK3), a URL, VCS, editable or path requirement (LK4), and the same package pinned twice (LK5). It is deliberately stricter than pip in one place: it flags the range line that pip 26.3 accepted in Step 6.

# lockcheck.py
"""Check hashed requirements files the way pip --require-hashes will, before pip runs.

Usage: python lockcheck.py FILE [FILE ...]      exit 0 = clean, 1 = problems, 2 = unreadable
"""
import re
import sys
from pathlib import Path

from packaging.requirements import InvalidRequirement, Requirement
from packaging.utils import canonicalize_name

HASH_RE = re.compile(r"--hash=(\w+):(\S+)")
HEX_LEN = {"sha256": 64, "sha384": 96, "sha512": 128}


def logical_lines(text):
    """Join backslash continuations, drop comments and blank lines."""
    lines, buffer = [], ""
    for raw in text.splitlines():
        line = raw.rstrip()
        if line.endswith("\\"):
            buffer += line[:-1] + " "
            continue
        full = re.sub(r"(^|\s)#.*$", "", buffer + line).strip()
        buffer = ""
        if full:
            lines.append(full)
    return lines


def check_text(text):
    """Return a list of (code, message) problems found in a requirements file."""
    problems, pins = [], {}
    for line in logical_lines(text):
        if line.startswith(("-e ", "--editable")):
            problems.append(("LK4", f"editable install cannot be hashed: {line}"))
            continue
        if line.startswith("-"):
            continue  # -r, --index-url and other options
        hashes = HASH_RE.findall(line)
        spec = HASH_RE.sub("", line).strip()
        if "://" in spec or " @ " in spec or spec.startswith((".", "/")):
            problems.append(("LK4", f"URL, VCS or path requirement: {spec}"))
            continue
        try:
            req = Requirement(spec)
        except InvalidRequirement as exc:
            problems.append(("LK0", f"cannot parse {spec!r}: {exc}"))
            continue
        ops = [(s.operator, s.version) for s in req.specifier]
        if not (len(ops) == 1 and ops[0][0] in ("==", "===") and not ops[0][1].endswith(".*")):
            problems.append(("LK1", f"{req.name} is not pinned with a single == (found {str(req.specifier) or 'no version'})"))
        if not hashes:
            problems.append(("LK2", f"{req.name} has no --hash"))
        for algo, digest in hashes:
            if algo not in HEX_LEN or len(digest) != HEX_LEN[algo] or not re.fullmatch(r"[0-9a-fA-F]+", digest):
                problems.append(("LK3", f"{req.name} has an unusable hash: {algo}:{digest[:10]}"))
        key = (canonicalize_name(req.name), str(req.marker or ""))
        if key in pins and pins[key] != str(req.specifier):
            problems.append(("LK5", f"{req.name} is pinned twice: {pins[key]} and {req.specifier}"))
        pins[key] = str(req.specifier)
    return problems


def main(paths):
    worst = 0
    for name in paths:
        try:
            text = Path(name).read_text(encoding="utf-8")
        except OSError as exc:
            print(f"{name}: cannot read ({exc})")
            worst = 2
            continue
        problems = check_text(text)
        if not problems:
            print(f"{name}: OK")
        for code, message in problems:
            print(f"{name}: {code} {message}")
        if problems and worst == 0:
            worst = 1
    return worst


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

Run it on the real lock from Step 7, the lab lock and a file made of mistakes. The last file has one of each problem:

$ python lockcheck.py requirements.txt real/requirements.txt reqs_bad.txt
requirements.txt: OK
real/requirements.txt: OK
reqs_bad.txt: LK1 sxzlab-app is not pinned with a single == (found >=1.0)
reqs_bad.txt: LK2 sxzlab-lib has no --hash
reqs_bad.txt: LK3 sxzlab-extra has an unusable hash: md5:cccccccccc
reqs_bad.txt: LK5 sxzlab-extra is pinned twice: ==1.0 and ==1.1
reqs_bad.txt: LK4 URL, VCS or path requirement: git+https://example.test/x.git@v1
[exit code 1]

The exit code is 0 for clean files, 1 when there are problems and 2 when a file cannot be read, so a CI step can simply run the command. A linter you cannot trust is worse than none, so here are its tests. Note the test about uppercase hexadecimal: my first version rejected it, then the Step 6 experiment showed that pip accepts it, and the test was changed to match what pip does.

# test_lockcheck.py
from lockcheck import check_text

H1 = "a" * 64
H2 = "b" * 64


def codes(text):
    return [code for code, _ in check_text(text)]


def test_clean_file_passes():
    assert codes(f"sxzlab-lib==2.0 --hash=sha256:{H1}\n") == []


def test_continuation_lines_and_comments():
    text = f"sxzlab-lib==2.0 \\\n    --hash=sha256:{H1} \\\n    --hash=sha256:{H2}\n    # via sxzlab-app\n"
    assert codes(text) == []


def test_marker_is_allowed():
    assert codes(f'colorama==0.4.6 ; sys_platform == "win32" --hash=sha256:{H1}\n') == []


def test_range_is_not_pinned():
    assert codes(f"sxzlab-lib>=2 --hash=sha256:{H1}\n") == ["LK1"]


def test_wildcard_is_not_pinned():
    assert codes(f"sxzlab-lib==2.* --hash=sha256:{H1}\n") == ["LK1"]


def test_bare_name_is_not_pinned():
    assert codes(f"sxzlab-lib --hash=sha256:{H1}\n") == ["LK1"]


def test_missing_hash():
    assert codes("sxzlab-lib==2.0\n") == ["LK2"]


def test_md5_is_refused():
    assert codes("sxzlab-lib==2.0 --hash=md5:" + "c" * 32 + "\n") == ["LK3"]


def test_short_and_non_hex_hashes_are_refused():
    assert codes("sxzlab-lib==2.0 --hash=sha256:" + "a" * 63 + "\n") == ["LK3"]
    assert codes("sxzlab-lib==2.0 --hash=sha256:" + "z" * 64 + "\n") == ["LK3"]


def test_uppercase_hex_is_accepted_because_pip_accepts_it():
    assert codes("sxzlab-lib==2.0 --hash=sha256:" + "A" * 64 + "\n") == []


def test_sha512_is_accepted():
    assert codes("sxzlab-lib==2.0 --hash=sha512:" + "d" * 128 + "\n") == []


def test_direct_reference_and_vcs_and_editable():
    assert codes(f"sxzlab-lib @ https://example.test/x.whl --hash=sha256:{H1}\n") == ["LK4"]
    assert codes("git+https://example.test/x.git@v1\n") == ["LK4"]
    assert codes("-e ./local\n") == ["LK4"]


def test_option_lines_are_ignored():
    assert codes(f"--index-url http://127.0.0.1:8765/simple/\nsxzlab-lib==2.0 --hash=sha256:{H1}\n") == []


def test_same_package_pinned_twice():
    text = f"sxzlab-lib==2.0 --hash=sha256:{H1}\nSxzlab_Lib==2.1 --hash=sha256:{H2}\n"
    assert codes(text) == ["LK5"]


def test_same_pin_twice_is_fine_and_markers_separate_pins():
    assert codes(f"sxzlab-lib==2.0 --hash=sha256:{H1}\nsxzlab-lib==2.0 --hash=sha256:{H1}\n") == []
    text = f'x==1 ; python_version < "3.12" --hash=sha256:{H1}\nx==2 ; python_version >= "3.12" --hash=sha256:{H2}\n'
    assert codes(text) == []


def test_unparseable_line():
    assert codes("this is not a requirement !!!\n") == ["LK0"]

Tests can also be weak. This script plants one bug at a time in lockcheck.py and checks that the tests notice:

# mutants.py
"""Plant one bug at a time in lockcheck.py and see whether the tests notice."""
import os
import subprocess
import sys
from pathlib import Path

TARGET = Path("lockcheck.py")
SRC = TARGET.read_text(encoding="utf-8")
MUTANTS = [
    ("accept >= as a pin", 'ops[0][0] in ("==", "===")', 'ops[0][0] in ("==", "===", ">=")'),
    ("accept a wildcard pin", ' and not ops[0][1].endswith(".*")', ""),
    ("make hashes optional", "if not hashes:", "if False:"),
    ("accept any hash algorithm", "algo not in HEX_LEN or ", ""),
    ("skip the length check", "len(digest) != HEX_LEN[algo] or ", ""),
    ("accept non-hex characters", "[0-9a-fA-F]+", ".+"),
    ("reject uppercase hex", "[0-9a-fA-F]+", "[0-9a-f]+"),
    ("ignore continuation lines", 'if line.endswith("\\\\"):', "if False:"),
    ("let URL requirements through", '"://" in spec or " @ " in spec or ', ""),
    ("forget duplicate pins", "if key in pins and pins[key] != str(req.specifier):", "if False:"),
    ("keep comments", 'full = re.sub(r"(^|\\s)#.*$", "", buffer + line).strip()', "full = (buffer + line).strip()"),
]
env = dict(os.environ, PYTEST_ADDOPTS="-p no:cacheprovider")
caught = 0
try:
    for label, old, new in MUTANTS:
        assert SRC.count(old) == 1, f"{label}: pattern found {SRC.count(old)} times"
        TARGET.write_text(SRC.replace(old, new), encoding="utf-8", newline="\n")
        run = subprocess.run([sys.executable, "-m", "pytest", "-x", "-q", "test_lockcheck.py"], capture_output=True, text=True, env=env)
        status = "caught" if run.returncode != 0 else "SURVIVED"
        caught += run.returncode != 0
        print(f"{status:9} {label}")
finally:
    TARGET.write_text(SRC, encoding="utf-8", newline="\n")
print(f"{caught} of {len(MUTANTS)} planted bugs caught")
$ python -m pytest -q test_lockcheck.py
................                                                                                                 [100%]
16 passed in 0.02s
$ python mutants.py
caught    accept >= as a pin
caught    accept a wildcard pin
caught    make hashes optional
caught    accept any hash algorithm
caught    skip the length check
caught    accept non-hex characters
caught    reject uppercase hex
caught    ignore continuation lines
caught    let URL requirements through
caught    forget duplicate pins
caught    keep comments
11 of 11 planted bugs caught

All sixteen tests pass and all eleven planted bugs are caught. A survivor would mean a rule with no test behind it.

Step 11: Keep the lock fresh without losing the seal

A lock that is never updated stops getting security fixes, so plan the update. The pip-tools documentation lists --upgrade-package (short form -P) for upgrading one package without moving the rest; I did not run an upgrade in this lab. Whatever tool you use, review the change the same way: read the diff of requirements.txt, look at when each new version was published, and run the lint and the audit before you merge. The tutorials on dependency cooldowns and pip-audit cover those two checks.

Check that everything works end to end

  1. Run python lockcheck.py requirements.txt. It should print requirements.txt: OK and exit with 0.
  2. Install from the lock into a throwaway folder with --require-hashes --no-cache-dir --target. It should end with “Successfully installed”.
  3. Swap one file as in Step 4 and run the install again. It should stop with “THESE PACKAGES DO NOT MATCH THE HASHES” and exit code 1.
  4. For production builds add --only-binary=:all: so that no source build can bring in unhashed tools.
  5. Delete the throwaway folders. If you want the lab again, rerun mkwheel.py.

Common mistakes

  • Copying the “Got” hash to make an error vanish. That turns a tamper alarm into a lock on the tampered file.
  • Hashing only the files on your own machine. Use --generate-hashes so every platform’s wheel is covered (Step 8).
  • Using --no-deps or --no-require-hashes to silence an error. Both remove protection (Step 6).
  • Forgetting that a pin is not a review. The hash of a malicious release is as valid as the hash of a good one.
  • Believing the checking covers the build tools. It did not in Step 9.
  • Where to go next

    Read the pip documentation on secure installs and the requirements file format, and try the same ideas with pylock.toml in our PEP 751 tutorial. For files that are not Python packages, verifying a download shows when a published hash helps and when a signature is needed. Finally, run your own lockfile through lockcheck.py in CI and see what it finds.

    Tags:

    Hash Functionspippip-toolsPyPIPython PackagingSupply Chain Security

Share

A pair of unfinished pale wooden clogs, called sabots, on a clogmaker's workbench among wood shavings and hand tools.
Previous Post

Anthropic Denies Claude Is Trained to Sabotage Work, and Its Documents Fit the Denial but Show a Silent Safeguard Retired After About Two Days in June, a Training Cap on Kernel and LLM-Architecture Skills With No Released-Model Score, and Viral Evidence That Cannot Tell Them Apart

A glass sugar dispenser with a steel lid beside a salt shaker and a pepper shaker with brass caps on a diner table
Next Post

easyDNS Says Customer Records, Stored AWS Keys and Unsalted Mailbox Password Hashes Were Exposed, but the Public Notice Gives No Counts, the Entry Point Appears Only in the CEO’s Comments to a Reporter, and It Is the Second Security Incident Its Blog Has Posted This Year

No Comment! Be the first one.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Latest
30 Nov
How to Fix SSL CERTIFICATE_VERIFY_FAILED in Python Without Turning Verification Off: Read the Error Code, Find Who Has to Fix It, Trust Your Own CA, and Catch Broken Chains in CI
30 Nov
The Unpublished Lattice Paper Attributed to Anthropic Reached the Public as Two Title Hashes That Match One Guessable String, the Coverage Splits on What It Breaks Because the Title Names Quantum Algorithms, Not a Key Recovery, and 21 of 24 Sites We Tested Still Pair ML-KEM With X25519
Trending
November 30, 2026
How to Fix SSL CERTIFICATE_VERIFY_FAILED in Python Without Turning Verification Off: Read the Error Code, Find Who Has to Fix It, Trust Your Own CA, and Catch Broken Chains in CI
November 30, 2026
The Unpublished Lattice Paper Attributed to Anthropic Reached the Public as Two Title Hashes That Match One Guessable String, the Coverage Splits on What It Breaks Because the Title Names Quantum Algorithms, Not a Key Recovery, and 21 of 24 Sites We Tested Still Pair ML-KEM With X25519
November 30, 2026
Cacti’s 4HTTP2SHELL Chain Drew 1,793 Attack Attempts on One Honeypot Sensor in Four Days, but the Fix Is Still Only Source Patches With No 1.2.32 Release or CVE ID, the Advisory Calls It “Authenticated,” and on Our Reading of the Code the Guest Route Hinges on One Setting That Ships as “No User”
November 30, 2026
How to Triage Vulnerabilities in Python With CVSS, EPSS, and CISA KEV: Build a Decision Engine, Replay It on 71 Real KEV Additions, and See What Each Signal Missed
November 30, 2026
The Register Gives China Mobile Credit for the “Most Capable” All-Domestic Open-Weight Model, but It Is China Telecom’s Xing4.1-Preview, Its Report Has No Capability Scores, the 4.68x Is a Simulation, and the Model Card’s Own Table Has It First or Tied for First on 2 of 18 Rows
November 30, 2026
easyDNS Says Customer Records, Stored AWS Keys and Unsalted Mailbox Password Hashes Were Exposed, but the Public Notice Gives No Counts, the Entry Point Appears Only in the CEO’s Comments to a Reporter, and It Is the Second Security Incident Its Blog Has Posted This Year

Related Posts

A laptop wrapped in a chain and padlock, illustrating least-privilege controls for AI agents.
Learning Hub

How to Secure Tool-Using AI Agents Before They Touch Production

June 8, 2026
Colorful sticky notes arranged on an office wall, symbolizing governance checklists and planning.
Learning Hub

AI Governance for Agentic Apps: A Practical Checklist for Builders

June 8, 2026
A technician connects green fiber optic cables at a data center, representing a private production inference endpoint.
Learning Hub

How to Deploy a Fine-Tuned LLM Behind a Private Production Inference Endpoint

June 8, 2026
Narrow aisle behind black supercomputer racks in a data center
Learning Hub

Kubernetes SELinux Volume Labeling: What Cluster Operators Should Audit Before v1.37

June 8, 2026
SXZ.io SXZ.io
  • [email protected]

Categories

Articles
Learning Hub
News

All Rights Reserved by SXZ.io ©2026