Skip to content

Commit c42b3f1

Browse files
authored
ci: attach per-package SBOMs to releases (3.x) (#19014)
Port of [#18887](#18887) to `3.x`. The first commit is the cherry-pick. The second commit has the `3.x` differences: - Runners stay on `ubuntu-24.04`, like the rest of `3.x`. Will update `3.x` to 26 in a separate PR. - Adds `writeStepSummary.ts`, which `3.x` does not have. [#18981](#18981) adds the same file with identical content, so the second PR to merge gets no conflict. - Adds `.github/scripts/**/*.spec.mjs` to the vitest `unit` project. Without it, the attach script spec does not run on `3.x`. - `SECURITY.md` describes v3 releases. Each stable v3 draft GitHub Release now gets one `payload-sboms-<version>.zip`. It holds a CycloneDX 1.6 and an SPDX 2.3 SBOM (software bill of materials: a machine-readable dependency list) for every published package, plus a `SHA256SUMS` file. A push to `3.x` checks that generation still works. ```diff .github/ ├── scripts/ +│ └── sbom/attach-sboms.mjs # uploads the zip to the draft release └── workflows/ ├── main.yml # + sbom job, push to 3.x only └── publish-release.yml # + generate-sboms, attach-sboms jobs tools/releaser/src/ +├── release-sbom.ts # pnpm release-sbom --out-dir <dir> +└── lib/sbom/ # formats, checks, SPDX supplier, zip bundle SECURITY.md # + SBOM section ``` Customers run security and compliance audits on the Payload packages they install. They need one SBOM per package, downloadable from the GitHub Release. ```text https://github.com/payloadcms/payload/releases/download/v3.93.0/payload-sboms-3.93.0.zip payload-sboms-3.93.0/ ├── payload-3.93.0.cdx.json ├── payload-3.93.0.spdx.json ├── payloadcms-db-postgres-3.93.0.cdx.json ├── ... └── SHA256SUMS pnpm release-sbom --out-dir /tmp/sboms # same generator, locally ``` ## Changes - **SBOM generator (`pnpm release-sbom`)** - Runs `pnpm sbom --split` once per format over the publish list. Flags are `--prod --exclude-peers --sbom-type library`. - Fails when the output dir is not empty or the file set differs from the expected names. Stale files cannot ship. - Checks each file for spec version, root package name, a license on every component, and every direct dependency. - Sets the SPDX root supplier to `Organization: Payload CMS, LLC`. pnpm ignores `--sbom-supplier` for SPDX. - Writes `SHA256SUMS` into `payload-sboms-<version>/` and zips that folder. - **Release workflow** - `generate-sboms` runs after `publish`. It installs, generates, and uploads the zip as an artifact. - `attach-sboms` uploads the zip to the draft release with the label `SBOMs`. - On a rerun, the attach script deletes the existing zip asset before it uploads. - The draft can be published before `attach-sboms` finishes. The script uploads to a draft or a published release. - **Main push check** - A new `sbom` job runs the generator on push to `3.x` when lockfile, manifests, pnpm version, generator files, or `main.yml` change. It is not part of `all-green`. - **Docs** - `SECURITY.md` documents the zip URL, the folder layout, what the SBOM covers, and checksum verification. ## Design Decisions - SBOMs describe what Payload built and tested each package with. They come from the repo lockfile in the real workspace. A fresh consumer resolve in a temp dir was rejected. `workspace:*` deps fail to install there. Customers can scan their own lockfile to see what their install resolves to. - Direct peer dependencies are excluded with `--exclude-peers`. The consumer's project provides `next`, `react`, and `payload`. Peers of transitive dependencies can still appear. - The release gets one zip instead of one asset per SBOM. Separate files would put dozens of assets on every release page. The cost is no per-package download URL. - Generation and upload are two jobs after `publish`. `publish` is unchanged, so an SBOM failure never blocks npm. "Re-run failed jobs" retries only the SBOM jobs. - `generate-sboms` runs third-party install scripts with `contents: read`. `attach-sboms` holds `contents: write` and runs no installed code. It checks out only `.github/scripts/sbom` and runs it through `actions/github-script`. - The attach job derives the zip name from the release tag and uses a fixed label. Nothing in the artifact chooses which file reaches the write token. - The attach script lists releases and matches `tag_name`, so it finds a draft or a published release. `GET /releases/tags/{tag}` cannot be used, because it returns 404 for drafts. - CycloneDX is pinned to 1.6. Snyk, FOSSA, and older Dependency-Track reject 1.7, the pnpm default. SPDX 2.3 covers procurement that asks for SPDX by name. ## Overall Flow ```diff tag v3.*.* pushed publish (environment: release, id-token: write) pnpm release-ci: build, npm publish, create draft release + generate-sboms (contents: read) + pnpm install + pnpm release-sbom: generate, check, SHA256SUMS, zip + upload artifact (zip) + attach-sboms (contents: write, no install) + download artifact + find release by tag_name + delete existing zip asset, upload zip with its label ``` ## References / Links - [pnpm sbom](https://pnpm.io/cli/sbom): generation flags and `--split` output names - [About releases](https://docs.github.com/en/repositories/releasing-projects-on-github/about-releases): asset limits and naming - [actions/github-script](https://github.com/actions/github-script): running a repo script with the job token ## Verify After Merge Local runs covered generation, the checks, the zip, and `SHA256SUMS`. The items below run only in CI. - **Merge of this PR (first push to `3.x`)** - The merge touches generator files. The `needs_sbom` filter should start the `sbom` job. - The generator runs on the CI runner after the shared setup action. - **First v3 release tag** - `generate-sboms` installs on a tag ref. The pnpm cache from `3.x` should restore. - The zip passes from `generate-sboms` to `attach-sboms` as an artifact. - `attach-sboms` checks out only `.github/scripts/sbom` and imports the script through `actions/github-script`. - `GITHUB_TOKEN` finds the draft that the App token created and uploads to it. - The release has one asset, `payload-sboms-<version>.zip`, with the label `SBOMs`. - A rerun of `attach-sboms` replaces the zip. The release still has one asset. - **If `attach-sboms` fails** - npm and the release are not affected. Download the artifact and run `gh release upload`. 🤖 Written with AI
1 parent fd11385 commit c42b3f1

20 files changed

Lines changed: 1422 additions & 0 deletions
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Uploads `payload-sboms-<version>.zip` from `dir` to the GitHub release for `tag`. Runs in the
2+
// `attach-sboms` job of publish-release.yml via actions/github-script. Lists releases to find
3+
// it, because `GET /releases/tags/{tag}` returns 404 for a draft release.
4+
5+
import { existsSync, readFileSync } from 'node:fs'
6+
import path from 'node:path'
7+
8+
const LABEL = 'SBOMs'
9+
10+
export async function attachSboms({ core, dir, github, owner, repo, tag }) {
11+
// The name comes from the tag, not from the artifact: the artifact is written by a job that
12+
// runs installed dependency code, so it cannot pick which file reaches the write token.
13+
const assetName = `payload-sboms-${tag.replace(/^v/, '')}.zip`
14+
const filePath = path.join(dir, assetName)
15+
if (!existsSync(filePath)) {
16+
throw new Error(`SBOM zip ${assetName} missing in ${dir}`)
17+
}
18+
19+
const release = await findReleaseByTag({ github, owner, repo, tag })
20+
21+
const existingAssets = await github.paginate(github.rest.repos.listReleaseAssets, {
22+
owner,
23+
per_page: 100,
24+
release_id: release.id,
25+
repo,
26+
})
27+
// A rerun finds the asset from the previous attempt; upload fails on a duplicate name.
28+
const existing = existingAssets.find((asset) => asset.name === assetName)
29+
if (existing) {
30+
await github.rest.repos.deleteReleaseAsset({ asset_id: existing.id, owner, repo })
31+
}
32+
33+
const data = readFileSync(filePath)
34+
await github.rest.repos.uploadReleaseAsset({
35+
data,
36+
headers: { 'content-length': data.length, 'content-type': 'application/zip' },
37+
label: LABEL,
38+
name: assetName,
39+
owner,
40+
release_id: release.id,
41+
repo,
42+
})
43+
44+
await core.summary.addRaw(`Attached ${assetName} to ${release.html_url}`).write()
45+
46+
return { assetName, releaseUrl: release.html_url }
47+
}
48+
49+
async function findReleaseByTag({ github, owner, repo, tag }) {
50+
const releases = await github.paginate(github.rest.repos.listReleases, {
51+
owner,
52+
per_page: 100,
53+
repo,
54+
})
55+
const match = releases.find((release) => release.tag_name === tag)
56+
if (!match) {
57+
throw new Error(`No GitHub release found for ${tag}`)
58+
}
59+
return match
60+
}
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
2+
import { tmpdir } from 'node:os'
3+
import path from 'node:path'
4+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5+
6+
import { attachSboms } from './attach-sboms.mjs'
7+
8+
const TAG = 'v4.0.0-beta.4'
9+
const ZIP = 'payload-sboms-4.0.0-beta.4.zip'
10+
11+
const release = (overrides = {}) => ({
12+
draft: true,
13+
html_url: `https://github.com/payloadcms/payload/releases/tag/${TAG}`,
14+
id: 42,
15+
tag_name: TAG,
16+
...overrides,
17+
})
18+
19+
const makeGithub = ({ existingAssets = [], releases = [release()] } = {}) => {
20+
const rest = {
21+
repos: {
22+
deleteReleaseAsset: vi.fn(async () => ({})),
23+
listReleaseAssets: vi.fn(),
24+
listReleases: vi.fn(),
25+
uploadReleaseAsset: vi.fn(async () => ({})),
26+
},
27+
}
28+
const results = new Map([
29+
[rest.repos.listReleaseAssets, existingAssets],
30+
[rest.repos.listReleases, releases],
31+
])
32+
const paginate = vi.fn(async (method) => {
33+
if (!results.has(method)) {
34+
throw new Error('unexpected paginate call')
35+
}
36+
return results.get(method)
37+
})
38+
return { paginate, rest }
39+
}
40+
41+
const makeCore = () => {
42+
const summary = { addRaw: vi.fn(() => summary), write: vi.fn(async () => summary) }
43+
return { info: vi.fn(), summary, warning: vi.fn() }
44+
}
45+
46+
describe('attachSboms', () => {
47+
let dir
48+
49+
beforeEach(() => {
50+
dir = mkdtempSync(path.join(tmpdir(), 'attach-sboms-'))
51+
writeFileSync(path.join(dir, ZIP), 'PK')
52+
})
53+
54+
afterEach(() => {
55+
rmSync(dir, { force: true, recursive: true })
56+
})
57+
58+
const run = ({ core = makeCore(), github = makeGithub(), tag = TAG } = {}) =>
59+
attachSboms({ core, dir, github, owner: 'payloadcms', repo: 'payload', tag })
60+
61+
it('uploads the SBOM zip for the tag with its label to the matching release', async () => {
62+
const github = makeGithub()
63+
64+
const result = await run({ github })
65+
66+
expect(result).toEqual({ assetName: ZIP, releaseUrl: release().html_url })
67+
expect(github.rest.repos.uploadReleaseAsset).toHaveBeenCalledOnce()
68+
expect(github.rest.repos.uploadReleaseAsset).toHaveBeenCalledWith(
69+
expect.objectContaining({
70+
label: 'SBOMs',
71+
name: ZIP,
72+
owner: 'payloadcms',
73+
release_id: 42,
74+
repo: 'payload',
75+
}),
76+
)
77+
})
78+
79+
it('sends the zip bytes with content type and length', async () => {
80+
const github = makeGithub()
81+
82+
await run({ github })
83+
84+
const [[args]] = github.rest.repos.uploadReleaseAsset.mock.calls
85+
86+
expect(args.data.toString()).toBe('PK')
87+
expect(args.headers).toEqual({ 'content-length': 2, 'content-type': 'application/zip' })
88+
})
89+
90+
it('picks the release that matches the tag', async () => {
91+
const github = makeGithub({
92+
releases: [
93+
release({ id: 1, tag_name: 'v4.0.0-beta.3' }),
94+
release(),
95+
release({ id: 3, tag_name: 'v4.0.0-beta.2' }),
96+
],
97+
})
98+
99+
await run({ github })
100+
101+
expect(github.rest.repos.uploadReleaseAsset).toHaveBeenCalledWith(
102+
expect.objectContaining({ release_id: 42 }),
103+
)
104+
})
105+
106+
it('deletes an existing asset with the same name before upload', async () => {
107+
const github = makeGithub({
108+
existingAssets: [
109+
{ id: 6, name: 'notes.txt' },
110+
{ id: 7, name: ZIP },
111+
],
112+
})
113+
114+
await run({ github })
115+
116+
expect(github.rest.repos.deleteReleaseAsset).toHaveBeenCalledOnce()
117+
expect(github.rest.repos.deleteReleaseAsset).toHaveBeenCalledWith(
118+
expect.objectContaining({ asset_id: 7 }),
119+
)
120+
expect(github.rest.repos.deleteReleaseAsset.mock.invocationCallOrder[0]).toBeLessThan(
121+
github.rest.repos.uploadReleaseAsset.mock.invocationCallOrder[0] ?? 0,
122+
)
123+
})
124+
125+
it('throws with the tag when no release matches, and uploads nothing', async () => {
126+
const github = makeGithub()
127+
writeFileSync(path.join(dir, 'payload-sboms-9.9.9.zip'), 'PK')
128+
129+
await expect(run({ github, tag: 'v9.9.9' })).rejects.toThrow('v9.9.9')
130+
expect(github.rest.repos.uploadReleaseAsset).not.toHaveBeenCalled()
131+
})
132+
133+
it('uploads when the release is published', async () => {
134+
const github = makeGithub({ releases: [release({ draft: false })] })
135+
136+
await run({ github })
137+
138+
expect(github.rest.repos.uploadReleaseAsset).toHaveBeenCalledOnce()
139+
})
140+
141+
it('throws before any API call when the zip for the tag is missing', async () => {
142+
rmSync(path.join(dir, ZIP))
143+
writeFileSync(path.join(dir, 'payload-sboms-4.0.0-beta.3.zip'), 'PK')
144+
const github = makeGithub()
145+
146+
await expect(run({ github })).rejects.toThrow(ZIP)
147+
expect(github.paginate).not.toHaveBeenCalled()
148+
expect(github.rest.repos.uploadReleaseAsset).not.toHaveBeenCalled()
149+
})
150+
151+
it('writes the zip name and release URL to the job summary', async () => {
152+
const core = makeCore()
153+
154+
await run({ core })
155+
156+
expect(core.summary.addRaw).toHaveBeenCalledWith(`Attached ${ZIP} to ${release().html_url}`)
157+
expect(core.summary.write).toHaveBeenCalled()
158+
})
159+
})

‎.github/workflows/main.yml‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ jobs:
3232
needs_tests: ${{ steps.filter.outputs.needs_tests }}
3333
templates: ${{ steps.filter.outputs.templates }}
3434
build_approvals: ${{ steps.filter.outputs.build_approvals }}
35+
needs_sbom: ${{ steps.filter.outputs.needs_sbom }}
3536
steps:
3637
# https://github.com/actions/virtual-environments/issues/1187
3738
- name: tune linux network
@@ -66,12 +67,28 @@ jobs:
6667
# the root lockfile; that, plus the allowlist itself, is what can introduce drift.
6768
- 'pnpm-lock.yaml'
6869
- 'packages/create-payload-app/src/lib/configure-pnpm-builds.ts'
70+
# Inputs of the release SBOMs (the dependency graph, the pnpm version, the generator) and this job.
71+
needs_sbom:
72+
- 'pnpm-lock.yaml'
73+
- 'pnpm-workspace.yaml'
74+
- 'packages/*/package.json'
75+
- '.tool-versions'
76+
- 'tools/releaser/src/release-sbom.ts'
77+
- 'tools/releaser/src/lib/sbom/**'
78+
- 'tools/releaser/src/lib/publishList.ts'
79+
- 'tools/releaser/src/lib/getPackageDetails.ts'
80+
- 'tools/releaser/package.json'
81+
- 'tools/constants/**'
82+
- 'package.json'
83+
- '.github/actions/setup/**'
84+
- '.github/workflows/main.yml'
6985
- name: Log filter results
7086
run: |
7187
echo "needs_build: ${{ steps.filter.outputs.needs_build }}"
7288
echo "needs_tests: ${{ steps.filter.outputs.needs_tests }}"
7389
echo "templates: ${{ steps.filter.outputs.templates }}"
7490
echo "build_approvals: ${{ steps.filter.outputs.build_approvals }}"
91+
echo "needs_sbom: ${{ steps.filter.outputs.needs_sbom }}"
7592
7693
lint:
7794
runs-on: ubuntu-26.04
@@ -112,6 +129,23 @@ jobs:
112129
path: ./*
113130
key: ${{ github.sha }}
114131

132+
# Catches SBOM generation regressions before a release. Push to 3.x only, not part of all-green.
133+
sbom:
134+
needs: changes
135+
if: github.event_name == 'push' && needs.changes.outputs.needs_sbom == 'true'
136+
runs-on: ubuntu-24.04
137+
138+
steps:
139+
- uses: actions/checkout@v5
140+
with:
141+
persist-credentials: false
142+
143+
- name: Node setup
144+
uses: ./.github/actions/setup
145+
146+
- name: Generate SBOMs
147+
run: pnpm release-sbom --out-dir "$RUNNER_TEMP/sboms"
148+
115149
tests-unit:
116150
permissions:
117151
actions: read

‎.github/workflows/publish-release.yml‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,65 @@ jobs:
5050
env:
5151
GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
5252
NPM_CONFIG_PROVENANCE: true
53+
54+
# Runs after publish so an SBOM failure never blocks npm. "Re-run failed jobs"
55+
# retries only these jobs; release-ci (and its draft notes PATCH) does not run again.
56+
generate-sboms:
57+
name: generate-sboms
58+
needs: publish
59+
if: github.repository == 'payloadcms/payload'
60+
runs-on: ubuntu-24.04
61+
permissions:
62+
contents: read
63+
steps:
64+
- name: Checkout tag
65+
uses: actions/checkout@v5
66+
with:
67+
ref: ${{ github.ref }}
68+
persist-credentials: false
69+
- name: Setup
70+
uses: ./.github/actions/setup
71+
- name: Generate SBOMs
72+
run: pnpm release-sbom --out-dir "$RUNNER_TEMP/sboms"
73+
- name: Upload SBOMs
74+
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
75+
with:
76+
name: sboms-${{ github.ref_name }}
77+
path: ${{ runner.temp }}/sboms/payload-sboms-*.zip
78+
if-no-files-found: error
79+
# A rerun of this job uploads the same artifact name again.
80+
overwrite: true
81+
82+
# Separate job: holds contents: write and runs no installed dependency code.
83+
attach-sboms:
84+
name: attach-sboms
85+
needs: generate-sboms
86+
if: github.repository == 'payloadcms/payload'
87+
runs-on: ubuntu-24.04
88+
permissions:
89+
contents: write
90+
steps:
91+
- name: Checkout attach script
92+
uses: actions/checkout@v5
93+
with:
94+
ref: ${{ github.ref }}
95+
persist-credentials: false
96+
sparse-checkout: .github/scripts/sbom
97+
- name: Download SBOMs
98+
uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
99+
with:
100+
name: sboms-${{ github.ref_name }}
101+
path: ${{ runner.temp }}/sboms
102+
- name: Attach SBOMs to draft release
103+
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
104+
with:
105+
script: |
106+
const { attachSboms } = await import(`${process.env.GITHUB_WORKSPACE}/.github/scripts/sbom/attach-sboms.mjs`)
107+
await attachSboms({
108+
core,
109+
dir: `${process.env.RUNNER_TEMP}/sboms`,
110+
github,
111+
owner: context.repo.owner,
112+
repo: context.repo.repo,
113+
tag: process.env.GITHUB_REF_NAME,
114+
})

‎SECURITY.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,22 @@ Please report any security issues or concerns to [[email protected]](mailt
77
## Rewards and Recognition
88

99
Any report that is validated and addressed is greatly appreciated. When a validated report requires a published advisory (for example, a GitHub Security Advisory / GHSA), the original reporter will be credited in that advisory. When submitting reports, be sure to include your GitHub username to receive credit. We do not offer monetary rewards or bug bounties for security reports.
10+
11+
## Software Bill of Materials (SBOM)
12+
13+
Each Payload v3 release on GitHub includes `payload-sboms-<version>.zip`. For example, the zip for 3.93.0 is at:
14+
15+
https://github.com/payloadcms/payload/releases/download/v3.93.0/payload-sboms-3.93.0.zip
16+
17+
The zip has one folder, `payload-sboms-<version>/`, with one SBOM per published npm package in two formats:
18+
19+
- CycloneDX 1.6 JSON: `<package>-<version>.cdx.json`
20+
- SPDX 2.3 JSON: `<package>-<version>.spdx.json`
21+
22+
`<package>` is the npm name without `@`, with `/` replaced by `-`. For example, `@payloadcms/db-postgres` is `payloadcms-db-postgres-3.93.0.cdx.json`.
23+
24+
Each SBOM lists the production dependencies that Payload built and tested the package with, from the repository lockfile. Other `@payloadcms/*` packages appear with their release version. Direct peer dependencies (for example `next` or `payload`) are excluded, because your project provides them, unless the package also lists them in `dependencies`. Peer dependencies of transitive dependencies can appear.
25+
26+
For the dependencies your project installs, generate an SBOM from your own lockfile.
27+
28+
To verify the files after you unzip, run `sha256sum -c SHA256SUMS` in the `payload-sboms-<version>/` folder.

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@
9999
"release": "pnpm --filter releaser release",
100100
"release-bump": "pnpm --filter releaser release-bump",
101101
"release-ci": "pnpm --filter releaser release-ci",
102+
"release-sbom": "pnpm --filter releaser release-sbom",
102103
"runts": "cross-env NODE_OPTIONS=\"--no-deprecation --no-experimental-strip-types\" node --no-deprecation --no-experimental-strip-types --import @swc-node/register/esm-register",
103104
"script:audit": "pnpm audit -P",
104105
"script:audit:critical": "pnpm audit -P --audit-level critical",

‎tools/releaser/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
"release": "tsx src/release.ts",
3434
"release-bump": "tsx src/release-bump.ts",
3535
"release-ci": "tsx src/release-ci.ts",
36+
"release-sbom": "tsx src/release-sbom.ts",
3637
"test": "echo \"Error: no test specified\" && exit 1"
3738
},
3839
"dependencies": {

0 commit comments

Comments
 (0)