Wheel SBOMs and PEP 770 embedding¶
See also: Command line for every other subcommand and the common flags, Hatchling build hook and GitHub Action for embedding at build time or in CI, and From Python for the same operations from code.
Commands that read or rewrite built .whl files: loom wheel,
embed-wheel, verify-wheel and validate-wheel.
Embed an SBOM (embed-wheel)¶
Generate an SPDX 3 SBOM and embed it in one or more built wheels, writing to
.dist-info/sboms/ and updating .dist-info/RECORD:
loom embed-wheel dist/*.whl --project-dir .
--project-dir rescans the source project so the SBOM carries project
metadata (dependencies, licence, AI models). It is never inferred from the
current directory, even when the shell sits in the project root: that
directory may not be the wheel's own project. With it, the file list and
hashes still come from the wheel itself, so they are accurate for any build
backend. Only --content-type and --extract-file-header can be affected by
the Source SBOM limitation, for a backend on the
Hatchling-based fallback: that per-file enrichment can silently fail to
attach (no data for a file, never wrong data).
Without --project-dir (and without --sbom), embed-wheel embeds a
standalone-wheel SBOM built from the wheel's own contents: no project scan,
so no AI-model enrichment and no [tool.pitloom] beyond an explicit
--config (run in a directory holding a pyproject.toml, it says so with one
INFO:,
option-missing/project-dir).
AI models inside the wheel are still found (see --scan-model-usage):
loom embed-wheel dist/mypackage-1.0.0-py3-none-any.whl
Or embed an existing SBOM:
loom embed-wheel dist/*.whl --sbom sbom.spdx3.json
The SBOM's declared subject name/version (PEP 503/440-normalised) is checked
against the wheel's own .dist-info/METADATA before anything is written. A
mismatch is an ERROR: that aborts the embed (exit 1, nothing written);
--allow-mismatch downgrades it to a WARNING: and embeds anyway (for
best-effort CI). A Pitloom-generated SBOM (no --sbom) is never checked: it
is built from the same metadata. An external SBOM is embedded verbatim, byte
for byte (line endings included; -o writes the same bytes), and may list
.dist-info files. It must be a regular file of at most 50 MiB: a
directory, FIFO or device is [input-not-found] and a larger file
[over-cap]. It must be UTF-8: other bytes (UTF-16 and UTF-32 included)
are an ERROR:, and a UTF-8 byte order mark is dropped with a WARNING:
(RFC 8259 section 8.1: FILE=<file>: SBOM starts with a byte order mark,
which JSON text must not have; dropped [json-malformed/bom]).
loom id import refuses these files with the same codes and drops a byte
order mark with the same WARNING:. A file that is not valid JSON (an empty
one included) or not a JSON object
(FILE=<file>: not valid JSON for the SBOM; <failure> [json-malformed]), or
named .spdx3.json but not SPDX 3 JSON-LD (a CycloneDX file, say:
FILE=<file>: named .spdx3.json but not SPDX 3 JSON-LD [sbom-wrong-format]),
or whose @graph is not a list of objects
(FILE=<file>: SBOM @graph is not a list [sbom-invalid], with or without
--validate) is an ERROR: and exit 1, and no wheel is written. So is one
that spdx3-validate refuses: each of its findings is one
ERROR: spdx3-validate: <line> line, then one coded line ends the run
(FILE=<file>: SBOM is not valid; no wheel was written [sbom-invalid]). A JSON
object in another format under another name is embedded, with a WARNING:
that its name and version cannot be cross-checked
(wheel-sbom-unusable).
The file is stored as <basename>.spdx3.json whatever it is called or holds.
An external SBOM is also checked for a credential in a URL field: it is
embedded unchanged, with a WARNING: per value, or, with
--refuse-url-credentials, refused (exit 1, no wheel written) unless
--accept-url-credential accepts it; a [tool.pitloom] setting does not apply
to a file Pitloom did not make. See
Credentials in URLs.
Embedding again replaces an earlier SBOM only when Pitloom made it, it is a
build or analyzed SBOM (software_sbomType), and it is of the same name and
version as the wheel. Any other .dist-info/sboms/*.spdx3.json made by Pitloom
stays, with one WARNING: naming it. This includes the build SBOM the
Hatchling hook embedded: embedding an external --sbom replaces it.
Or use --embed on loom wheel:
loom wheel dist/mypackage-1.0.0-py3-none-any.whl --embed
It embeds the same kind of SBOM as embed-wheel: RFC 8785 canonical JSON, no
relationship descriptions, no registry update. So --pretty,
--describe-relationship and --update-id-registry warn and have no effect,
and -o FILE writes a copy of exactly what was embedded.
Other flags:
--sbom-basename NAMEsets the embedded file's basename. A trailing.spdx3.jsonis optional and dropped with aWARNING:. A path (a/,\,:or NUL) is anoption-invalidERROR:, raised before the SBOM is generated (exit 1, nothing written). The default is<name>-<version>.spdx3.jsonfrom the wheel's own name/version, with a control character, whitespace,/,\or:becoming_; with no name or version inMETADATA, or a name over 255 characters, the wheel's.dist-infodirectory name (escaped the same way) is used.-o/--output FILEalso writes a copy of the embedded SBOM to FILE and printsPITLOOM_SBOM_OUTPUT_PATH=<FILE>; it is anERROR:with more than one wheel (ambiguous). Each wheel is always modified in place.--verify/--validaterun the checks below on the wheel just embedded. A failure is reported and sets the exit code, but the embed is not rolled back. With--sbom FILE --validate, an SPDX 3 file is validated first: one that fails is refused (ERROR:, exit 1) and the wheel is not written. A file in a format with no validator is embedded, with aWARNING:.
loom embed-wheel dist/*.whl --project-dir . --verify --validate
What an SBOM lists¶
Every wheel-reading command (loom wheel, generate <whl>, embed-wheel,
wheel --embed) lists the wheel's payload only: nothing under the wheel's own
.dist-info (METADATA, WHEEL, RECORD, licenses/, sboms/,
signatures). An SBOM describes the packaged project, not its container, so a
listed hash never goes stale when the embed rewrites RECORD and adds
sboms/. The Hatchling hook and loom project list no
.dist-info/licenses/* file either.
A wheel's own .dist-info is the top-level directory its file name names
(PEP 503/440 comparison). Where the file name names none, it is the only
top-level .dist-info, with a WARNING: if the file name is a wheel name. A
.dist-info vendored deeper in the tree is never the wheel's own. With none,
or several not picked out by the file name, loom wheel and loom generate
warn and name the package unknown; wheel --embed, embed-wheel,
verify-wheel and validate-wheel refuse the wheel. METADATA is read for
its headers only (at most 16 MiB and 10,000 headers); past a cap, one
WARNING: per command and the name is unknown. That placeholder is not
looked up in or recorded into an ID registry: the package gets a per-document
id and, with a registry declared, one INFO: says so (once per
embed-wheel batch). The same holds for wheel --embed and embed-wheel,
with or without --project-dir. The ids of an
unidentified wheel depend on its base file name (as given, no case folding,
the same on every OS) as well as its payload: the same file name and bytes
give the same SBOM, two such wheels with one payload but different file names
get different ids, and a renamed copy gets new ids.
Authors. A wheel's METADATA does not keep [project].authors as
declared. Backends write a name-only author into the free-text Author
field, so authors with an email address are read first, then name-only
ones; several name-only authors joined in one Author read as one author
(an INFO: says it may list several when it holds ,, ; or and,
author-ambiguous);
a name-only author beside a single email-only one reads as one author, but
one beside two read as three (never paired by position); and poetry-core
writes only the first author. With embed-wheel --project-dir (and the
GitHub Action) the project's declared authors are used instead, with no
WARNING: for the wheel's split Author or Author-email (one for a
split in the project's own free-text author or author_email,
--config or not); when the project's name differs from the wheel's, a
WARNING: says so and the wheel's authors are kept
(metadata-conflict), as they
are when the project's metadata cannot be read
(project-unreadable).
How Author (cut only next to an address) and Author-email (split) are
read and what each author becomes: How authors are
read.
Dependencies. The wheel's Requires-Dist lines, extras included, become
the same packages and relationships as from a source directory; see Extras
and the optional edge.
Signed wheels¶
SECURITY: a wheel with a RECORD signature (RECORD.jws, RECORD.p7s)
is refused, and left untouched, by embed-wheel and wheel --embed: the
embed rewrites RECORD, so the signature would stop verifying
(wheel-unusable/signed).
--allow-signed-wheel removes the signature files and embeds (one
INFO: ARCHIVE='<archive>' ENTRY='<member>': signature removed; re-sign the
wheel [wheel-unusable/signed] per file); re-sign afterwards. Like
--allow-build, it has no [tool.pitloom]
equivalent: it is a per-run decision.
Pitloom sees only signatures inside the wheel. Any embed changes the wheel
file's own digest, so a signature or attestation over the file (detached GPG
.asc, Sigstore bundle, PEP 740 attestation) and a recorded wheel hash (lock
file, pip --hash) stop matching, and Pitloom cannot detect them. Embed
first, then sign, attest, upload and hash.
Refused archives¶
loom wheel, generate, wheel --embed and embed-wheel read every member.
They refuse a file that is not a ZIP, and a wheel with a member that cannot be
read (damaged, encrypted, a name that is not UTF-8:
wheel-unreadable), with one name
twice (also as a/M and a\M), or with a NUL in a name (zipfile cuts it
there, so an installer extracts it under another member's name:
wheel-invalid). wheel --embed and
embed-wheel also refuse a wheel whose own .dist-info has a non-conforming
member name
(wheel-unusable).
verify-wheel reads only the member names, the own .dist-info's METADATA
and the embedded SBOM; validate-wheel only the names and the embedded SBOM.
A damaged other member does not fail them, but a damaged member they read, a
duplicate or NUL name, or a file zipfile cannot open does.
Each refusal is one ERROR: naming the archive and, where there is one, the
member, and ending ; wheel refused and a [code], for example
ERROR: ARCHIVE='demo-1.0-py3-none-any.whl' ENTRY='demo/a.py': duplicate
member name; wheel refused [wheel-invalid]
(a command's own prefix, such as ERROR: loom wheel: ARCHIVE=..., comes
before the ARCHIVE=). Exit
1, nothing written (not even the -o copy). With several wheels the others are
still processed. The library raises WheelRefused, a ValueError that carries
the code.
A wheel's name and version come from its own top-level .dist-info. Where
there is none, or several and the file name picks none, loom wheel and
generate go on and name the wheel unknown
(WARNING: ARCHIVE='<archive>': no top-level .dist-info directory; identity
unknown [dist-info-missing]),
while embed-wheel, wheel --embed, verify-wheel and validate-wheel print
only the ERROR: (... wheel refused; also
dist-info-ambiguous). A file
name that names no top-level .dist-info, where exactly one other exists, is
read as that one, with a WARNING:
(dist-info-conflict).
A member that does not install where its name says is not a refusal. Pitloom
lists it under its install name
(WARNING: ARCHIVE='<archive>' ENTRY='<member>': non-conforming name; listed
as '<install-name>' [archive-member-invalid]),
or leaves it out of a wheel or sdist read with ; not listed
(WARNING: ARCHIVE='<archive>' ENTRY='<member>': no safe install location;
not listed [archive-member-unsafe],
or
archive-member-conflict),
and, on the --allow-build route, does not extract it from the built wheel:
; not copied instead.
Every wheel line ends with a [code] that a script or an agent can key on;
Message codes: Wheels and
Message codes: Embedded SBOMs list each line,
what it means and what Pitloom did.
Verify (verify-wheel)¶
Check that a wheel's embedded SBOM is at the PEP 770 location
(.dist-info/sboms/), uses its format's recommended extension, and declares a
subject name/version matching the wheel's own .dist-info/METADATA:
loom verify-wheel dist/*.whl
loom verify-wheel dist/mypackage-1.0.0-py3-none-any.whl --sbom-filename mypackage-1.0.0.spdx3.json
loom verify-wheel dist/*.whl --fail-on-mismatch
- A missing SBOM is an
ERROR:(exit 1,wheel-sbom-missing). - A non-conventional extension is a
WARNING:only (exit 0,wheel-sbom-wrong-format). - Several
sboms/entries need--sbom-filenameto pick one, elseERROR:(wheel-sbom-ambiguous). - A name/version mismatch is a
WARNING:(exit 0);--fail-on-mismatchmakes it anERROR:(exit 1,wheel-sbom-conflict). - If the subject name/version cannot be extracted at all (unsupported format,
or SPDX 3 with an unexpected graph shape), the cross-check is skipped with a
WARNING:naming why, regardless of--fail-on-mismatch(wheel-sbom-unusable). - A summary
INFO: verify-wheel: <number> wheel(s) OKcloses a run that found every wheel's SBOM; it carries no code.
Validate (validate-wheel)¶
Validate the embedded SBOM's content against its format's schema and SHACL
rules (SPDX 3 JSON-LD only, via the spdx3-validate library also behind
loom fragment validate; needs pip
install "pitloom[validate]"):
loom validate-wheel dist/*.whl
An embedded file in an unrecognised format prints a WARNING: and skips
validation (exit 0, STATUS=skipped): unsupported is not invalid. An invalid
SBOM prints each finding of spdx3-validate once, as
ERROR: spdx3-validate: <line>, then one coded
ERROR: FILE=<file>: not valid SPDX 3 (<number> finding(s) above) [sbom-invalid]
line (FILE= names the SBOM as <wheel>/<member>), and the wheel is reported
STATUS=failed; there is no empty ERROR: line.
Package hash¶
The package element's verifiedUsing holds a SHA-256 Merkle root over the
wheel's payload. What it covers follows the SBOM type:
- Analyzed (
loom wheel,generate <whl>,embed-wheelwithout a project directory,wheel --embed): the wheel as built. - Source (
loom project) and the Build SBOM of the Hatchling hook: the source files the build backend selects, hashed before the build. When the build adds payload of its own (shared data, scripts, generated or repaired files) the root differs from the built wheel's, as the two describe different things. - Build with
embed-wheel --project-dir: the wheel as built, so it can differ from the hook's root for the same wheel.
A wheel's <name>-<version>.data/ directory (PEP 427: files installed outside
site-packages, such as scripts/, data/ and headers/) is payload, not
packaging metadata. It is listed and hashed under its path in the wheel, e.g.
demo-1.0.data/data/share/demo/d.txt, not its install destination. The hook
and loom project cannot see it before the build, one reason their root
differs from the built wheel's.
To recompute the root of a built wheel:
- Take every wheel member except those under the wheel's own
.dist-info(the top-level directory its file name names, compared per PEP 503 names and PEP 440 versions). Another*.dist-infodeeper in the tree is payload. Directory entries are not members. - Name each by its install-location path (POSIX, normalised). A member name
that is not one (
\,./,//,.., an absolute path) is normalised (; listed as '<install-name>') or left out (; not listed) by Pitloom, each with aWARNING:(see Refused archives); the snippet below reads names as stored, so it reproduces the root of a conforming wheel only. - Sort by that path (Python
sorted, code-point order). - A leaf is the raw 32-byte SHA-256 of the member's bytes.
- Combine adjacent pairs as
sha256(left || right); an odd last node is promoted unchanged; repeat until one node remains. - The root is that node in lowercase hex. A single file's root is its own digest; an empty payload has no hash.
A wheel with no single own .dist-info has none to leave out: loom wheel
lists and hashes every member (with a WARNING:, identity unknown), and the
embed commands refuse it. SBOM
relationships and directory elements are not part of the root.
import hashlib
import zipfile
def package_hash(wheel: str, own_dist_info: str) -> str | None:
leaves = {}
with zipfile.ZipFile(wheel) as zf:
for name in zf.namelist():
if name.endswith("/") or name.split("/")[0] == own_dist_info:
continue
leaves[name] = hashlib.sha256(zf.read(name)).digest()
level = [leaves[name] for name in sorted(leaves)]
if not level:
return None
while len(level) > 1:
nxt = [
hashlib.sha256(level[i] + level[i + 1]).digest()
for i in range(0, len(level) - 1, 2)
]
if len(level) % 2:
nxt.append(level[-1])
level = nxt
return level[0].hex()
print(package_hash("pkg-1.0-py3-none-any.whl", "pkg-1.0.dist-info"))
From Python¶
Programmatic PEP 770 post-build wheel injection. Exact signatures: API reference.
from pathlib import Path
from pitloom.assemble import ConfigOverrides, embed_sbom_in_wheel, embed_wheel_sbom
# 1. Generate and embed SBOM in one step
modified_wheel, arcname, sbom_json, removed, floored = embed_wheel_sbom(
wheel_path=Path("dist/mypackage-1.0.0-py3-none-any.whl"),
project_dir=Path("."),
overrides=ConfigOverrides(offline=True), # optional
# ConfigOverrides also accepts build_options=BuildOptions(...) (no
# [tool.pitloom] equivalent) -- see [`--allow-build`](allow-build.md#from-python).
)
# 2. Or embed an externally-generated, pre-written SBOM file (checked)
modified_wheel, arcname, sbom_json, removed, floored = embed_wheel_sbom(
wheel_path=Path("dist/mypackage-1.0.0-py3-none-any.whl"),
sbom_path=Path("sbom.spdx3.json"),
allow_mismatch=False, # default: raise ValueError on a name/version mismatch
)
# 3. Or embed arbitrary pre-generated SBOM content (unchecked, lower-level)
modified_wheel, arcname, removed, floored = embed_sbom_in_wheel(
wheel_path=Path("dist/mypackage-1.0.0-py3-none-any.whl"),
sbom_content=sbom_json_string,
sbom_filename="custom.spdx3.json", # optional
)
removed lists any prior Pitloom-embedded SBOM entries cleaned up as part
of the embed; floored is True when the wheel's ZIP entry timestamp had
to be floored to 1980-01-01 (see Configuration).
With sbom_path= (form 2, the equivalent of the CLI's embed-wheel --sbom),
the SBOM's declared subject name/version (PEP 503/440-normalised) is
cross-checked against the wheel's own .dist-info/METADATA before
anything is written: a mismatch raises ValueError and nothing is
written (a name and a version both differing log the first as an ERROR:
and raise the last), unless allow_mismatch=True downgrades it to a
WARNING: log and lets the embed proceed. Form 1 (a Pitloom-generated SBOM)
is never checked -- it's built from the same wheel metadata, so it can't
diverge.
A Pitloom-generated SBOM lists the wheel's payload only (see
Wheel SBOMs). A wheel with a
RECORD signature (RECORD.jws, RECORD.p7s) raises WheelRefused (a
ValueError) and is left untouched, unless allow_signed_wheel=True removes
the signature the rewrite invalidates (the removed names are returned with any
stale SBOMs). Embed before
signing, attesting, uploading or hashing the wheel file.
A wheel's name and version come from its own top-level .dist-info (see
Wheel SBOMs). A wheel with one
of the problems below raises
pitloom.core.wheel_dist_info.WheelRefused, a ValueError whose message is
the ERROR: line without its tag and code, and whose pitloom_code
attribute is that code (wheel-unreadable,
wheel-invalid,
dist-info-missing,
dist-info-ambiguous,
wheel-unusable), naming the
archive (and the member, where one is at fault), and nothing is written:
- a member that cannot be read;
- two members with one name;
- a NUL in a member name;
- a file that is not a ZIP archive, or that
zipfilecannot open; - no single own
.dist-info; - (embed only) a member of its own
.dist-infounder a non-conforming name.
A wheel that is not there raises FileNotFoundError (input-not-found);
one under a directory Pitloom may not search raises ValueError
(file-unreadable) from the generate and embed functions, OSError from
read_wheel(); one whose own permissions refuse the open raises OSError.
Pass identity=(name, version) to embed_sbom_in_wheel() where
you have already read them from the wheel's METADATA: the default file
name is made from it and METADATA is not read, or warned about, again.
pitloom.extract.wheel.wheel_identity(metadata) gives that pair from the
ProjectMetadata of read_wheel(), or of generate_wheel_sbom_with_metadata()
(see Python API): None for a field the wheel did not declare.
Form 3, embed_sbom_in_wheel(), is the lower-level, unchecked archive
primitive both forms 1 and 2 converge on -- calling it directly (bypassing
embed_wheel_sbom()) skips the cross-check entirely, same as it skips
SBOM generation.
Batch embedding with EmbedFileCache¶
Embedding into several wheels from the same project_dir in a loop --
what the CLI's embed-wheel dist/*.whl --project-dir . does -- should
share one EmbedFileCache across the whole batch instead of calling
embed_wheel_sbom() per wheel with no cache: without it, each call
independently resolves project_dir's file list (and, with
--allow-build, reruns the real PEP 517 build) once per wheel instead of
once for the batch, and repeats each ineffective build flag's
WARNING: once per wheel.
from pathlib import Path
from pitloom.embed import EmbedFileCache, embed_wheel_sbom
wheels = [
Path("dist/mypackage-1.0.0-py3-none-any.whl"),
Path("dist/mypackage-1.0.0-py2-none-any.whl"),
]
with EmbedFileCache() as cache:
for wheel in wheels:
embed_wheel_sbom(
wheel_path=wheel,
project_dir=Path("."),
file_cache=cache,
)
EmbedFileCache must be used as a context manager around the whole
batch: it resolves project_dir's file list (and any --allow-build
build) once, on the batch's first call, and removes its temporary
directories on exit -- including on SIGTERM/SIGHUP or Ctrl-C, via the
same TerminationGuard the --allow-build docs describe. Every call
in one batch must use the same project_dir, file-scan settings and
build options -- a call that doesn't raises ValueError. Passing
file_cache= to embed_wheel_sbom() outside the with block raises
RuntimeError.
Advanced/batch use only -- a single embed_wheel_sbom() call needs no
file_cache and manages its own resolve-then-cleanup cycle.