Nothing changed, but the build did
On Monday the shop's build passed. On Tuesday it failed, and nobody had pushed a single commit.
Overnight, a library the shop uses published a new version, and the build picked it up by itself. It could as easily have picked up something worse.
By the end of this lesson
Note
I can lock a project's dependencies with hashes so every install gets the same files.
Key words
| Word | What it means | Example |
|---|---|---|
| Version range | any version that meets a rule | shopkit>=2.4 |
| Pin | one exact version | shopkit==2.4.0 |
| Lock file | every package, pinned, with its hash | |
| Hash | the digest a file must have to be accepted | |
| Reproducible | giving the same result every time |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
4 questionsThe rule for this lesson
Warning
You will replace a package on an index, in your own lab copy only. The index is a folder inside the lab. Changing files on someone else's systems without permission is a crime under the Computer Misuse Act 1990.
A range takes whatever is newest
A version range such as shopkit>=2.4 accepts any version from 2.4 up. So the install depends on the day you run it.
Write the package builder if an earlier lesson did not, publish shopkit 2.4.0, and install with a range. Then publish 2.5.0 and install again.
Write the package builder (part 1)
docker exec -i ci sh -c "cat > pkg.py" <<'EOF'
"""Puts a made-up package in one of the lab's package indexes:
python3 pkg.py private|public NAME VERSION WORDS
Importing it prints WORDS and does nothing else."""
import hashlib
import os
import re
import sys
import zipfile
index, name, version, words = sys.argv[1:5]
module = re.sub(r"[-_.]+", "_", name).lower()
info = module + "-" + version + ".dist-info/"
files = {
module + "/__init__.py": "print(" + repr(words) + ")\n",
info + "METADATA": "Metadata-Version: 2.1\nName: " + name + "\nVersion: " + version + "\n",
info + "WHEEL": "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n",
}
EOFShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the package builder (part 2)
docker exec -i ci sh -c "cat >> pkg.py" <<'EOF'
files[info + "RECORD"] = "".join(path + ",,\n" for path in [*files, info + "RECORD"])
folder = "/tmp/pkg/" + index + "/simple/" + module.replace("_", "-")
os.makedirs(folder, exist_ok=True)
out = folder + "/" + module + "-" + version + "-py3-none-any.whl"
with zipfile.ZipFile(out, "w") as wheel:
for path, text in files.items():
wheel.writestr(zipfile.ZipInfo(path, (2026, 1, 1, 0, 0, 0)), text)
print(index, out.split("/")[-1], hashlib.sha256(open(out, "rb").read()).hexdigest())
EOFShown here, not run. Press Start lab to type it into your own lab’s terminal.
Publish shopkit 2.4.0
docker exec ci python3 pkg.py public shopkit 2.4.0 "shopkit 2.4.0, the real one"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Start the indexes
docker exec -d ci python3 -m http.server 8100 --bind 127.0.0.1 -d /tmp/pkgShown here, not run. Press Start lab to type it into your own lab’s terminal.
Install with a range
docker exec ci sh -c "printf 'shopkit>=2.4\n' > requirements.in" && docker exec ci pip install --no-cache-dir --dry-run --index-url http://127.0.0.1:8100/public/simple/ -r requirements.inShown here, not run. Press Start lab to type it into your own lab’s terminal.
A new version is published
docker exec ci python3 pkg.py public shopkit 2.5.0 "shopkit 2.5.0, released today"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Install with the same range again
docker exec ci pip install --no-cache-dir --dry-run --index-url http://127.0.0.1:8100/public/simple/ -r requirements.inShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsA lock file pins versions and bytes
A pin fixes the version, but trusts the index to hand out the same file. A lock file also records each file's hash, and pip with --require-hashes refuses any file that does not match.
Tools write lock files for you. uv's pip compile reads the ranges and writes every package pinned, with hashes.
Install uv in the step runner
docker exec ci pip install -q --user --no-warn-script-location uv==0.13.9Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the lock file
docker exec -i ci .local/bin/uv pip compile requirements.in --no-cache --quiet --generate-hashes --index-url http://127.0.0.1:8100/public/simple/ -o requirements.lock && docker exec ci cat requirements.lockShown here, not run. Press Start lab to type it into your own lab’s terminal.
Install from the lock file
docker exec ci pip install --no-cache-dir --dry-run --ignore-installed --require-hashes --index-url http://127.0.0.1:8100/public/simple/ -r requirements.lockShown here, not run. Press Start lab to type it into your own lab’s terminal.
Try it: accept only what is locked
lock = {"shopkit": ("2.5.0", "sha256:8f3e")}
def accept(name, version, digest):
wanted = lock.get(name)
return wanted == (version, digest)
print(accept("shopkit", "2.5.0", "sha256:8f3e"))
print(accept("shopkit", "2.5.0", "sha256:0bad"))
print(accept("shopkit", "2.6.0", "sha256:8f3e"))
# Add a line that accepts "requests" 2.33.0 with digest "sha256:a1". Which call proves it?
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsSame version, different bytes
Now play an attacker who can write to the index. Replace the shopkit 2.5.0 file with other code under the same name and version.
Install it with a plain pin, then from the lock file, and compare.
Replace the 2.5.0 file
docker exec ci python3 pkg.py public shopkit 2.5.0 "shopkit 2.5.0, replaced by an attacker: this could have been any code"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Install with a pin, then import
docker exec ci pip install --no-cache-dir -q --user --force-reinstall --index-url http://127.0.0.1:8100/public/simple/ shopkit==2.5.0 && docker exec ci python3 -c "import shopkit"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Install from the lock file again
docker exec ci pip install --no-cache-dir --dry-run --ignore-installed --require-hashes --index-url http://127.0.0.1:8100/public/simple/ -r requirements.lockShown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think pinning a version means always getting the same code. A pin trusts whoever serves the file. Only a hash proves the bytes are the ones you reviewed. Lock every package, transitive ones too, and let the install fail when one differs.
Pin everything a build pulls in
The same idea covers more than Python. Pin a container image by its digest, as this lab's own file does, and a CI action by its commit, not its tag.
Update pins on purpose, in a reviewed change, with a bot such as Dependabot or Renovate. The shop's Dockerfile still needs this.
Read what the shop's image is built from
docker exec gitleaks grep -n FROM /work/tuckshop/DockerfileShown here, not run. Press Start lab to type it into your own lab’s terminal.
Assignment: check a lock file
A lock file has one requirement per entry, such as shopkit==2.5.0 --hash=sha256:8f3e, where a line ending in \ continues on the next. Lines starting with # are comments. Write three functions.
entries(text) joins continued lines, skips comments and blank lines, and returns a list of (requirement, hashes) pairs: the requirement is the text before the first --hash, stripped, and hashes is the list of values after each --hash=. problems(text) returns a sorted list of (name, problem) pairs, where name is the requirement's package name in lower case, and problem is "not pinned" when the requirement has no == and "no hash" when it has no hashes. An entry can have both. accepts(text, name, digest) returns True when the entry for name (any case) lists sha256: followed by digest.
def entries(text):
return []
def problems(text):
return []
def accepts(text, name, digest):
return True
Make a free account to save your work and track your progress.
Exit quiz
Have a go