Supply Chain Exercises
Each exercise is a small piece of the logic that SBOM tools, scanners and verifiers run, written as a pure function with the calls already in place. Run the starter first: it prints placeholder answers, which shows what the calls expect. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last exercise is a real cosign session to fix.
Exercise 1: Parse a package URL
Topics: What an SBOM Is
Split a purl into type, namespace, name, version and a dict of qualifiers. Decode %40 to @. A purl without a namespace has namespace = None.
def parse_purl(purl):
# TODO: strip "pkg:", split off "?qualifiers", then "@version", then type / namespace / name
return {"type": None, "namespace": None, "name": None, "version": None, "qualifiers": {}}
for p in ["pkg:npm/%40types/node@24.0.0",
"pkg:pypi/jinja2@2.11.2",
"pkg:apk/alpine/busybox@1.36.0-r9?arch=x86_64&distro=alpine-3.18.0"]:
print(parse_purl(p)){'type': None, 'namespace': None, 'name': None, 'version': None, 'qualifiers': {}}
{'type': None, 'namespace': None, 'name': None, 'version': None, 'qualifiers': {}}
{'type': None, 'namespace': None, 'name': None, 'version': None, 'qualifiers': {}}
Expected output:
{'type': 'npm', 'namespace': '@types', 'name': 'node', 'version': '24.0.0', 'qualifiers': {}}
{'type': 'pypi', 'namespace': None, 'name': 'jinja2', 'version': '2.11.2', 'qualifiers': {}}
{'type': 'apk', 'namespace': 'alpine', 'name': 'busybox', 'version': '1.36.0-r9', 'qualifiers': {'arch': 'x86_64', 'distro': 'alpine-3.18.0'}}Show solution
from urllib.parse import unquote
def parse_purl(purl):
rest = purl[len("pkg:"):]
rest, _, query = rest.partition("?")
qualifiers = dict(kv.split("=", 1) for kv in query.split("&")) if query else {}
rest, _, version = rest.rpartition("@")
parts = rest.split("/")
ptype, name = parts[0], unquote(parts[-1])
namespace = unquote("/".join(parts[1:-1])) if len(parts) > 2 else None
return {"type": ptype, "namespace": namespace, "name": name, "version": version or None, "qualifiers": qualifiers}rpartition("@") matters: the namespace %40types is encoded, but a version separator is always the last @.
Exercise 2: Diff two SBOMs
Topics: Converting & Querying SBOMs
Given two lists of purls (old and new release), report packages that were added, removed and changed version, by type/name.
OLD = ["pkg:npm/lodash@4.17.15", "pkg:npm/minimist@1.2.5", "pkg:npm/debug@4.3.4"]
NEW = ["pkg:npm/lodash@4.17.21", "pkg:npm/debug@4.3.4", "pkg:npm/left-pad@1.3.0"]
def sbom_diff(old, new):
# TODO: key by "type/name" (the part before @), compare versions
return {"added": [], "removed": [], "changed": []}
print(sbom_diff(OLD, NEW)){'added': [], 'removed': [], 'changed': []}
Expected output:
{'added': ['npm/left-pad@1.3.0'], 'removed': ['npm/minimist@1.2.5'], 'changed': ['npm/lodash 4.17.15 -> 4.17.21']}Show solution
def sbom_diff(old, new):
def index(purls):
return dict(p[len("pkg:"):].rsplit("@", 1) for p in purls)
a, b = index(old), index(new)
return {
"added": sorted(f"{k}@{b[k]}" for k in b.keys() - a.keys()),
"removed": sorted(f"{k}@{a[k]}" for k in a.keys() - b.keys()),
"changed": sorted(f"{k} {a[k]} -> {b[k]}" for k in a.keys() & b.keys() if a[k] != b[k]),
}Exercise 3: Apply VEX statements
Topics: VEX, Vulnerability Data
A scanner reports findings by its own id (here GHSA ids, with CVE aliases). Suppress a finding when a VEX statement with status not_affected names its id or one of its aliases for the same package purl. Statements with other statuses don't suppress anything.
findings = [
{"id": "GHSA-35jh-r3h4-6jhm", "aliases": ["CVE-2021-23337"], "purl": "pkg:npm/lodash@4.17.15"},
{"id": "GHSA-xvch-5gv4-984h", "aliases": ["CVE-2021-44906"], "purl": "pkg:npm/minimist@1.2.5"},
{"id": "GHSA-p6mc-m468-83gw", "aliases": ["CVE-2020-8203"], "purl": "pkg:npm/lodash@4.17.15"},
]
statements = [
{"vulnerability": "CVE-2021-23337", "products": ["pkg:npm/lodash@4.17.15"], "status": "not_affected"},
{"vulnerability": "CVE-2021-44906", "products": ["pkg:npm/minimist@1.2.5"], "status": "under_investigation"},
{"vulnerability": "CVE-2020-8203", "products": ["pkg:npm/lodash@4.17.21"], "status": "not_affected"},
]
def apply_vex(findings, statements):
# TODO: return the ids of findings that remain reported
return [f["id"] for f in findings]
print(apply_vex(findings, statements))['GHSA-35jh-r3h4-6jhm', 'GHSA-xvch-5gv4-984h', 'GHSA-p6mc-m468-83gw']
Expected output:
['GHSA-xvch-5gv4-984h', 'GHSA-p6mc-m468-83gw']Show solution
def apply_vex(findings, statements):
def suppressed(f):
ids = {f["id"], *f["aliases"]}
return any(s["status"] == "not_affected" and s["vulnerability"] in ids and f["purl"] in s["products"]
for s in statements)
return [f["id"] for f in findings if not suppressed(f)]The third statement names lodash 4.17.21, not the installed 4.17.15, so it doesn't apply: VEX statements are about specific products and versions.
Exercise 4: Verify an image digest
Topics: OCI Images
A registry returned manifest bytes for a reference pinned by digest. Check that sha256: + the SHA-256 of the exact bytes equals the requested digest. Then show why re-serialising the JSON breaks the check.
import hashlib, json
manifest_bytes = b'{"schemaVersion":2,"config":{"digest":"sha256:5e2b"},"layers":[{"digest":"sha256:8a49"}]}'
requested = "sha256:" + hashlib.sha256(manifest_bytes).hexdigest()
def digest_ok(requested, received_bytes):
# TODO: compute the digest of the received bytes and compare
return None
print(digest_ok(requested, manifest_bytes))
print(digest_ok(requested, manifest_bytes.replace(b"8a49", b"0bad")))
print(digest_ok(requested, json.dumps(json.loads(manifest_bytes), indent=2).encode()))None
None
None
Expected output:
True
False
FalseShow solution
def digest_ok(requested, received_bytes):
return requested == "sha256:" + hashlib.sha256(received_bytes).hexdigest()The third case has the same content as JSON, but different bytes (whitespace), so a different digest. Verifiers always hash the bytes as received.
Exercise 5: Match a signer identity
Topics: GitHub Attestations, Admission Control
Write trusted(identity) that accepts only the release workflow of acme/shop at a semver tag vX.Y.Z. Use an anchored regular expression.
const identities = [
'https://github.com/acme/shop/.github/workflows/release.yml@refs/tags/v1.4.2',
'https://github.com/acme/shop/.github/workflows/release.yml@refs/heads/main',
'https://github.com/acme/shop/.github/workflows/release.yml@refs/tags/v1.4.2-rc1',
'https://github.com/evil/x/.github/workflows/a.yml@refs/heads/github.com/acme/shop/.github/workflows/release.yml@refs/tags/v9.9.9',
];
function trusted(identity) {
// TODO: an anchored regular expression
return true;
}
for (const id of identities) console.log(trusted(id), id.slice('https://github.com/'.length));true acme/shop/.github/workflows/release.yml@refs/tags/v1.4.2
true acme/shop/.github/workflows/release.yml@refs/heads/main
true acme/shop/.github/workflows/release.yml@refs/tags/v1.4.2-rc1
true evil/x/.github/workflows/a.yml@refs/heads/github.com/acme/shop/.github/workflows/release.yml@refs/tags/v9.9.9
Expected output:
true acme/shop/.github/workflows/release.yml@refs/tags/v1.4.2
false acme/shop/.github/workflows/release.yml@refs/heads/main
false acme/shop/.github/workflows/release.yml@refs/tags/v1.4.2-rc1
false evil/x/.github/workflows/a.yml@refs/heads/github.com/acme/shop/.github/workflows/release.yml@refs/tags/v9.9.9Show solution
function trusted(identity) {
return /^https:\/\/github\.com\/acme\/shop\/\.github\/workflows\/release\.yml@refs\/tags\/v\d+\.\d+\.\d+$/.test(identity);
}Exercise 6: The signature that went missing
Topics: Where Signatures Live
This pipeline signs in staging, promotes to production, and verifies in production. The verification fails. Fix the promotion step (one line) so that production verifies without signing again.
crane push /opt/samples/images/alpine-3.18.0.tar localhost:5000/staging/shop:1.4.2 > /dev/null 2>&1
DIGEST=$(crane digest localhost:5000/staging/shop:1.4.2)
cosign sign --key /opt/keys/cosign.key --signing-config /opt/sigstore/offline-signing-config.json \
"localhost:5000/staging/shop@$DIGEST" > /dev/null 2>&1
# promote
crane copy localhost:5000/staging/shop:1.4.2 localhost:5000/prod/shop:1.4.2 > /dev/null 2>&1
# verify in production
cosign verify --key /opt/keys/cosign.pub --insecure-ignore-tlog "localhost:5000/prod/shop@$DIGEST" 2>&1 | grep -E '^Error' || echo "production: signature verified"Error: no signatures found
Expected after the fix:
production: signature verifiedShow solution
oras cp -r --from-plain-http --to-plain-http localhost:5000/staging/shop:1.4.2 localhost:5000/prod/shop:1.4.2 > /dev/nullcrane copy copies the image only. The signature is a separate referrer artifact in the staging repository; oras cp -r copies the image together with everything that refers to it. Re-signing in production would also work, but it means the production signing key or identity must be available to the promotion job.
Test yourself
Why must a purl parser split the version at the *last* @?
- Versions can contain @
- The namespace may contain an encoded @ (%40), and the version separator is the final @
- It doesn't matter
- purls have no version
A VEX statement says not_affected for lodash 4.17.21; the scanner found lodash 4.17.15. Is the finding suppressed?
- Yes, same package
- No, statements apply to the products and versions they name
- Only in Trivy
- Only with --only-fixed