A name that leaked
In 2021 a researcher found the names of private packages used inside large companies, in files they had published by accident. He uploaded packages with the same names to public indexes, with high version numbers.
Build machines inside those companies downloaded his packages instead of their own. His code only reported back, and he was paid bug bounties.
By the end of this lesson
Note
I can explain how dependency confusion picks the wrong package and stop it.
Key words
| Word | What it means | Example |
|---|---|---|
| Package index | a server that hands out packages by name | |
| Internal package | one only your organisation should publish | |
| Extra index | a second index pip also searches | --extra-index-url |
| Dependency confusion | a public package taking an internal one's place | |
| Index strategy | the rule for choosing between indexes |
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 publish a package that takes another's place, in your own lab copy only. Both indexes are inside the lab. Never upload a lookalike package to a real public index. Getting your code onto someone else's systems without permission is a crime under the Computer Misuse Act 1990.
The shop has its own index
The shop keeps its receipt code in an internal package, tuck-receipts, on its own package index. The lab has two indexes: private, the shop's, and public, standing in for an index anyone can upload to.
First write the script that builds a small package, in two parts. Its only code prints a sentence.
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 the shop's own package
docker exec ci python3 pkg.py private tuck-receipts 1.0.0 "tuck-receipts 1.0.0, the shop's own"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Start the two 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.
Ask the private index alone
docker exec ci pip install --no-cache-dir --dry-run --index-url http://127.0.0.1:8100/private/simple/ tuck-receiptsShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionspip takes the highest version anywhere
Many teams point pip at the public index and add their own with --extra-index-url. pip then searches both and takes the highest version it finds, from either.
Publish tuck-receipts 99.0.0 on the public index, as an attacker would, and ask again.
Publish a higher version publicly
docker exec ci python3 pkg.py public tuck-receipts 99.0.0 "tuck-receipts 99.0.0 from the public index: this could have been any code"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Ask both indexes, as many teams do
docker exec ci pip install --no-cache-dir --dry-run --index-url http://127.0.0.1:8100/public/simple/ --extra-index-url http://127.0.0.1:8100/private/simple/ tuck-receiptsShown here, not run. Press Start lab to type it into your own lab’s terminal.
Install it and import it
docker exec ci pip install --no-cache-dir -q --user --index-url http://127.0.0.1:8100/public/simple/ --extra-index-url http://127.0.0.1:8100/private/simple/ tuck-receipts && docker exec ci python3 -c "import tuck_receipts"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Try it: how pip chooses
indexes = {
"public": {"tuck-receipts": ["99.0.0"], "requests": ["2.33.0"]},
"private": {"tuck-receipts": ["1.0.0"]},
}
def as_numbers(version):
return tuple(int(part) for part in version.split("."))
found = [(as_numbers(v), v, name) for name, index in indexes.items()
for v in index.get("tuck-receipts", [])]
print("pip takes:", max(found)[1:])
# Change the public version to "0.0.1" and press Run. Which index wins now?
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsA common mistake
Warning
Many people think adding their own index makes pip prefer it. pip treats every index as equal and takes the highest version. Only a tool told to stop at the first index that has the name, or a single index, keeps an internal package safe.
One index, or the first one wins
The strongest fix is a single index: your own, which also mirrors the public packages you approve. Then a public name never reaches the build.
uv searches indexes in order and stops at the first that has the name. Claim your internal names on the public index too, and lock hashes, as lesson 6 shows.
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.
Resolve with uv's default strategy
docker exec -i ci .local/bin/uv pip compile - --no-cache --quiet --no-header --index-url http://127.0.0.1:8100/public/simple/ --extra-index-url http://127.0.0.1:8100/private/simple/ <<< tuck-receiptsShown here, not run. Press Start lab to type it into your own lab’s terminal.
Resolve the way pip does
docker exec -i ci .local/bin/uv pip compile - --no-cache --quiet --no-header --index-strategy unsafe-best-match --index-url http://127.0.0.1:8100/public/simple/ --extra-index-url http://127.0.0.1:8100/private/simple/ <<< tuck-receiptsShown here, not run. Press Start lab to type it into your own lab’s terminal.
Detect it: where did each package come from?
docker exec ci pip install --no-cache-dir --dry-run --ignore-installed --quiet --report - --index-url http://127.0.0.1:8100/public/simple/ --extra-index-url http://127.0.0.1:8100/private/simple/ tuck-receipts | grep -o '"url": "[^"]*"'Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Assignment: choose like an installer
An index is a dictionary from a package name to a list of versions, such as {"tuck-receipts": ["1.0.0"]}. Write three functions.
normalise(name) lowers a name and turns every run of -, _ and . into one -, as package indexes do, so Tuck_Receipts becomes tuck-receipts. choose(indexes, name, strategy) takes a list of (index_name, index) pairs in search order and returns (index_name, version): with strategy "best" the highest version in any index, as pip does; with "first" the highest version in the first index that has the name, as uv does. Compare versions as numbers, match names after normalise, and return None when no index has it. at_risk(internal, public) returns the sorted, normalised internal names that also appear in the public index.
def normalise(name):
return name
def choose(indexes, name, strategy):
return None
def at_risk(internal, public):
return []
Make a free account to save your work and track your progress.
Exit quiz
Have a go