Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Pinning and lock files

After this lesson: I can lock a project's dependencies with hashes so every install gets the same files.

55 min lesson14 commandsDevSecOps lab: build a security pipeline and a gate

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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

WordWhat it meansExample
Version rangeany version that meets a ruleshopkit>=2.4
Pinone exact versionshopkit==2.4.0
Lock fileevery package, pinned, with its hash
Hashthe digest a file must have to be accepted
Reproduciblegiving the same result every time

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The 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)

Command
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",
}
EOF

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the package builder (part 2)

Command
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())
EOF

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Publish shopkit 2.4.0

Command
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

Command
docker exec -d ci python3 -m http.server 8100 --bind 127.0.0.1 -d /tmp/pkg

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Install with a range

Command
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.in

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

A new version is published

Command
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

Command
docker exec ci pip install --no-cache-dir --dry-run --index-url http://127.0.0.1:8100/public/simple/ -r requirements.in

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A 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

Command
docker exec ci pip install -q --user --no-warn-script-location uv==0.13.9

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the lock file

Command
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.lock

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Install from the lock file

Command
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.lock

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Try it: accept only what is locked

Code: python
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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Same 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

Command
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

Command
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

Command
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.lock

Shown 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

Command
docker exec gitleaks grep -n FROM /work/tuckshop/Dockerfile

Shown 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.

Code: python
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

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.