Reading width
Wide uses the full column for everything, text, diagrams, code, and exercises. Narrow keeps the standard reading width.
Text size
Scales the body text. Headings and code blocks keep their size.
In this section
0.8 Software Supply Chain Basics
Introduction
Every piece of code an assistant writes comes with assumptions about what it can import, and when the code is run, those assumptions become installs. Module 8 builds a gate for AI-written code: dependency checks, detection of packages that do not exist or only look like ones that do, and checks on the provenance of the models the code loads.
This lesson lays the foundation: what a dependency list commits you to, what can go wrong with each line, and why the check has to happen before anything is installed.
An assistant writes the gate to a contract and runs it against a requirements file drafted for a threat intelligence collector, with five problems planted in eight lines. Two shortcuts are measured against it, and the lesson ends with the other half of the AI supply chain: a model file that runs code the moment it is loaded.
An assistant can name a package that does not exist or is one letter off a popular one, and an attacker can publish under that name. The gate sits between the list and the install.
Eight Lines, Five Problems
Read the names before installing themHere is the dependency list. Read each name as if you were about to install it.
1# requirements.txt for the lab's threat-intel collector, drafted with an assistant2requests==2.32.4 --hash=sha256:d337b22bd91bcd49afe5f8b1e45b260e54a7ac344a8398f6e9eee12dbef24aaf3urllib3==2.5.0 --hash=sha256:be17de7e4287bf2bc042d61f0b9ed369b530c396c72cbe42c4cb7a256c7e56794pyyaml==6.0.2 --hash=sha256:2fe71ad9f4ac236f1bbf924ac16bbb42e24e2db63f897b159dc99d6161d055895numpy6jinja2==3.1.6 --hash=sha256:0b250921f39021dd9c1f482192104bef781a45f8a2e76462d591a4fc747692027reqeusts==2.32.4 --hash=sha256:b31f6838728996d00e01aea3dfaa50b77d09e3b5ac84a95bae28255d21d99b538flask-stix-taxii-bridge==0.4.19flask==3.1.2 --hash=sha256:fb9dd7aa760dbcc18e4e1bea7469f1f9976511bb0e42e736d581a877151f8e4a
Most of it is ordinary: well-known packages, each pinned to a version and a hash.
Four lines are not. numpy has no version and no hash, so whatever release is current on the day of install is what arrives. reqeusts is one transposed letter away from requests. flask-stix-taxii-bridge sounds exactly like a package a threat intelligence collector would need. And the pyyaml line looks correct; the problem in it is only visible against the index.
The eight lines are also only the start. Each package declares its own dependencies, which declare theirs, and an install resolves the whole tree. A list of eight direct dependencies commonly becomes dozens of installed packages, every one of which runs on the machine and every one of which could be the compromised one.
A gate that checks only the lines a person wrote misses most of what is installed. The practical answer is to resolve the tree once, record every package with its exact version and hash, and gate that complete list, which is what a lockfile is.
Assistants produce lists like this one routinely, and a study of package hallucination measured how often the names are invented. Researchers tested sixteen code-generating models on 576,000 code samples and found hallucinated packages in at least 5.2 percent of cases for commercial models and 21.7 percent for open-source ones, with 205,474 unique invented names.
The study is due to appear at the 2025 USENIX Security Symposium. A name that does not exist is harmless until someone registers it, and an invented name that recurs is an obvious one to register. Registering package names that assistants are likely to invent has been given the name slopsquatting; registering names that people are likely to mistype is typosquatting, and reqeusts is an example.
The two attacks reach different victims through the same door. A typosquat waits for a person's slip on a keyboard; a slopsquat waits for an assistant's confident suggestion that a person accepts without checking. The second is the newer risk and scales with how much code is drafted by assistants, because the invented name arrives already typed, in a file that looks finished, inside code that otherwise works.
Why Before Install
Installing is runningThe gate's contract has one rule that shapes everything else: nothing is fetched, imported or installed to check it. That rule exists because installing a package is running its code.
Python packages built from source can run arbitrary code during installation, and importing any package runs its top-level code, with the permissions of whoever ran the install, on a machine that usually holds credentials, source code and access to other systems. A check that installs a package to see whether it is safe has already lost.
So the gate works from metadata. The lab's index stands in for the package registry: for each package, its versions with the hash of each release file, when it was first published, and how often it has been downloaded recently. Real registries publish the same kinds of information. Everything the gate decides, it decides from that.
The metadata deserves only as much trust as its source. Publication dates and file hashes come from the registry and are hard for a package's author to fake. Download counts are easier to inflate, with scripts that fetch a package repeatedly, and a squatter who wants to look established can buy some apparent popularity.
That is why the gate uses downloads only in its report, as context for the reviewer, and decides look-alikes on name distance and age, the two signals an attacker controls least.
⋯ 16 lines folded17 name==version --hash=sha256:<hex> (the version and the hash are each optional)18 Names compare case-insensitively.19 'not in index' the name does not exist in the index (the package may have been hallucinated)20 'look-alike' the name exists, is not in POPULAR, is within edit distance 2 of a POPULAR name, and was first21 published fewer than 90 days before today (an ISO date string)22 'unpinned' no ==version23 'unknown version' the version is not one the index has24 'no hash' no --hash25 'hash mismatch' the hash is not the index's hash for that version26 A package can have more than one finding. Report nothing for a line with no problem.27"""2829POPULAR = {'requests', 'urllib3', 'pyyaml', 'numpy', 'jinja2', 'flask'}30PROBLEMS = ('not in index', 'look-alike', 'unpinned', 'unknown version', 'no hash', 'hash mismatch')3132⋯ 2 lines folded
Six problems, each with a precise definition. A name not in the index may have been hallucinated. A look-alike must be both close to a popular name and recently published, because closeness alone flags legitimate packages and newness alone flags every new project.
Unpinned means no version; an unknown version is one the index has never seen. No hash means nothing ties the line to one file; a hash mismatch means the file has changed.
Run the check against the file as shipped.
$ python3 -m lab check f08
f08 0.8 Software Supply Chain Basics: lab/foundations/supply.py
FAIL audit() is written
lesson 0.8: write audit
FAIL
Once audit exists, the check runs it against the planted file and expects exactly the planted findings: each one present, and nothing reported for the clean lines.
It then runs two smaller tests, the same look-alike checked at a later date when it would no longer be new, and a correctly named package with a version the index has never seen, written in capitals, to confirm names are compared without regard to case.
Before the brief, here is the procedure the contract describes, drawn as the steps and decisions the code has to make.
Every requirement line is read against the package index before anything is installed. A line can collect more than one finding; only a name missing from the index ends its checks.
Keep it open while reading the draft: each decision in the diagram should appear as a condition in the code, and each side branch as a case the check can test.
Session: The Brief
Never run what you are checkingThe brief points at the contract and the data, and adds the constraint that matters.
Write audit() in supply.py to the contract in its docstring, standard library only. It runs before anything is installed, so it must never fetch, import or execute a package to check it: the index file is the only source. Write the edit distance yourself rather than adding a dependency.
An assistant asked whether a package exists may reasonably suggest checking by installing it, or by importing it in a try block. The brief rules both out: the index file is the only source. It also asks for the edit distance to be written in the file rather than imported, for a reason that is easy to miss.
A dependency gate that adds a dependency to do its job has added exactly the kind of risk it exists to catch, and the algorithm is a dozen lines.
There is a lesson here for working with assistants beyond this exercise. When an assistant proposes a package, it is making a factual claim, that a package of that name exists and does what the code needs, and the claim deserves the same checking as any other.
Asking the assistant to confirm does not help, because the same process that invented the name can confirm it. The check is against the registry: does the name exist, who publishes it, how long has it existed, how widely is it used. That takes a minute per package and is the cheapest step in the whole supply chain.
The Draft
Parse, look up, compareThe reply was the file. Here is the code below the docstring.
29import re30from datetime import date3132POPULAR = {'requests', 'urllib3', 'pyyaml', 'numpy', 'jinja2', 'flask'}33PROBLEMS = ('not in index', 'look-alike', 'unpinned', 'unknown version', 'no hash', 'hash mismatch')34LINE = re.compile(r'^\s*([A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:==\s*([^\s]+))?\s*(?:--hash=sha256:([0-9a-fA-F]+))?\s*$')353637def _distance(a, b):38 prev = list(range(len(b) + 1))39 for i, ca in enumerate(a, 1):40 cur = [i]41 for j, cb in enumerate(b, 1):42 cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))43 prev = cur44 return prev[-1]454647def audit(requirements_text, index, today):48 idx = {k.lower(): v for k, v in index.items()}49 now = date.fromisoformat(today)50 findings = []5152 def add(name, problem, detail):53 findings.append({'package': name, 'problem': problem, 'detail': detail})5455 for raw in requirements_text.splitlines():56 line = raw.strip()57 if not line or line.startswith('#'):58 continue59 m = LINE.match(line)60 if not m:61 add(line, 'not in index', 'line does not parse as a requirement')62 continue63 name, version, digest = m.group(1).lower(), m.group(2), m.group(3)64 entry = idx.get(name)65 if entry is None:66 add(name, 'not in index', 'no package of this name exists in the index')67 elif name not in POPULAR:68 near = [p for p in POPULAR if _distance(name, p) <= 2]69 age = (now - date.fromisoformat(entry['first_published'])).days70 if near and age < 90:71 add(name, 'look-alike', f"{_distance(name, near[0])} edits from {near[0]}, first published {age} days ago")72 if version is None:73 add(name, 'unpinned', 'no ==version: any release may be installed')74 elif entry is not None and version not in entry['versions']:75 add(name, 'unknown version', f'{version} is not a release in the index')76 if digest is None:77 add(name, 'no hash', 'nothing ties the requirement to one file')78 elif entry is not None and version in entry.get('versions', {}) and digest.lower() != entry['versions'][version]:79 add(name, 'hash mismatch', f'{version} in the index has a different sha256')80 return findings
Each line is parsed with one regular expression into a name, an optional version and an optional hash, and the name is lower-cased. A name missing from the index is reported.
A name present but not popular is compared with every popular name by edit distance, the number of single-character insertions, deletions and substitutions that turn one into the other, and flagged only if it is within two edits and was first published fewer than ninety days ago. The version and hash are then checked against the index's record for that release.
The lab's requirement format is a simplified version of the real one, and the draft's single regular expression is enough for it and not for production. Real requirement files allow extras in square brackets, environment markers, several hashes per line for different platforms' files, line continuations, and comments after a requirement.
A production gate reads them with the installer's own parsing library, not a hand-written pattern, so that the gate and the installer can never disagree about what a line means. A gate that parses differently from the installer can be passed by a line written to be read two ways.
Where the gate runs matters as much as what it checks. On a developer's machine before the first install, it stops a bad package before it runs anywhere. In the build pipeline, on every change to a dependency file, it stops one that slipped past.
At install time in production, it confirms that what is about to run is what was reviewed. Module 8 runs it in all three places, from the same code and the same allowlist, so that a package cannot be acceptable in one and blocked in another.
Run the check against the draft.
$ cp records/supply-0.8.py lab/foundations/supply.py
$ python3 -m lab check f08
f08 0.8 Software Supply Chain Basics: lab/foundations/supply.py
ok finds flask-stix-taxii-bridge: no hash
ok finds flask-stix-taxii-bridge: not in index
ok finds numpy: no hash
ok finds numpy: unpinned
ok finds pyyaml: hash mismatch
ok finds reqeusts: look-alike
ok reports nothing for clean lines
none
ok a look-alike published long ago is not flagged as new
ok names compare case-insensitively; an unknown version is caught
no hash, unknown version
PASS
Every planted problem is found, including one that is easy to overlook: flask-stix-taxii-bridge has no hash as well as no index entry, and the contract says a package can have more than one finding. Here is the gate's report as a reviewer would read it.
$ cp records/supply-0.8.py lab/foundations/supply.py
$ python3 audit.py
pyyaml hash mismatch 6.0.2 in the index has a different
sha256
numpy unpinned no ==version: any release may be
installed
numpy no hash nothing ties the requirement to one
file
reqeusts look-alike 2 edits from requests, first published
16 days ago
flask-stix-taxii-bridge not in index no package of this name exists in the
index
flask-stix-taxii-bridge no hash nothing ties the requirement to one
file
Each finding names the package, the problem and the evidence: how many edits separate the look-alike from what it imitates and how recently it appeared, which version's hash differs, which line ties nothing to a file. The report is what a pull request comment or a build failure should say, because a developer who sees only the word blocked tends to work around the gate rather than fix the line.
Pinned Is Not Fixed, Measured
A version without a hashA common belief is that pinning a version makes an install repeatable. Here is the draft with the hash comparison removed: versions must exist, but the file behind them is trusted.
77 add(name, 'no hash', 'nothing ties the requirement to one file')- elif entry is not None and version in entry.get('versions', {}) and digest.lower() != entry['versions'][version]:- add(name, 'hash mismatch', f'{version} in the index has a different sha256')78 return findings
Run the check and read the pyyaml line.
$ cp records/supply-nohash.py lab/foundations/supply.py
$ python3 -m lab check f08 | grep -A1 "pyyaml"
FAIL finds pyyaml: hash mismatch
ok finds reqeusts: look-alike
pyyaml passes, and nothing in the check's output suggests anything was wrong with that line: the gate that skipped the comparison reported the remaining problems normally and simply never looked. The line names a real version of a real package, and the hash it records no longer matches the file the index holds for that version.
A version is a label; the file behind it is whatever the registry, a mirror or a proxy serves on the day of install. A hash ties the line to one exact file, so a replaced, corrupted or substituted file fails the install instead of running. Python's installer can enforce hashes for every requirement in a file, and a gate should require them for anything that reaches a build.
Files change behind versions in several ways: a maintainer's account is taken over and a release is replaced or a new one published, an internal mirror is poisoned, a proxy in the build path serves something else.
A hash protects against all of them from the moment it is recorded. It does not prove the file was good when the hash was taken; it proves the file is the same one. That is why hashes are recorded once, at a review, and changed only in a reviewed commit, so that every change to what is installed passes through a person.
Real Is Not Safe, Measured
A package that existsThe second shortcut accepts any package the index knows. If it exists, it is real; if it is real, it is fine. Here is that version.
69 age = (now - date.fromisoformat(entry['first_published'])).days- if near and age < 90:70+ if False: # it is in the index, so it is a real package71 add(name, 'look-alike', f"{_distance(name, near[0])} edits from {near[0]}, first published {age} days ago")
Run the check and read the reqeusts line.
$ cp records/supply-exists.py lab/foundations/supply.py
$ python3 -m lab check f08 | grep -A1 "reqeusts"
FAIL finds reqeusts: look-alike
ok reports nothing for clean lines
reqeusts passes. It is in the index, with a version and a matching hash; everything about the line is correct except the package itself, which appeared sixteen days before the check date, has been downloaded a few hundred times in a month, and is two letters from one of the most widely used HTTP libraries in Python.
Existence was never the question. A typosquat exists by design, and so does a hallucinated name once someone registers it. A hallucinated name also changes over time in a way the gate has to allow for.
On the day an assistant suggests it, the name may not exist, and the gate reports it as not in the index; a developer who decides to deal with it later may find, a month on, that the name now exists, registered by someone who noticed it being suggested.
The gate must run again at install time against the registry as it is then, because a not-in-index finding is only true on the day it was made. The signals that separate them from legitimate packages are the ones the gate reads together: closeness to a popular name, a short history, and an audience far smaller than the package it imitates.
The same signals flag legitimate packages too. A new library from a well-known team can be young, small and close in name to something popular. A gate that blocks on these signals needs an exception path: a person reviews the package, records why it is acceptable, and adds it to an allowlist that the gate reads.
The exception is a decision with a name on it, which is the difference between a gate that is used and one that is bypassed the first time it blocks something a developer needs.
Models Are Dependencies Too
A file that runs code when loadedAI-written code does not only import packages; it loads models, and model files are a supply chain of their own. Many are saved with Python's pickle format, and loading a pickle can run code. This script saves an object that looks like a model and then loads it.
$ python3 pickle_demo.py
wrote detector.pkl, 84 bytes
loading it:
code ran while the model file was loading
Loading the file ran a command. The command here only prints a line; the same mechanism could read credentials, open a connection or install something else. Pickle rebuilds objects by calling functions the file names, and a file can name any function, including one that runs a shell command.
Nothing about the file's name or size says so. A model downloaded from a public hub and loaded with a pickle-based loader is code from that hub running on your machine, whatever the model card says.
A model card is the model's own description of itself, written by whoever uploaded it, and it is a claim like any package's README.
The facts worth checking are the ones the hosting platform records: which account published the model and how long it has existed, which exact revision you downloaded, and whether the file's hash matches the one you recorded when you tested it. A model renamed to resemble a well-known one is a typosquat in a new place.
The defenses follow the same pattern as packages. Prefer formats designed to hold only numbers and metadata, such as safetensors, over formats that can carry code.
Pin a model to an exact revision and record its hash, so the file you tested is the file you load. And treat a model's source the way a package's is treated: who published it, how long it has existed, and whether the name is the one you meant. Module 8 adds model files to the gate.
Scanning a pickle for dangerous calls before loading it helps and is not a guarantee, because the format can reach almost any function and scanners look for known patterns.
When a pickle-based model must be loaded, the safer course is to load it once in an isolated environment with no credentials and no network, convert it to a code-free format, and use the converted file from then on. The model's weights are numbers; nothing a legitimate model needs requires running code at load time.
From the Gate to Module 8
What the review carries forwardThe session record keeps what held, the measurements, and the two decisions the gate made without evidence.
1# Session 0.8: a dependency gate23Assistant: Claude Opus 5.5 (claude-opus-5-5), the SEC410 build session, 2026-11-1845## Held6- One regular expression per line; the index is the only source.7- Edit distance written in the file: no new dependency.8- Look-alikes need both: near a popular name, and new.9- check f08: PASS. Nothing fetched, imported or installed.1011## Measured12- Pinned without a hash check: pyyaml's changed file passed.13- Existence taken as legitimacy: reqeusts passed, a 412-download14 package published 16 days ago, two letters from requests.15- A pickled "model" ran a command when it was loaded.1617## For Module 818- The 90-day window and distance 2 are guesses; measure them.19- Model files are not checked here at all.
The ninety-day window and the two-edit distance are guesses, reasonable for a foundation exercise and unmeasured. Too wide, and the gate flags legitimate young packages until developers stop reading it; too narrow, and a squatter who waits three months walks through.
Module 8 measures both against a larger index with known squats and known legitimate look-alikes, and adds the check this lesson leaves out: the model files the code loads, by format, revision and hash.
Module 8's gate also writes down what passed it. A software bill of materials, an SBOM, lists every component in a build with its version and origin, and it is what makes the next question answerable: when a vulnerability or a malicious release is announced in some package, which of your builds contain it.
A gate that checks dependencies and records the result in a standard form turns that question from a search through every project into a lookup.
Practice
A dependency gate the labBrief your assistant with the contract and the no-execution rule, check the draft, reproduce both shortcuts, then ask your assistant for a requirements file of its own and check every name it gives you.
1# Practice 0.8: a dependency gate23## Done when4- [ ] lab/foundations/supply.py meets its docstring's contract5- [ ] python -m lab check f08 prints PASS6- [ ] both shortcuts reproduced; what each let through recorded7- [ ] ask your assistant for a requirements file for a task of8 your own; run the gate's logic on it by hand and record9 every name you could not confirm exists10- [ ] records/0.8-<assistant>.md: brief, draft, runs, review1112## Constraints13- Nothing is installed, imported or fetched to check it.1415## Stretch16- Flag model files saved in a pickle-based format, and record17 which formats you allowed instead and why.
A dependency list is a list of code that will run on your machine, and it has to be checked before installation, from registry metadata alone. Assistants invent package names at measurable rates, and squatters register names people and assistants are likely to type.
A gate catches names that do not exist, look-alikes that are both close and new, unpinned lines, unknown versions and files whose hashes changed. Pinning without a hash trusted a changed file; existence without history trusted a typosquat. Model files are dependencies too, and a pickled one ran code on load.