Sub topic 9
Verify suggested packages before installing them
An assistant can suggest pip install for a package that does not exist. It can also suggest one whose name is close to a real package. This chapter assumes you can run pip, read a requirements.txt, and use Python's standard library. Earlier chapters covered symbols that do not exist. This one covers whole packages that do not exist.
Why a wrong package name is dangerous
If a suggested name does not exist, pip install fails with "No matching distribution found". That is the harmless outcome.
The risky outcome is that someone has registered the name. Attackers can publish packages under names that models tend to invent, or under misspellings of popular libraries. This is sometimes called slopsquatting, or typosquatting when the name is a typo. Installing such a package can run attacker code, because a source distribution may execute code at install time.
Three cases to tell apart:
| Case | Example | What you see |
|---|---|---|
| Invented name | `requests-json-helper` | 404 on the index, or a package you have never heard of |
| Look-alike name | `reqeusts` | Exists, but is not the library you intended |
| Right library, wrong install name | `pip install sklearn` | The import name differs from the distribution name (`scikit-learn`) |
A verification routine
Do this before you install anything an assistant suggests.
- Find the install command in the library's own documentation, not only in the assistant's answer.
- Look the name up on the package index and compare the project links with the official repository.
- Check the history: first upload date, number of releases, and maintainers.
- Pin the exact version you reviewed.
Check the index from a script
PyPI publishes metadata as JSON at https://pypi.org/pypi/<name>/json. This script reads it and prints the facts that matter. It uses only the standard library.
import json
import sys
import urllib.error
import urllib.request
def pypi_info(name):
"""Return basic metadata for a PyPI project, or None if it does not exist."""
url = f"https://pypi.org/pypi/{name}/json"
try:
with urllib.request.urlopen(url, timeout=10) as resp:
data = json.load(resp)
except urllib.error.HTTPError as err:
if err.code == 404:
return None
raise
uploads = [
f["upload_time_iso_8601"]
for files in data["releases"].values()
for f in files
]
return {
"latest": data["info"]["version"],
"releases": len(data["releases"]),
"first_upload": min(uploads)[:10] if uploads else "unknown",
"home_page": data["info"].get("home_page")
or data["info"].get("project_urls"),
}
if __name__ == "__main__":
for package in sys.argv[1:]:
info = pypi_info(package)
print(package, "->", info if info else "NOT FOUND")Run it as python check_pkg.py requests reqeusts. The first name returns many releases and an old first upload date. The second may return nothing, or something with one release and a recent date.
A recent first upload and a handful of releases do not prove a package is malicious. They mean you should read the project page and its source repository before you trust it.
Catch look-alike names
Compare each new name with the dependencies you already trust. Names that are very similar but not identical deserve a second look.
import difflib
trusted = ["requests", "numpy", "pandas", "flask"]
suggested = "reqeusts"
matches = difflib.get_close_matches(suggested, trusted, n=3, cutoff=0.8)
if suggested not in trusted and matches:
print(f"{suggested!r} looks like {matches}. Check the spelling.")Pin what you reviewed
After you approve a package, lock the version and its file hashes so a later upload under the same name cannot replace it. pip-tools can generate the hashes, and pip can enforce them.
pip install pip-tools
pip-compile --generate-hashes requirements.in -o requirements.txt
pip install --require-hashes -r requirements.txtWith --require-hashes, pip refuses any file whose hash is not listed. Review changes to requirements.txt in code review the same way you review code.
Exercise
An assistant tells you to run pip install fastjson-utils for a JSON task. The index lookup shows the package exists, with one release uploaded last week and no link to a source repository. Do you install it? What do you do next?
Show answer
Do not install it yet. Existence on the index only rules out an invented name. A single, very recent release with no source link is a warning sign for a squatted or malicious package. Check the documentation of the library you are using for the official install command, and see whether the standard library (json) or a well-known package already does the job. If you still want this package, read its source and publisher first, then pin the exact version and hashes.
Exercise
Why does pip install --require-hashes help after you have already verified a package?
Show answer
It makes pip install only files whose hashes you recorded during review. If someone later publishes a different file under the same name and version, or a new version appears, the install fails instead of silently using it.