Complete Guide to Supply Chain Security
Secure your software supply chain end-to-end: SBOMs, dependency scanning, Sigstore signing, SLSA provenance, and CI/CD hardening with runnable examples.
Introduction
Your application is maybe 10% code you wrote. The other 90% — direct dependencies, transitive dependencies, build tools, base images, CI actions — was written by strangers, and it runs with your permissions and your secrets. Supply chain security is the discipline of not blindly trusting that 90%.
This isn’t theoretical. The SolarWinds attackers didn’t breach every customer network — they breached the build system once and shipped the backdoor as a legitimate signed update to ~18,000 organizations. When Log4Shell (CVE-2021-44228) dropped in December 2021, teams without an inventory of their dependencies spent days grepping servers and container images; teams with an SBOM answered “are we affected?” in minutes. In March 2024 the xz utils backdoor (CVE-2024-3094) showed a multi-year social-engineering campaign to compromise a single open-source maintainer. And in March 2025 the tj-actions/changed-files compromise (CVE-2025-30066) showed that a GitHub Action’s mutable tag can be moved to a malicious commit, leaking CI secrets into public workflow logs across thousands of repositories.
This guide covers the controls that would have caught or contained each of those attacks: software bills of materials (SBOMs), dependency scanning, artifact signing with Sigstore, SLSA provenance, dependency confusion and typosquatting defenses, and a hardened CI/CD pipeline that ties them together. For the pipeline-specific controls (runner isolation, OIDC federation, branch protection) see the companion CI/CD security guide — this guide focuses on the chain itself: what flows in, what you build, and what you sign.
When Supply Chain Security Matters
You need these controls when:
- You ship software to anyone outside your team — OSS, SaaS, vendor products. Consumers increasingly ask for an SBOM and a signature before they trust your artifact.
- You sell to the US federal government or regulated industries — Executive Order 14028 makes SBOMs a procurement requirement, and frameworks like PCI DSS 4.0 and FedRAMP expect software component inventories.
- You run third-party code in CI/CD — which is everyone who runs
npm installor uses a GitHub Action. Your build pipeline executes stranger code with access to your secrets. - You maintain internal package repositories — the internal names are a dependency-confusion target the moment they leak.
- You publish container images or packages to public registries — users need a way to verify they got what you built, not what an attacker re-uploaded.
Where it’s mostly overkill: internal scripts that never leave your machine, prototypes without CI, personal projects with no consumers. But even there, the near-free baseline — lockfiles, hash pinning, minimal permissions — is worth keeping, because the day a project stops being a toy is rarely the day you notice.
The Supply Chain Attack Surface
Every artifact you ship travels through roughly the same pipeline, and every stage has an attacker who got there before you:
Two properties of this diagram matter more than the individual controls. First, the stages compound: a compromised dependency poisons the build, the build signs it, and the registry ships it under your name — downstream consumers can’t tell the difference because the signature is legitimately yours. Second, verification has to happen at consumption, not just at build: signing an artifact that nobody verifies is decoration.
Software Bill of Materials (SBOM)
An SBOM is a machine-readable inventory of everything in your software: direct dependencies, transitive dependencies, versions, licenses, and where each component came from. It’s the answer to the question nobody wants to ask during an incident — “is the vulnerable thing in here?”
The practical value only shows up if the SBOM is queryable and current. Generating one once for an audit and filing it away is compliance theater. What you want is an SBOM generated per release (or per commit), stored somewhere searchable, so a new CVE announcement becomes a lookup instead of a forensic investigation.
Generating an SBOM
Every major ecosystem has a generator. CycloneDX (an OWASP project) is the common choice for security use cases; syft is a solid general-purpose alternative.
# Python: Generate SBOM with cyclonedx
# pip install cyclonedx-bom
# Generate SBOM from requirements.txt
# cyclonedx-py requirements -i requirements.txt -o sbom.json
# Generate SBOM from Poetry
# cyclonedx-py poetry -o sbom.json
# Node.js: Generate SBOM with npm
# npm sbom --sbom-format cyclonedx > sbom.json
# Java: Generate SBOM with Maven plugin
# mvn org.cyclonedx:cyclonedx-maven-plugin:makeAggregateBom
A generated CycloneDX document looks like this — the purl field is what makes components searchable across ecosystems:
{
"bomFormat": "CycloneDX",
"specVersion": "1.5",
"components": [
{
"type": "library",
"name": "requests",
"version": "2.31.0",
"purl": "pkg:pypi/requests@2.31.0",
"licenses": [
{"license": {"id": "Apache-2.0"}}
]
},
{
"type": "library",
"name": "flask",
"version": "3.0.0",
"purl": "pkg:pypi/flask@3.0.0",
"licenses": [
{"license": {"id": "BSD-3-Clause"}}
]
}
]
}
CycloneDX vs SPDX
The two formats solve overlapping problems from different directions, and which one you lead with depends on who’s asking:
| CycloneDX | SPDX | |
|---|---|---|
| Steward | OWASP | Linux Foundation |
| Status | spec 1.5/1.6 | ISO/IEC 5962:2021 |
| Designed for | Security, vuln analysis, VEX | License compliance, provenance |
| Formats | JSON, XML, protobuf | JSON, RDF, tag:value, YAML |
| Best fit | Security teams, vuln monitoring | Legal review, gov. submissions |
For most teams the answer is CycloneDX for daily security work — it’s lighter, tooling is better, and VEX (Vulnerability Exploitability eXchange) lets you annotate “this CVE doesn’t apply” inside the same format. SPDX shows up when legal or a government contract asks for it.
Validating and Monitoring an SBOM
An SBOM on disk is just a JSON file. The value is in comparing it against things: your license policy, your latest known-good versions, new vulnerability feeds. Here’s a minimal validator for the two checks teams actually run — license compliance and drift detection:
import json
from datetime import datetime
class SBOMValidator:
def __init__(self, sbom_path: str):
with open(sbom_path) as f:
self.sbom = json.load(f)
def get_components(self) -> list:
return self.sbom.get("components", [])
def find_component(self, name: str) -> dict | None:
for comp in self.get_components():
if comp["name"] == name:
return comp
return None
def check_license_compliance(self, allowed_licenses: set) -> list:
violations = []
for comp in self.get_components():
licenses = comp.get("licenses", [])
for lic in licenses:
lic_id = lic.get("license", {}).get("id", "")
if lic_id and lic_id not in allowed_licenses:
violations.append({
"component": comp["name"],
"version": comp["version"],
"license": lic_id
})
return violations
def check_outdated(self, latest_versions: dict) -> list:
outdated = []
for comp in self.get_components():
name = comp["name"]
current = comp["version"]
latest = latest_versions.get(name)
if latest and current != latest:
outdated.append({
"component": name,
"current": current,
"latest": latest
})
return outdated
# Usage
validator = SBOMValidator("sbom.json")
# Check license compliance
allowed = {"MIT", "Apache-2.0", "BSD-3-Clause", "ISC", "MPL-2.0"}
violations = validator.check_license_compliance(allowed)
for v in violations:
print(f"License violation: {v['component']} uses {v['license']}")
# Check for outdated dependencies
latest = {"requests": "2.32.0", "flask": "3.0.3"}
outdated = validator.check_outdated(latest)
for o in outdated:
print(f"Outdated: {o['component']} {o['current']} -> {o['latest']}")
For continuous monitoring, feed SBOMs to a dedicated service rather than scripting this yourself. OWASP Dependency-Track ingests CycloneDX SBOMs and continuously re-matches components against new CVEs — that’s the difference between “we generated an SBOM once” and “we get paged when a dependency we ship turns vulnerable”. Grype does a lighter-weight version: point it at an SBOM and it reports matching vulnerabilities.
Dependency Scanning
Software Composition Analysis (SCA) is the runtime version of what the SBOM gives you statically: it compares your component list against vulnerability databases — OSV, the GitHub Advisory Database, the NVD — and flags what’s affected. The SBOM tells you what’s in the artifact; scanning tells you what’s wrong with it.
The failure mode of most SCA setups isn’t the scanning, it’s the noise. Running npm audit on a real project returns a wall of transitive vulnerabilities in dependencies you don’t control, most of which aren’t exploitable in your context. Tune for severity and reachability, and fail the build only on what you’d actually block a release for — otherwise developers learn to ignore the report, which is worse than not having one.
Automated Vulnerability Scanning
# Python: pip-audit
# pip install pip-audit
# pip-audit --strict --format json > audit-report.json
import subprocess
import json
def run_pip_audit() -> dict:
"""Run pip-audit and parse its JSON output (vulns => non-zero exit)."""
result = subprocess.run(
["pip-audit", "--format", "json"],
capture_output=True,
text=True
)
return json.loads(result.stdout) if result.stdout else {}
# Node.js: npm audit
def run_npm_audit() -> dict:
result = subprocess.run(
["npm", "audit", "--json"],
capture_output=True,
text=True
)
return json.loads(result.stdout)
# Parse and report
def report_vulnerabilities(audit_data: dict) -> str:
vulns = audit_data.get("vulnerabilities", {})
if not vulns:
return "No vulnerabilities found"
report = []
for name, info in vulns.items():
severity = info.get("severity", "unknown")
via = info.get("via", [])
fix_available = info.get("fixAvailable", False)
report.append(
f" {name}: {severity} (fix available: {fix_available})"
)
return "\n".join(report)
Scanning produces findings; someone has to triage them. The vulnerability management template covers the program side — severity-based SLAs, ownership, and remediation tracking — while the dependency vulnerability triage template gives the per-finding process: exploitability, blast radius, and a decision with a deadline. Together they turn scan output into action instead of a JSON file nobody reads.
SCA in CI/CD Pipeline
In the pipeline you want scanning to be fast, deterministic, and only blocking on high severity. This example also generates the SBOM in the same job so the inventory stays in sync with the scan:
# .github/workflows/sca.yml
name: Software Composition Analysis
on: [push, pull_request]
jobs:
sca:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Python dependency audit
run: |
pip install pip-audit
pip-audit --strict --require-hashes
- name: npm audit
run: |
npm audit --audit-level=high
npm audit signatures # Verify package signatures
- name: Trivy filesystem scan
uses: aquasecurity/trivy-action@0.20.0
with:
scan-type: fs
scan-ref: .
severity: HIGH,CRITICAL
format: json
output: trivy-report.json
- name: Snyk scan
uses: snyk/actions/python@0.4.0 # pin a release or SHA in production
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
with:
args: --severity-threshold=high
- name: Generate SBOM
run: |
pip install cyclonedx-bom
cyclonedx-py requirements -i requirements.txt -o sbom.json
- name: Upload SBOM
uses: actions/upload-artifact@v4
with:
name: sbom
path: sbom.json
Two things worth noting in that YAML. npm audit signatures verifies that the packages you installed match what the npm registry signed — it catches tampering between registry and install, not just known-vulnerable versions. And @master on third-party actions would undo everything this guide is about: pin actions to a release tag at minimum, and a full commit SHA where it matters (more on that in the hardening section).
Signing Artifacts with Sigstore
Traditional code signing asks you to solve a key-management problem before it solves your integrity problem: generate a long-lived key, protect it, rotate it, distribute the public half. Those keys end up in CI secrets, get exfiltrated, or outlive the people who created them. Most teams never sign anything because the operational cost is real.
Sigstore removes the key-management problem entirely with “keyless” signing. Instead of holding a private key, your workload authenticates through OIDC — GitHub Actions issues an identity token, Fulcio (Sigstore’s CA) issues a short-lived certificate bound to that identity, cosign signs the artifact, and the signature plus certificate go into Rekor, a public transparency log. The certificate expires in minutes; there’s no long-lived key to steal, and the transparency log means signatures are publicly auditable after the fact.
Signing Artifacts with Cosign
# Install cosign
brew install sigstore/cosign/cosign
# Generate key pair (traditional mode)
cosign generate-key-pair
# Sign a container image
cosign sign --key cosign.key myregistry.com/myapp:v1.0.0
# Verify a signed image
cosign verify --key cosign.pub myregistry.com/myapp:v1.0.0
# Sign with keyless (OIDC-based, no key management)
cosign sign myregistry.com/myapp:v1.0.0
# Verify keyless signature
cosign verify myregistry.com/myapp:v1.0.0 \
--certificate-identity "https://github.com/myorg/myrepo/.github/workflows/deploy.yml@refs/heads/main" \
--certificate-oidc-issuer "https://token.actions.githubusercontent.com"
The identity check in cosign verify is the important part, and it’s where most people stop too early. Anyone can sign an image with keyless cosign — the signature only proves that some OIDC identity signed it. You must verify that the certificate identity matches your repository and issuer, or the signature proves nothing about origin.
Signing Python Packages
# Sign a Python package with sigstore
# pip install sigstore
# Sign a distribution
# python -m sigstore sign dist/myapp-1.0.0-py3-none-any.whl
# Verify a signed package
# python -m sigstore verify \
# --identity "https://github.com/myorg/myapp/.github/workflows/release.yml@refs/tags/v1.0.0" \
# --oidc-issuer "https://token.actions.githubusercontent.com" \
# dist/myapp-1.0.0-py3-none-any.whl
Signing in CI/CD
Keyless signing is where OIDC earns its keep: the workflow gets an id-token permission, Fulcio binds the certificate to the exact repo + workflow + ref that ran the build, and no secret ever needs storing. If you’re still storing signing keys or cloud credentials in secrets, switching the pipeline to OIDC federation removes a whole class of credential-leak attacks — the secrets management guide covers the secret-storage side of the same problem.
# GitHub Actions: Sign container image with cosign
name: Build and Sign
on:
push:
tags: ["v*"]
jobs:
build:
runs-on: ubuntu-latest
permissions:
id-token: write # Required for keyless signing
packages: write
steps:
- uses: actions/checkout@v4
- name: Build image
run: docker build -t ghcr.io/myorg/myapp:${{ github.ref_name }} .
- name: Push image
run: docker push ghcr.io/myorg/myapp:${{ github.ref_name }}
- name: Install cosign
uses: sigstore/cosign-installer@v3
- name: Sign image (keyless)
run: |
cosign sign --yes ghcr.io/myorg/myapp:${{ github.ref_name }}
- name: Generate provenance attestation
run: |
cosign attest --yes \
--predicate <(echo '{"buildType":"github-actions","repository":"myorg/myapp"}') \
--type slsaprovenance \
ghcr.io/myorg/myapp:${{ github.ref_name }}
SLSA Framework
SLSA (Supply-chain Levels for Software Artifacts, pronounced “salsa”) is the framework that turns all of this into levels instead of a checklist. Its core idea: consumers should be able to verify how an artifact was built — from which source, by which builder, with which inputs — via signed provenance, and the levels describe how much you can trust that provenance.
SLSA Levels
The current spec, SLSA v1.0, defines three levels on the Build track. Earlier drafts (v0.2) defined a Level 4 requiring hermetic, reproducible builds with two-party review; it was deferred out of v1.0 to keep the levels achievable, and is expected back in future tracks. Anyone quoting a “Level 5” isn’t reading the spec.
SLSA v1.0 Build track:
Level 1: Provenance exists
- Automated/scripted build process
- Provenance generated (even if unsigned/untrusted)
Level 2: Hosted build platform
- Version-controlled source
- Build runs on a hosted platform (GitHub Actions, GitLab CI)
- Platform generates and signs provenance, so the user
running the build can't tamper with it
Level 3: Hardened build platform
- Builds run in isolated, ephemeral environments
- Provenance is unfalsifiable by the project owner
(platform-enforced signing, e.g. slsa-github-generator)
The escalation is about who could forge the claim. At L1 you say how it was built. At L2 a hosted platform vouches for it. At L3 the platform is built so that not even the project owner can produce false provenance — the provenance is generated by the build platform’s control plane, not by user-controlled build steps. The tj-actions incident is a Level-2 failure in practice: trusted hosted platform, user-controlled tag, forged by moving the tag to a malicious commit.
Generating SLSA Provenance
Provenance is an in-toto attestation: a signed statement describing the build. This generator produces a SLSA v1.0-shaped predicate — buildDefinition captures what was supposed to happen, runDetails captures what actually happened:
import json
from datetime import datetime, timezone
def generate_provenance(
source_repo: str,
commit_sha: str,
build_command: str,
artifacts: list,
builder_id: str
) -> dict:
"""Generate a SLSA v1.0 provenance attestation (in-toto statement)."""
now = datetime.now(timezone.utc).isoformat()
return {
"_type": "https://in-toto.io/Statement/v0.1",
"subject": [
{
"name": artifact["name"],
"digest": artifact["digest"]
}
for artifact in artifacts
],
"predicateType": "https://slsa.dev/provenance/v1",
"predicate": {
"buildDefinition": {
"buildType": "https://github.com/myorg/myrepo/.github/workflows/build.yml",
"externalParameters": {
"repository": source_repo,
"ref": commit_sha,
"command": build_command
},
"internalParameters": {},
"resolvedDependencies": [
{
"uri": source_repo,
"digest": {"gitCommit": commit_sha}
}
]
},
"runDetails": {
"builder": {"id": builder_id},
"metadata": {
"startedOn": now,
"finishedOn": now,
"invocationId": f"{source_repo}/actions/runs/1"
}
}
}
}
# Usage
provenance = generate_provenance(
source_repo="https://github.com/myorg/myapp",
commit_sha="abc123def456",
build_command="docker build -t myapp:v1.0.0 .",
artifacts=[{
"name": "ghcr.io/myorg/myapp:v1.0.0",
"digest": {"sha256": "a1b2c3d4e5f6..."}
}],
builder_id="https://github.com/actions/runner"
)
with open("provenance.json", "w") as f:
json.dump(provenance, f, indent=2)
Hand-rolling provenance like this is fine for understanding the format, but for real Level 3 you want the provenance signed by the build platform itself — that’s what slsa-github-generator does as a reusable workflow, which is why it belongs at job level in the pipeline below, not inside steps.
Dependency Confusion Attacks
Dependency confusion is the attack that’s embarrassing for how little it requires: no exploit, no social engineering, just a name and a higher version number. Alex Birsan demonstrated it at scale in February 2021 — he published packages to public npm, PyPI, and RubyGems under names matching internal packages at Apple, Microsoft, PayPal, and ~35 other companies. The victims’ build systems fetched his packages automatically, executing his (harmless, proof-of-concept) code on their internal networks. He collected over $130k in bug bounties.
The Attack
Dependency confusion exploits package managers that check both
internal and public registries. If an attacker publishes a public
package with the same name as your internal package but a higher
version number, the package manager may download the attacker's
package instead of your internal one.
Attack vector:
1. Attacker discovers internal package names (from error messages,
job postings, or leaked configs)
2. Attacker publishes a malicious package with the same name to
the public registry (npm, PyPI) with a higher version
3. Your build system fetches the attacker's package instead of
your internal one
The mechanism is version resolution, not trust: pip install myapp-utils hits both the internal index and the public one, and if the attacker published myapp-utils==99.0 to PyPI, the “latest” version wins. Internal names leak constantly — they appear in requirements.txt files committed to public repos, error tracebacks in issue trackers, job postings, and npm config output in screenshots.
Prevention
# .npmrc: Force scoped packages to use internal registry
"""
@myorg:registry=https://npm.internal.myorg.com
registry=https://registry.npmjs.org
always-auth=true
"""
# pip.conf: Use internal index with explicit fallback
"""
[global]
index-url = https://pypi.internal.myorg.com/simple
extra-index-url = https://pypi.org/simple
trusted-host = pypi.internal.myorg.com
"""
# Better: Use a virtual repository (Artifactory, Nexus) that
# resolves internal packages first and proxies public packages
"""
[global]
index-url = https://artifactory.internal.myorg.com/api/pypi/pypi-virtual/simple
"""
# Verify package integrity with hashes
# requirements.txt with hashes
"""
requests==2.32.0 \
--hash=sha256:1234abc... \
--hash=sha256:5678def...
flask==3.0.3 \
--hash=sha256:abcd123...
"""
# Install with hash checking
# pip install --require-hashes -r requirements.txt
The layered defense that actually holds up: use npm scopes for internal packages so they can only resolve against your registry; run a virtual repository (Artifactory, Nexus, AWS CodeArtifact) as the single ingress so resolution order is enforced in one place, not in each developer’s config; pin hashes so even a successful confusion attack fails on digest mismatch; and squat your own namespace — publish placeholder packages under your internal names on public registries so an attacker can’t claim them.
Typosquatting Detection
Typosquatting targets the human in the loop: reqeusts instead of requests, python-dateutil2 instead of python-dateutil, colorama vs colorlib. Attackers also combosquat — appending plausible suffixes (requests-http, django-utils) — which looks like a legitimate companion package rather than a typo. A string-similarity check catches most of both:
import difflib
class TyposquatDetector:
POPULAR_PACKAGES = [
"requests", "flask", "django", "fastapi", "numpy",
"pandas", "scipy", "matplotlib", "tensorflow", "torch",
"transformers", "pytest", "celery", "redis", "sqlalchemy",
"pydantic", "uvicorn", "gunicorn", "httpx", "aiohttp"
]
def detect_typosquats(self, package_name: str, threshold: float = 0.8) -> list:
"""Detect if a package name is a typosquat of a popular package."""
typosquats = []
for popular in self.POPULAR_PACKAGES:
similarity = difflib.SequenceMatcher(None, package_name, popular).ratio()
if similarity >= threshold and package_name != popular:
typosquats.append({
"package": package_name,
"mimics": popular,
"similarity": similarity,
"reason": self._get_reason(package_name, popular)
})
return typosquats
def _get_reason(self, name: str, target: str) -> str:
if name == target + "s" or name == target + "2":
return f"Appended suffix to {target}"
if name == target.replace("s", ""):
return f"Removed trailing 's' from {target}"
if name == target.replace("-", "_") or name == target.replace("_", "-"):
return f"Changed separator in {target}"
if len(name) == len(target) and sum(a != b for a, b in zip(name, target)) <= 2:
return f"Character substitution in {target}"
return f"Similar to {target}"
def scan_dependencies(self, dependencies: list) -> dict:
"""Scan all dependencies for typosquats."""
results = {}
for dep in dependencies:
name = dep.split("==")[0].split(">=")[0].split("<=")[0].strip()
typosquats = self.detect_typosquats(name)
if typosquats:
results[name] = typosquats
return results
# Usage
detector = TyposquatDetector()
# Check a suspicious package
suspicious = detector.detect_typosquats("reqeusts")
print(suspicious) # Similar to "requests"
# Scan all dependencies
deps = ["requests==2.31.0", "flask==3.0.0", "reqeusts==1.0.0", "numpyy==1.0.0"]
results = detector.scan_dependencies(deps)
for pkg, typosquats in results.items():
for ts in typosquats:
print(f"WARNING: {ts['package']} mimics {ts['mimics']} ({ts['reason']})")
This detector works best as a pre-merge check on dependency changes — wire it into CI on diffs to requirements.txt/package.json, not as a periodic scan. Registries do retroactive cleanup, but a malicious typosquat only needs to survive the few hours between your npm install and the takedown. Similarity isn’t proof of malice either — legit packages with similar names exist — so treat hits as review prompts, not automatic blocks.
CI/CD Pipeline Hardening
The build pipeline is where every other control converges, which makes it the highest-value target in the whole chain. The tj-actions/changed-files incident is the canonical lesson: a widely-used GitHub Action’s tag was moved to a malicious commit, and every workflow that referenced tj-actions/changed-files@v45 executed code that dumped CI secrets into public logs — ~23,000 repositories were using it. Nothing about the victims’ builds was wrong; the trust anchor itself (a mutable tag) was the vulnerability.
The hardening rules that follow from that:
- Pin actions to the full 40-character commit SHA, not a tag or a short SHA. Tags move; SHAs don’t. Comment the version so Dependabot/Renovate can keep it updated.
- Least-privilege
GITHUB_TOKEN— defaultpermissions:tocontents: readand grantid-token: writeorpackages: writeonly to the jobs that need them. - OIDC instead of stored credentials — federate to cloud providers and Fulcio rather than keeping long-lived keys in secrets.
- Isolate the build step — run compilation in a container with no network and a read-only root, with dependencies vendored beforehand. An isolated build can’t
npm ci(there’s no registry to reach), so fetch dependencies in a networked step first, then run the build itself on the pre-installednode_modules.
# Hardened GitHub Actions workflow
name: Secure Build
on:
push:
branches: [main]
pull_request:
jobs:
secure-build:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # For OIDC
packages: write
outputs:
image-digest: ${{ steps.push.outputs.digest }}
steps:
# Pin actions to the full commit SHA, not tags (tags can be moved —
# see tj-actions/changed-files, March 2025)
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
fetch-depth: 0 # Full history for analysis
# Verify commit signatures
- name: Verify commits
run: |
git log --pretty=format:'%H %G?' main..HEAD | while read hash signed; do
if [ "$signed" != "G" ] && [ "$signed" != "B" ]; then
echo "Unsigned commit: $hash"
exit 1
fi
done
# Fetch dependencies WITH network — lockfile gives integrity.
# The isolated step below has no network, so deps must be vendored first.
- name: Install dependencies
run: npm ci
# Run the build in an isolated environment: no network, read-only
# root, writes only to /build. node_modules is already vendored above.
- name: Build in container
run: |
docker run --rm \
--network=none \
--read-only \
--tmpfs /tmp \
-v $(pwd):/src:ro \
-v $(pwd)/build:/build \
myorg/builder:latest \
/bin/sh -c "cd /src && npm run build -- --outDir /build"
# Generate SBOM
- name: Generate SBOM
run: |
npx cyclonedx-bom -o build/sbom.json
# Scan for vulnerabilities
- name: Trivy scan
uses: aquasecurity/trivy-action@0.20.0
with:
scan-type: fs
scan-ref: ./build
severity: HIGH,CRITICAL
exit-code: 1 # Fail build on critical vulns
# Sign artifacts
- uses: sigstore/cosign-installer@v3
- name: Sign artifacts
run: |
cosign sign-blob --yes build/app.tar.gz --output-signature build/app.sig
cosign sign-blob --yes build/sbom.json --output-signature build/sbom.sig
# Attach provenance as an in-toto attestation via cosign.
# For automated L3 provenance, use the slsa-github-generator
# reusable workflow at JOB level — see the provenance job below.
- name: Generate provenance
run: |
cosign attest --yes \
--predicate provenance.json \
--type slsaprovenance \
build/app.tar.gz
# Upload with attestation
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: build-outputs
path: |
build/app.tar.gz
build/app.sig
build/sbom.json
build/sbom.sig
provenance.json
# SLSA's reusable generator produces platform-signed provenance (L3).
# It must be called as a job (uses: at job level), never inside steps.
# For container images:
# provenance:
# needs: [secure-build]
# permissions:
# actions: read # to fetch build metadata
# id-token: write # to sign the provenance
# packages: write # to publish to the registry
# uses: slsa-framework/slsa-github-generator/.github/workflows/generator_container_slsa3.yml@v2.1.0
# with:
# image: ghcr.io/myorg/myapp
# digest: ${{ needs.secure-build.outputs.image-digest }}
# registry-username: ${{ github.actor }}
# secrets:
# registry-password: ${{ secrets.GITHUB_TOKEN }}
Common Mistakes
The patterns that produce supply chain incidents in practice:
- Trusting mutable tags.
uses: actions/checkout@v4executes whatever the tag points at today. The tj-actions compromise showed a tag moving to a malicious commit; every consumer ran it automatically. Pin the SHA, comment the version. - Generating an SBOM and never querying it. An SBOM nobody searches during an incident is shelf-ware. If it’s not wired into Dependency-Track, Grype, or a lookup you actually run, it only exists to satisfy a questionnaire.
- Signing artifacts nobody verifies. Signatures are checked at deploy time or they’re decoration. If your Kubernetes admission controller or deploy script doesn’t
cosign verify, the signature protects nothing. - Generating provenance without enforcing it. SLSA provenance is only as good as the policy that rejects artifacts lacking it. Without admission-time verification you’re attesting to yourself.
- “Hermetic” builds that can’t work.
--network=noneplusnpm ciin the same step fails — npm can’t fetch from a registry it can’t reach. Vendor dependencies first, then isolate. - Pinning the wrong thing.
myorg/builder:latestas the isolated image,@masteron a security action,*version ranges — all mutable, all defeatable. The lockfile and the SHA are the point. - Treating internal names as private. Internal package names leak through public
requirements.txt, error traces, and job posts. Namespace-squat them publicly or scope them — don’t assume obscurity.
Security Checklist
Printable version of the controls above, organized by where they sit in the chain:
Supply Chain Security Checklist:
Source Code:
[ ] All commits signed (GPG or SSH)
[ ] Branch protection rules enforced
[ ] Two-party review required for merges
[ ] No force pushes to main branches
[ ] Secrets scanned in git history
Dependencies:
[ ] SBOM generated for every release
[ ] Automated dependency scanning in CI/CD
[ ] License compliance verified
[ ] Dependency hashes pinned (pip --require-hashes, npm package-lock)
[ ] Internal package names protected against dependency confusion
[ ] Typosquatting detection on new dependencies
Build:
[ ] Build runs in isolated environment (no network)
[ ] Build tools pinned to specific versions
[ ] GitHub Actions pinned to full SHAs, not tags
[ ] Build provenance generated (SLSA v1.0 L2+)
[ ] Artifacts signed with Sigstore/cosign
Distribution:
[ ] Container images signed
[ ] Provenance attestation attached
[ ] Package registry requires authentication
[ ] Download verification (checksums, signatures)
[ ] Rollback plan for compromised packages
Best Practices
The practices that separate “has the tools” from “would actually catch it”:
- Verify at the point of use, not at the point of generation. Signatures, provenance, and SBOMs only matter if something downstream rejects artifacts that fail. Put
cosign verifyin your deploy script or admission controller; that’s where the check has teeth. - One ingress for all dependencies. A virtual repository (Artifactory, Nexus, CodeArtifact) as the single path for packages beats per-developer
.npmrc/pip.conffiles — you control resolution order once, centrally, and dependency confusion gets blocked at the proxy. - Prefer OIDC over stored secrets everywhere it exists. GitHub Actions to AWS/GCP, Actions to Fulcio for signing — every long-lived credential you delete is a credential that can’t leak. The tj-actions attack only worked because CI env vars contained secrets worth exfiltrating.
- Tune scanners to what you’d block on.
npm audit --audit-level=highand Trivyexit-code: 1on HIGH/CRITICAL are deliberate: failing on every transitive low-severity finding trains the team to add--forceflags. Block on what matters, track the rest. - Squat your own namespaces. Publish placeholder packages on public registries under your internal names, and reserve your org’s scope on npm. It costs nothing and closes the dependency-confusion hole at the registry level, not at config level.
- Treat the lockfile as a security artifact.
package-lock.jsonandrequirements.txtwith hashes are the enforcement point: commit them, review diffs to them (that’s where a new dependency appears), and gatenpm ci/pip installon--require-hashes.
See Also
- CI/CD Security: Harden Your Pipelines and Prevent Supply Chain Attacks — pipeline-specific controls (runners, OIDC, branch protection)
- Complete Guide to Secrets Management — the OIDC/secret-storage side of keyless signing
- Complete Guide to Docker in Production — hardened base images and runtime security
- Vulnerability Management Template — triage the findings your scanners produce
- SLSA v1.0 Specification — the actual level definitions
- Sigstore / cosign docs — keyless signing and Rekor
- CycloneDX spec — SBOM format (OWASP)
- OWASP Dependency-Track — continuous SBOM monitoring
- npm docs: audit and audit signatures — registry signature verification
- GitHub docs: SLSA provenance with slsa-github-generator — OIDC and artifact provenance
- Alex Birsan: Dependency Confusion — the original attack write-up
- US Executive Order 14028 — the SBOM mandate
- Supply chain security companion on GitHub — runnable SBOM validator, typosquat detector, provenance generator, and the hardened workflow
Frequently Asked Questions
What is an SBOM and why do I need one?
An SBOM (Software Bill of Materials) is a formal, machine-readable inventory of every component in your software — dependencies, transitive dependencies, versions, and licenses. You need one to answer "are we affected?" quickly when a vulnerability drops (Log4Shell is the canonical case), and regulations like US Executive Order 14028 increasingly require SBOMs for procurement. Generate one per release with cyclonedx or syft.
How does the SLSA framework define its levels?
SLSA v1.0 defines three Build-track levels: L1 requires provenance to exist for an automated build, L2 requires a hosted build platform to sign that provenance, and L3 requires the platform to be hardened so provenance can't be forged even by the project owner. An earlier draft (v0.2) had a Level 4 for hermetic, reproducible builds — it was deferred from v1.0. There's no Level 5; see slsa.dev for the spec.
How do I prevent dependency confusion attacks?
Route all package resolution through a virtual repository (Artifactory, Nexus, CodeArtifact) that resolves internal packages first before proxying public registries. Scope internal npm packages (@myorg/) so they can only come from your registry. Pin dependency hashes so a confused fetch fails on digest mismatch. And squat your internal package names on public registries before an attacker claims them.
What is Sigstore and how does it work?
Sigstore is a free, open-source signing ecosystem built around "keyless" signing: your build authenticates via OIDC, Fulcio issues a short-lived certificate bound to that identity, cosign signs the artifact, and the signature is recorded in Rekor's public transparency log. No long-lived keys exist to steal or rotate, and signatures are publicly auditable. Verifiers check the certificate identity (repo, workflow, ref) against what they expect.
How do I detect typosquatting in my dependencies?
Compare package names against a list of popular packages with string similarity — difflib.SequenceMatcher at a threshold around 0.8 catches most cases. Watch for the common patterns: character substitutions, added/dropped characters, separator changes (- vs _), and combosquatting suffixes (requests-http). Run it as a CI check on lockfile diffs, because a malicious typosquat only needs to survive until your next install.
Should I pin GitHub Actions to commit SHAs?
Yes — pinning to a full 40-character SHA is the standard hardening control. Tags are mutable and can be moved to a different commit (that's exactly how the tj-actions/changed-files compromise worked in March 2025). A SHA pins the code itself. Write it as actions/checkout@<full-sha> # v4.2.2 so Dependabot or Renovate can keep the comment versioned and the SHA updated.
Related Resources
Complete Guide to OWASP Top 10 2025
Mitigate each risk in the OWASP Top 10 2025 list with practical code examples. Covers the new supply chain and exception-handling categories, plus the reordered classics.
GuideComplete Guide to Secrets Management
Manage application secrets securely in production: Vault, AWS, Azure, GCP, Kubernetes secrets, rotation, CI/CD, and when a manager is overkill.
GuideComplete Guide to API Security
Secure your APIs end-to-end: rate limiting, auth, input validation, CORS, injection prevention, gateway patterns, audit logging, and testing.
GuideCI/CD Pipeline Security: Prevent Supply Chain Attacks
A practical guide to securing CI/CD pipelines: secrets management, least-privilege runners, artifact signing, and supply chain defense.
DocVulnerability Management Template
A repeatable template for tracking vulnerabilities, assigning remediation owners, defining patching timelines, and reporting security risks to stakeholders.
RecipeManage Application Secrets with HashiCorp Vault and Python
Store, retrieve, and rotate application secrets securely using HashiCorp Vault with Python hvac client, dynamic secrets, and automatic lease renewal.