diff --git a/docs/git-node.md b/docs/git-node.md index d403ee34..079cb17c 100644 --- a/docs/git-node.md +++ b/docs/git-node.md @@ -577,11 +577,13 @@ $ git node vote \ Manage or starts a security release process. -Every `git node security` action asks for permission before each mutating step. -Read-only operations, such as reading files or fetching report data, run without -confirmation. Each confirmation names the command or service action that will -write state and explains the side effect, such as writing files, committing and -pushing changes, creating issues, or updating HackerOne reports. +Every `git node security` action asks for permission before each step that +changes remote state, such as creating issues or pull requests, or updating +HackerOne reports. Local changes run without confirmation: files are written +and staged, and the commit message is pre-filled in `.git/MERGE_MSG`, so it is +picked up by `git commit` and editors such as VS Code. Apart from `--start`, +which pushes its draft through the GitHub API, the CLI never commits or pushes; +review the staged diff, then commit and push `next-security-release` yourself. @@ -609,6 +611,13 @@ is configured with, not your local git credentials. That token needs: pull request), plus **Pull requests: Read** on `nodejs-private/node-private` to look up patch authors. +`git node security --request-cve` lists the reports without a CVE and asks for +a single confirmation. It then requests a CVE for each report and adds the CVE +ID to the HackerOne report right away, without further prompts. +`vulnerabilities.json` is updated and staged last, so if that step fails or the +run is interrupted, `git node security --sync` can still fetch the CVE IDs from +HackerOne. + #### Optional: reserve CVEs through the OpenJS Foundation CNA By default `--request-cve` reserves CVE ids through HackerOne, which acts as diff --git a/lib/prepare_security.js b/lib/prepare_security.js index a6676e47..f34ba7fa 100644 --- a/lib/prepare_security.js +++ b/lib/prepare_security.js @@ -18,7 +18,7 @@ import { import { NEXT_SECURITY_RELEASE_BRANCH, NEXT_SECURITY_RELEASE_FOLDER, - commitAndPushVulnerabilitiesJSON, + stageSecurityReleaseChanges, validateDate, promptDependencies, getSupportedVersions, @@ -195,11 +195,11 @@ export default class PrepareSecurityRelease extends SecurityRelease { vulnerabilityJSON.releaseDate}?`, { defaultAnswer: true }); if (updateFolder) { - await this.updateReleaseFolder( + this.updateReleaseFolder( vulnerabilityJSON.releaseDate.replaceAll('/', '-') ); const securityReleaseFolder = path.join(process.cwd(), 'security-release'); - await commitAndPushVulnerabilitiesJSON( + await stageSecurityReleaseChanges( securityReleaseFolder, 'chore: change next-security-release folder', { cli: this.cli, repository: this.repository } diff --git a/lib/security-announcement.js b/lib/security-announcement.js index f12bad6b..828975d4 100644 --- a/lib/security-announcement.js +++ b/lib/security-announcement.js @@ -1,3 +1,4 @@ +import fs from 'node:fs'; import { NEXT_SECURITY_RELEASE_REPOSITORY, checkoutOnSecurityReleaseBranch, @@ -5,9 +6,8 @@ import { getVulnerabilitiesJSONPath, validateDate, formatDateToYYYYMMDD, - commitAndPushVulnerabilitiesJSON, - createIssue, - writeSecurityFile + stageSecurityReleaseChanges, + createIssue } from './security-release/security-release.js'; import auth from './auth.js'; import Request from './request.js'; @@ -52,14 +52,9 @@ export default class SecurityAnnouncement { content.dockerIssue = dockerIssue; const vulnerabilitiesJSONPath = getVulnerabilitiesJSONPath(); - await writeSecurityFile( - cli, - vulnerabilitiesJSONPath, - JSON.stringify(content, null, 2), - 'This records the build and docker tracking issue links in vulnerabilities.json.' - ); + fs.writeFileSync(vulnerabilitiesJSONPath, JSON.stringify(content, null, 2)); const commitMessage = 'chore: add build and docker issue link'; - await commitAndPushVulnerabilitiesJSON([vulnerabilitiesJSONPath], + await stageSecurityReleaseChanges([vulnerabilitiesJSONPath], commitMessage, { cli: this.cli, repository: this.repository }); this.cli.ok('Added docker and build issue in vulnerabilities.json'); diff --git a/lib/security-release/security-release.js b/lib/security-release/security-release.js index a710c2ea..392b617e 100644 --- a/lib/security-release/security-release.js +++ b/lib/security-release/security-release.js @@ -32,10 +32,6 @@ export const PLACEHOLDERS = { downloads: '%DOWNLOADS%' }; -function formatCommand(command, args) { - return [command, ...args].join(' '); -} - export async function confirmSecurityStep(cli, action, detail) { let message = `Allow action: ${action}?`; if (detail) { @@ -48,17 +44,6 @@ export async function confirmSecurityStep(cli, action, detail) { } } -export async function runSecurityGitCommand(cli, args, detail) { - const command = formatCommand('git', args); - await confirmSecurityStep(cli, `run \`${command}\``, detail); - return runSync('git', args); -} - -export async function writeSecurityFile(cli, filePath, content, detail) { - await confirmSecurityStep(cli, `write \`${filePath}\``, detail); - return fs.writeFileSync(filePath, content); -} - export async function checkRemote(cli, repository) { const remote = runSync('git', ['ls-remote', '--get-url', 'origin']).trim(); const { owner, repo } = repository; @@ -93,24 +78,33 @@ export async function checkoutOnSecurityReleaseBranch(cli, repository) { } else { args = ['checkout', '-b', NEXT_SECURITY_RELEASE_BRANCH]; } - await runSecurityGitCommand( - cli, - args, - `This switches to ${NEXT_SECURITY_RELEASE_BRANCH} without resetting an existing branch.` - ); + runSync('git', args); cli.ok(`Checkout on branch: ${NEXT_SECURITY_RELEASE_BRANCH} `); } } -export async function commitAndPushVulnerabilitiesJSON( +function writeCommitMessage(commitMessage) { + const messagePath = runSync('git', ['rev-parse', '--git-path', 'MERGE_MSG']).trim(); + let existing = ''; + try { + existing = fs.readFileSync(messagePath, 'utf8').trim(); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } + if (existing.split('\n').includes(commitMessage)) return; + fs.writeFileSync(messagePath, + existing ? `${existing}\n${commitMessage}\n` : `${commitMessage}\n`); +} + +export async function stageSecurityReleaseChanges( filePath, commitMessage, { cli, repository } ) { await checkRemote(cli, repository); - const files = (Array.isArray(filePath) ? filePath : [filePath]) - .map((file) => path.resolve(file)); + const filePaths = Array.isArray(filePath) ? filePath : [filePath]; + const files = filePaths.map((file) => path.resolve(file)); const stagedFiles = runSync('git', ['diff', '--cached', '--name-only', '-z']) .split('\0').filter(Boolean); const unrelated = stagedFiles.filter((file) => { @@ -125,47 +119,22 @@ export async function commitAndPushVulnerabilitiesJSON( ); } - if (Array.isArray(filePath)) { - for (const currentPath of filePath) { - runSync('git', ['add', currentPath]); - } - } else { - runSync('git', ['add', filePath]); - } + runSync('git', ['add', '--', ...filePaths]); const staged = runSync('git', ['diff', '--name-only', '--cached']).trim(); if (!staged) { - cli.ok('No changes to commit'); + cli.ok('No changes to stage'); return; } - await runSecurityGitCommand( - cli, - ['commit', '-m', commitMessage], - `This creates a local commit with message: ${commitMessage}` - ); - - try { - await runSecurityGitCommand( - cli, - ['push', '-u', 'origin', NEXT_SECURITY_RELEASE_BRANCH], - `This pushes the security release branch to origin/${NEXT_SECURITY_RELEASE_BRANCH}.` - ); - } catch { - cli.warn('Rebasing...'); - // try to pull rebase and push again - await runSecurityGitCommand( - cli, - ['pull', 'origin', NEXT_SECURITY_RELEASE_BRANCH, '--rebase'], - `This rebases local changes on origin/${NEXT_SECURITY_RELEASE_BRANCH}.` - ); - await runSecurityGitCommand( - cli, - ['push', '-u', 'origin', NEXT_SECURITY_RELEASE_BRANCH], - `This retries pushing the security release branch to origin/${NEXT_SECURITY_RELEASE_BRANCH}.` - ); - } - cli.ok(`Pushed commit: ${commitMessage} to ${NEXT_SECURITY_RELEASE_BRANCH}`); + writeCommitMessage(commitMessage); + cli.ok(`Staged changes with commit message: ${commitMessage}`); + cli.log(runSync('git', ['diff', '--cached', '--stat']).trimEnd()); + cli.info(`Next steps: + - git diff --cached # review the staged changes + - git commit # edit the pre-filled message (or --no-edit to keep it) + - git push -u origin ${NEXT_SECURITY_RELEASE_BRANCH} + To discard, run \`git reset\` (it also clears the pre-filled message).`); } export async function getSupportedVersions() { @@ -398,15 +367,10 @@ export class SecurityRelease { NEXT_SECURITY_RELEASE_FOLDER, 'vulnerabilities.json'); } - async updateReleaseFolder(releaseDate) { + updateReleaseFolder(releaseDate) { const folder = path.join(process.cwd(), NEXT_SECURITY_RELEASE_FOLDER); const newFolder = path.join(process.cwd(), 'security-release', releaseDate); - await confirmSecurityStep( - this.cli, - `rename \`${folder}\` to \`${newFolder}\``, - 'This moves the next-security-release folder to the dated release folder.' - ); fs.renameSync(folder, newFolder); return newFolder; } @@ -415,13 +379,8 @@ export class SecurityRelease { try { const vulnerabilitiesJSONPath = this.getVulnerabilitiesJSONPath(); this.cli.startSpinner(`Updating vulnerabilities.json from ${vulnerabilitiesJSONPath}...`); - await writeSecurityFile( - this.cli, - vulnerabilitiesJSONPath, - JSON.stringify(content, null, 2), - 'This updates vulnerabilities.json with the latest security release data.' - ); - await commitAndPushVulnerabilitiesJSON(vulnerabilitiesJSONPath, + fs.writeFileSync(vulnerabilitiesJSONPath, JSON.stringify(content, null, 2)); + await stageSecurityReleaseChanges(vulnerabilitiesJSONPath, 'chore: updated vulnerabilities.json', { cli: this.cli, repository: this.repository }); this.cli.stopSpinner(`Done updating vulnerabilities.json from ${vulnerabilitiesJSONPath}`); diff --git a/lib/security_blog.js b/lib/security_blog.js index c4a01efc..a7c8f0a3 100644 --- a/lib/security_blog.js +++ b/lib/security_blog.js @@ -6,11 +6,10 @@ import { checkoutOnSecurityReleaseBranch, validateDate, SecurityRelease, - commitAndPushVulnerabilitiesJSON, + stageSecurityReleaseChanges, getAffectedVersionLines, getDependencyUpdates, getHighestSeverityAnnouncement, - writeSecurityFile, } from './security-release/security-release.js'; import auth from './auth.js'; import Request from './request.js'; @@ -69,12 +68,7 @@ export default class SecurityBlog extends SecurityRelease { link, type: 'warning' }); - await writeSecurityFile( - cli, - file, - preRelease, - 'This writes the pre-release vulnerability announcement post.' - ); + fs.writeFileSync(file, preRelease); cli.ok(`Announcement file created and banner has been updated. Folder: ${nodejsOrgFolder}`); await this.updateAnnouncementLink(link); @@ -89,14 +83,9 @@ export default class SecurityBlog extends SecurityRelease { } content.announcement = link; - await writeSecurityFile( - this.cli, - vulnerabilitiesJSONPath, - JSON.stringify(content, null, 2), - 'This writes the announcement link to vulnerabilities.json.' - ); + fs.writeFileSync(vulnerabilitiesJSONPath, JSON.stringify(content, null, 2)); const commitMessage = 'chore: add announcement link'; - await commitAndPushVulnerabilitiesJSON([vulnerabilitiesJSONPath], + await stageSecurityReleaseChanges([vulnerabilitiesJSONPath], commitMessage, { cli: this.cli, repository: this.repository }); this.cli.ok('Updated the announcement link in vulnerabilities.json'); @@ -163,12 +152,7 @@ export default class SecurityBlog extends SecurityRelease { text: `${capitalizedMonth} Security Release is available` }); - await writeSecurityFile( - cli, - preReleasePath, - updatedContent, - 'This writes the post-release vulnerability announcement post.' - ); + fs.writeFileSync(preReleasePath, updatedContent); cli.ok(`Announcement file and banner has been updated. Folder: ${nodejsOrgFolder}`); } @@ -199,12 +183,7 @@ export default class SecurityBlog extends SecurityRelease { link: content.link ?? currentValue.link, type: content.type ?? currentValue.type }; - await writeSecurityFile( - this.cli, - siteJsonPath, - JSON.stringify(siteJson, null, 2) + '\n', - 'This writes the updated security release website banner.' - ); + fs.writeFileSync(siteJsonPath, JSON.stringify(siteJson, null, 2) + '\n'); } formatReleaseDate(releaseDate) { diff --git a/lib/update_security_release.js b/lib/update_security_release.js index 6a2285eb..e9505101 100644 --- a/lib/update_security_release.js +++ b/lib/update_security_release.js @@ -1,14 +1,14 @@ +import fs from 'node:fs'; import { checkoutOnSecurityReleaseBranch, checkRemote, - commitAndPushVulnerabilitiesJSON, + stageSecurityReleaseChanges, validateDate, pickReport, getAffectedVersionLines, getReportSeverity, getSummary, confirmSecurityStep, - writeSecurityFile, SecurityRelease } from './security-release/security-release.js'; import auth from './auth.js'; @@ -93,15 +93,10 @@ export default class UpdateSecurityRelease extends SecurityRelease { }; } const vulnerabilitiesJSONPath = this.getVulnerabilitiesJSONPath(); - await writeSecurityFile( - this.cli, - vulnerabilitiesJSONPath, - JSON.stringify(content, null, 2), - 'This writes synchronized HackerOne report data to vulnerabilities.json.' - ); + fs.writeFileSync(vulnerabilitiesJSONPath, JSON.stringify(content, null, 2)); const commitMessage = 'chore: git node security --sync'; - await commitAndPushVulnerabilitiesJSON([vulnerabilitiesJSONPath], + await stageSecurityReleaseChanges([vulnerabilitiesJSONPath], commitMessage, { cli: this.cli, repository: this.repository }); this.cli.ok('Synced vulnerabilities.json with HackerOne'); } @@ -123,7 +118,7 @@ export default class UpdateSecurityRelease extends SecurityRelease { const updatedVulnerabilitiesFiles = await this.updateJSONReleaseDate(releaseDate, { cli }); const commitMessage = `chore: update the release date to ${releaseDate}`; - await commitAndPushVulnerabilitiesJSON(updatedVulnerabilitiesFiles, + await stageSecurityReleaseChanges(updatedVulnerabilitiesFiles, commitMessage, { cli, repository: this.repository }); cli.ok('Done!'); } @@ -133,12 +128,7 @@ export default class UpdateSecurityRelease extends SecurityRelease { const content = this.readVulnerabilitiesJSON(vulnerabilitiesJSONPath); content.releaseDate = releaseDate; - await writeSecurityFile( - this.cli, - vulnerabilitiesJSONPath, - JSON.stringify(content, null, 2), - `This sets releaseDate to ${releaseDate} in vulnerabilities.json.` - ); + fs.writeFileSync(vulnerabilitiesJSONPath, JSON.stringify(content, null, 2)); this.cli.ok(`Updated the release date in vulnerabilities.json: ${releaseDate}`); return [vulnerabilitiesJSONPath]; @@ -161,15 +151,10 @@ export default class UpdateSecurityRelease extends SecurityRelease { const vulnerabilitiesJSONPath = this.getVulnerabilitiesJSONPath(); const content = this.readVulnerabilitiesJSON(vulnerabilitiesJSONPath); content.reports.push(entry); - await writeSecurityFile( - this.cli, - vulnerabilitiesJSONPath, - JSON.stringify(content, null, 2), - `This appends HackerOne report ${entry.id} to vulnerabilities.json.` - ); + fs.writeFileSync(vulnerabilitiesJSONPath, JSON.stringify(content, null, 2)); this.cli.ok(`Updated vulnerabilities.json with the report: ${entry.id}`); const commitMessage = `chore: added report ${entry.id} to vulnerabilities.json`; - await commitAndPushVulnerabilitiesJSON(vulnerabilitiesJSONPath, + await stageSecurityReleaseChanges(vulnerabilitiesJSONPath, commitMessage, { cli: this.cli, repository: this.repository }); this.cli.ok('Done!'); } @@ -186,16 +171,11 @@ export default class UpdateSecurityRelease extends SecurityRelease { process.exit(1); } content.reports = content.reports.filter((report) => report.id !== reportId); - await writeSecurityFile( - this.cli, - vulnerabilitiesJSONPath, - JSON.stringify(content, null, 2), - `This removes HackerOne report ${reportId} from vulnerabilities.json.` - ); + fs.writeFileSync(vulnerabilitiesJSONPath, JSON.stringify(content, null, 2)); this.cli.ok(`Updated vulnerabilities.json with the report: ${reportId}`); const commitMessage = `chore: remove report ${reportId} from vulnerabilities.json`; - await commitAndPushVulnerabilitiesJSON(vulnerabilitiesJSONPath, + await stageSecurityReleaseChanges(vulnerabilitiesJSONPath, commitMessage, { cli, repository: this.repository }); cli.ok('Done!'); } @@ -249,16 +229,6 @@ export default class UpdateSecurityRelease extends SecurityRelease { } async updateHackonerReportCve(req, report) { - const { id, cveIds } = report; - await confirmSecurityStep( - this.cli, - `update HackerOne report \`${id}\` with CVEs ${cveIds}`, - 'This writes the assigned CVE IDs back to the HackerOne report.' - ); - return this.updateHackonerReportCveWithoutConfirmation(req, report); - } - - async updateHackonerReportCveWithoutConfirmation(req, report) { const { id, cveIds } = report; this.cli.startSpinner(`Updating report ${id} with CVEs ${cveIds}..`); const body = { @@ -294,29 +264,30 @@ export default class UpdateSecurityRelease extends SecurityRelease { async promptCVECreation(req, reports, programId, content, cveSource = 'hackerone') { const reportsWithoutCVE = reports.filter((report) => !report.cveIds?.length); - const requestAll = await this.promptRequestAllCVEs(reportsWithoutCVE); - - if (requestAll) { - await confirmSecurityStep( - this.cli, - `request CVEs for ${reportsWithoutCVE.length} HackerOne reports`, - cveSource === 'openjs-cna' - ? 'This reserves a CVE through the OpenJS Foundation CNA for every report without a CVE.' - : 'This submits CVE requests to HackerOne for every report without a CVE.' - ); + if (!reportsWithoutCVE.length) { + this.cli.info('All reports already have a CVE.'); + return; } + this.showCVERequestSummary(reportsWithoutCVE); + await confirmSecurityStep( + this.cli, + `request CVEs for ${reportsWithoutCVE.length} HackerOne reports`, + (cveSource === 'openjs-cna' + ? 'This reserves a CVE through the OpenJS Foundation CNA for each report' + : 'This submits a CVE request to HackerOne for each report') + + ', adds each CVE ID to its HackerOne report, then updates vulnerabilities.json.' + ); const supportedVersions = (await nv('supported')); const eolVersions = (await nv('eol')); const versionCache = new Map(); - const successfulReports = await this.collectSuccessfulCVERequests({ + const { successfulReports, h1Failed } = await this.collectSuccessfulCVERequests({ req, reports, programId, supportedVersions, eolVersions, versionCache, - requestAll, content, cveSource }); @@ -326,7 +297,7 @@ export default class UpdateSecurityRelease extends SecurityRelease { return; } - await this.applySuccessfulCVEUpdates(req, content, successfulReports); + await this.applySuccessfulCVEUpdates(content, successfulReports, h1Failed); } showCVERequestSummary(reports) { @@ -337,15 +308,6 @@ export default class UpdateSecurityRelease extends SecurityRelease { } } - promptRequestAllCVEs(reportsWithoutCVE) { - if (reportsWithoutCVE.length <= 1) return false; - this.showCVERequestSummary(reportsWithoutCVE); - return this.cli.prompt( - 'Request CVEs for all reports without prompting for each report?', - { defaultAnswer: false } - ); - } - async collectSuccessfulCVERequests({ req, reports, @@ -353,11 +315,11 @@ export default class UpdateSecurityRelease extends SecurityRelease { supportedVersions, eolVersions, versionCache, - requestAll, content, cveSource = 'hackerone' }) { const successfulReports = []; + const h1Failed = []; try { for (const report of reports) { const requested = await this.requestReportCVE({ @@ -367,17 +329,22 @@ export default class UpdateSecurityRelease extends SecurityRelease { supportedVersions, eolVersions, versionCache, - requestAll, content, cveSource }); - if (requested) successfulReports.push(report); + if (!requested) continue; + successfulReports.push(report); + // Update HackerOne before vulnerabilities.json so that `--sync` can + // recover the CVE IDs if the local update does not happen. + if (!await this.updateHackonerReportCve(req, report)) { + h1Failed.push(report); + } } } catch (error) { if (!this.isPromptInterrupted(error)) throw error; this.cli.warn('CVE request interrupted. Finalizing successful requests.'); } - return successfulReports; + return { successfulReports, h1Failed }; } isPromptInterrupted(error) { @@ -393,11 +360,10 @@ export default class UpdateSecurityRelease extends SecurityRelease { supportedVersions, eolVersions, versionCache, - requestAll, content, cveSource = 'hackerone' }) { - const { id, summary, title, affectedVersions, cveIds, link } = report; + const { id, affectedVersions, cveIds } = report; const affectedVersionLines = getAffectedVersionLines(affectedVersions); // skip if already has a CVE // risky because the CVE associated might be @@ -437,18 +403,6 @@ export default class UpdateSecurityRelease extends SecurityRelease { const { cvss_vector_string, weakness_id } = severity; - const issuer = cveSource === 'openjs-cna' ? 'the OpenJS Foundation CNA' : 'HackerOne'; - const create = requestAll || await this.cli.prompt( - `Request a CVE via ${issuer} for: \n -Title: ${title}\n -Link: ${link}\n -Affected versions: ${affectedVersionLines.join(', ')}\n -Vector: ${cvss_vector_string}\n -Summary: ${summary}\n`, - { defaultAnswer: true }); - - if (!create) return false; - const { h1AffectedVersions, patchedVersions } = await this.calculateVersions( affectedVersionLines, @@ -458,13 +412,6 @@ Summary: ${summary}\n`, ); if (cveSource === 'openjs-cna') { - if (!requestAll) { - await confirmSecurityStep( - this.cli, - `reserve a CVE through the OpenJS Foundation CNA for HackerOne report \`${id}\``, - 'This reserves a CVE id at MITRE through the OpenJS CNA for the selected report.' - ); - } return this.reserveCveViaOpenJsCna({ req, report, content, patchedVersions }); } @@ -488,13 +435,6 @@ Summary: ${summary}\n`, } } }; - if (!requestAll) { - await confirmSecurityStep( - this.cli, - `request CVE for HackerOne report \`${report.id}\``, - 'This submits a CVE request to HackerOne for the selected report.' - ); - } this.cli.startSpinner(`Requesting CVE for report ${id}...`); let response; try { @@ -552,22 +492,10 @@ Summary: ${summary}\n`, return this.waitForReservedCve({ req, report, content }); } - // Writes vulnerabilities.json locally (no commit) so the `pendingCve` - // marker survives an interrupted run. The commit happens with the regular - // post-request update. - async persistPendingCve(content, report) { - const vulnerabilitiesJSONPath = this.getVulnerabilitiesJSONPath(); - const action = report.pendingCve - ? `This saves the pending OpenJS CNA correlation id for report ${report.id} ` + - 'so the reservation can be resumed if this command is interrupted.' - : `This clears the failed OpenJS CNA reservation marker for report ${report.id} ` + - 'so the next attempt dispatches a fresh reservation.'; - await writeSecurityFile( - this.cli, - vulnerabilitiesJSONPath, - JSON.stringify(content, null, 2), - action - ); + // Writes vulnerabilities.json locally so the `pendingCve` marker survives an + // interrupted run. It is staged with the regular post-request update. + persistPendingCve(content) { + fs.writeFileSync(this.getVulnerabilitiesJSONPath(), JSON.stringify(content, null, 2)); } async waitForReservedCve({ req, report, content }) { @@ -625,66 +553,22 @@ Summary: ${summary}\n`, return true; } - async applySuccessfulCVEUpdates(req, content, successfulReports) { + async applySuccessfulCVEUpdates(content, successfulReports, h1Failed = []) { this.cli.info('CVE requests succeeded:'); for (const { id, cveIds } of successfulReports) { this.cli.info(`- ${id}: ${cveIds.join(', ')}`); } - const updateVulnerabilitiesJSON = await this.cli.prompt( - 'Update vulnerabilities.json with the successful CVE requests?', - { defaultAnswer: true } - ); - if (!updateVulnerabilitiesJSON) { - this.cli.warn( - 'Skipping HackerOne updates because vulnerabilities.json was not updated.' - ); - return; + if (h1Failed.length) { + this.cli.warn('HackerOne reports not updated:'); + for (const { id, cveIds } of h1Failed) { + this.cli.warn(`- ${id}: ${cveIds.join(', ')}`); + } } const vulnerabilitiesUpdated = await this.updateVulnerabilitiesJSON(content); if (!vulnerabilitiesUpdated) { - this.cli.warn('Skipping HackerOne updates because vulnerabilities.json update failed.'); - return; - } - - const updateHackerOne = await this.cli.prompt( - 'Update HackerOne reports with the successful CVE IDs?', - { defaultAnswer: true } - ); - if (updateHackerOne) { - await confirmSecurityStep( - this.cli, - `update ${successfulReports.length} HackerOne reports with CVE IDs`, - 'This writes the assigned CVE IDs back to all successful HackerOne reports.' - ); - const h1Succeeded = []; - const h1Failed = []; - for (const report of successfulReports) { - try { - const updated = await this.updateHackonerReportCveWithoutConfirmation(req, report); - if (updated) { - h1Succeeded.push(report); - } else { - h1Failed.push(report); - } - } catch (error) { - this.cli.error(error); - h1Failed.push(report); - } - } - - if (h1Succeeded.length) { - this.cli.info('HackerOne reports updated:'); - for (const { id, cveIds } of h1Succeeded) { - this.cli.info(`- ${id}: ${cveIds.join(', ')}`); - } - } - if (h1Failed.length) { - this.cli.warn('HackerOne reports not updated:'); - for (const { id, cveIds } of h1Failed) { - this.cli.warn(`- ${id}: ${cveIds.join(', ')}`); - } - } + this.cli.warn('vulnerabilities.json was not updated. Run `git node security --sync` ' + + 'to fetch the CVE IDs from HackerOne.'); } } diff --git a/test/unit/security_git.test.js b/test/unit/security_git.test.js index d0f60019..64f05d96 100644 --- a/test/unit/security_git.test.js +++ b/test/unit/security_git.test.js @@ -9,7 +9,7 @@ import PrepareSecurityRelease from '../../lib/prepare_security.js'; import { checkoutOnSecurityReleaseBranch, - commitAndPushVulnerabilitiesJSON, + stageSecurityReleaseChanges, NEXT_SECURITY_RELEASE_REPOSITORY } from '../../lib/security-release/security-release.js'; @@ -35,7 +35,7 @@ function repository(t) { return directory; } -const cli = { info() {}, ok() {}, prompt: async() => true }; +const cli = { info() {}, ok() {}, log() {}, prompt: async() => true }; describe('security release git state', { concurrency: false }, () => { it('creates a new release branch from the current HEAD', async(t) => { @@ -72,15 +72,6 @@ describe('security release git state', { concurrency: false }, () => { git('rev-parse', '--abbrev-ref', '@{upstream}'), 'origin/next-security-release'); }); - it('does not switch branches when the checkout is declined', async(t) => { - repository(t); - await assert.rejects(checkoutOnSecurityReleaseBranch({ - ...cli, prompt: async() => false - }, NEXT_SECURITY_RELEASE_REPOSITORY), /Aborted/); - assert.strictEqual(git('branch', '--show-current'), 'main'); - assert.strictEqual(git('branch', '--list', 'next-security-release'), ''); - }); - it('rejects unrelated staged work before staging the release file', async(t) => { repository(t); fs.writeFileSync('unrelated notes.txt', 'User work\n'); @@ -88,7 +79,7 @@ describe('security release git state', { concurrency: false }, () => { fs.writeFileSync('vulnerabilities.json', '{}\n'); const index = git('write-tree'); const head = git('rev-parse', 'HEAD'); - await assert.rejects(commitAndPushVulnerabilitiesJSON( + await assert.rejects(stageSecurityReleaseChanges( 'vulnerabilities.json', 'Prepare release', { cli, repository: NEXT_SECURITY_RELEASE_REPOSITORY } ), /Unrelated staged changes/); @@ -97,28 +88,33 @@ describe('security release git state', { concurrency: false }, () => { assert.strictEqual(fs.readFileSync('unrelated notes.txt', 'utf8'), 'User work\n'); }); - it('allows staged release files and stops at a declined commit', async(t) => { + it('stages release files with a pre-filled commit message', async(t) => { repository(t); fs.mkdirSync('security-release'); fs.writeFileSync('security-release/vulnerabilities.json', '{}\n'); git('add', 'security-release/vulnerabilities.json'); - const index = git('write-tree'); - const prompts = []; - await assert.rejects(commitAndPushVulnerabilitiesJSON( + fs.writeFileSync('security-release/notes.md', 'Notes\n'); + const head = git('rev-parse', 'HEAD'); + await stageSecurityReleaseChanges( 'security-release', 'Prepare release', { - cli: { - ...cli, - async prompt(message) { - prompts.push(message); - return false; - } - }, + cli: { ...cli, prompt: async() => assert.fail('Staging must not prompt') }, repository: NEXT_SECURITY_RELEASE_REPOSITORY } - ), /Aborted/); - assert.strictEqual(prompts.length, 1); - assert.match(prompts[0], /git commit/); - assert.strictEqual(git('write-tree'), index); + ); + assert.strictEqual(git('rev-parse', 'HEAD'), head); + assert.strictEqual(git('diff', '--cached', '--name-only'), + 'security-release/notes.md\nsecurity-release/vulnerabilities.json'); + const messagePath = git('rev-parse', '--git-path', 'MERGE_MSG'); + assert.strictEqual(fs.readFileSync(messagePath, 'utf8'), 'Prepare release\n'); + + fs.writeFileSync('security-release/vulnerabilities.json', '[]\n'); + await stageSecurityReleaseChanges( + 'security-release', 'Update release', { + cli, repository: NEXT_SECURITY_RELEASE_REPOSITORY + } + ); + assert.strictEqual(fs.readFileSync(messagePath, 'utf8'), + 'Prepare release\nUpdate release\n'); }); it('preserves Git state if draft preparation fails', async(t) => { diff --git a/test/unit/security_release.test.js b/test/unit/security_release.test.js index edcf7dde..8a3ba0c7 100644 --- a/test/unit/security_release.test.js +++ b/test/unit/security_release.test.js @@ -257,7 +257,7 @@ describe('security_release: CVE request versions', () => { ]); }); - it('shows the bulk CVE summary before asking to request all reports', async() => { + it('asks a single confirmation after showing the CVE summary', async() => { const events = []; const release = new UpdateSecurityRelease({ info(message) { @@ -269,9 +269,9 @@ describe('security_release: CVE request versions', () => { return false; } }); - release.collectSuccessfulCVERequests = async() => []; + release.collectSuccessfulCVERequests = async() => assert.fail('Must not start'); - await release.promptRequestAllCVEs([ + await assert.rejects(release.promptCVECreation({}, [ { id: '1', title: 'First report', @@ -296,13 +296,15 @@ describe('security_release: CVE request versions', () => { affectedVersions: ['24.x'], summary: 'Second summary' } - ]); + ], '123', {}), /Aborted/); - assert.deepStrictEqual(events.slice(0, 4), [ + assert.deepStrictEqual(events, [ 'info:Reports selected for CVE requests (2):', 'info:- 1 [high] First report', 'info:- 2 [medium] Second report', - 'prompt:Request CVEs for all reports without prompting for each report?' + 'prompt:Allow action: request CVEs for 2 HackerOne reports?\n\n' + + 'This submits a CVE request to HackerOne for each report, adds each CVE ID ' + + 'to its HackerOne report, then updates vulnerabilities.json.' ]); }); @@ -372,18 +374,18 @@ describe('security_release: CVE request versions', () => { ]); }); - it('applies successful CVE updates once after requests finish', async() => { + it('updates vulnerabilities.json once without prompting', async() => { const messages = []; - const prompts = []; - const h1Updates = []; + const warnings = []; const release = new UpdateSecurityRelease({ info(message) { messages.push(message); }, - warn() {}, + warn(message) { + warnings.push(message); + }, prompt(message) { - prompts.push(message); - return true; + assert.fail(`Unexpected prompt: ${message}`); } }); const content = { reports: [] }; @@ -392,129 +394,64 @@ describe('security_release: CVE request versions', () => { { id: '2', cveIds: ['CVE-2026-0002'] } ]; let jsonUpdates = 0; - release.updateVulnerabilitiesJSON = async(updatedContent) => { assert.strictEqual(updatedContent, content); jsonUpdates++; return true; }; - release.updateHackonerReportCveWithoutConfirmation = async(req, report) => { - h1Updates.push(report.id); - return true; - }; - await release.applySuccessfulCVEUpdates({}, content, successfulReports); + await release.applySuccessfulCVEUpdates(content, successfulReports, [successfulReports[1]]); assert.deepStrictEqual(messages, [ 'CVE requests succeeded:', '- 1: CVE-2026-0001', - '- 2: CVE-2026-0002', - 'HackerOne reports updated:', - '- 1: CVE-2026-0001', '- 2: CVE-2026-0002' ]); - assert.deepStrictEqual(prompts, [ - 'Update vulnerabilities.json with the successful CVE requests?', - 'Update HackerOne reports with the successful CVE IDs?', - 'Allow action: update 2 HackerOne reports with CVE IDs?\n\n' + - 'This writes the assigned CVE IDs back to all successful HackerOne reports.' + assert.deepStrictEqual(warnings, [ + 'HackerOne reports not updated:', + '- 2: CVE-2026-0002' ]); assert.strictEqual(jsonUpdates, 1); - assert.deepStrictEqual(h1Updates, ['1', '2']); }); - it('skips HackerOne updates when vulnerabilities.json update is declined', async() => { + it('suggests --sync when vulnerabilities.json update fails', async() => { const warnings = []; const release = new UpdateSecurityRelease({ info() {}, warn(message) { warnings.push(message); - }, - prompt() { - return false; } }); - let h1Updates = 0; - release.updateVulnerabilitiesJSON = async() => { - throw new Error('should not update vulnerabilities.json'); - }; - release.updateHackonerReportCveWithoutConfirmation = async() => { - h1Updates++; - }; + release.updateVulnerabilitiesJSON = async() => false; - await release.applySuccessfulCVEUpdates({}, {}, [ + await release.applySuccessfulCVEUpdates({}, [ { id: '1', cveIds: ['CVE-2026-0001'] } ]); assert.deepStrictEqual(warnings, [ - 'Skipping HackerOne updates because vulnerabilities.json was not updated.' + 'vulnerabilities.json was not updated. Run `git node security --sync` ' + + 'to fetch the CVE IDs from HackerOne.' ]); - assert.strictEqual(h1Updates, 0); }); - it('skips HackerOne updates when vulnerabilities.json update fails', async() => { - const warnings = []; - let promptCount = 0; - const release = new UpdateSecurityRelease({ - info() {}, - warn(message) { - warnings.push(message); - }, - prompt() { - promptCount++; - return true; - } - }); - let h1Updates = 0; - release.updateVulnerabilitiesJSON = async() => false; - release.updateHackonerReportCveWithoutConfirmation = async() => { - h1Updates++; + it('updates each HackerOne report right after its CVE request', async() => { + const events = []; + const reports = [{ id: '1' }, { id: '2' }, { id: '3' }]; + const release = new UpdateSecurityRelease({}); + release.requestReportCVE = async({ report }) => { + events.push(`request:${report.id}`); + return report.id !== '2'; + }; + release.updateHackonerReportCve = async(req, report) => { + events.push(`h1:${report.id}`); + return report.id !== '3'; }; - await release.applySuccessfulCVEUpdates({}, {}, [ - { id: '1', cveIds: ['CVE-2026-0001'] } - ]); - - assert.deepStrictEqual(warnings, [ - 'Skipping HackerOne updates because vulnerabilities.json update failed.' - ]); - assert.strictEqual(promptCount, 1); - assert.strictEqual(h1Updates, 0); - }); - - it('summarizes HackerOne update failures', async() => { - const messages = []; - const warnings = []; - const release = new UpdateSecurityRelease({ - info(message) { - messages.push(message); - }, - warn(message) { - warnings.push(message); - }, - prompt() { - return true; - } + assert.deepStrictEqual(await release.collectSuccessfulCVERequests({ reports, req: {} }), { + successfulReports: [reports[0], reports[2]], + h1Failed: [reports[2]] }); - release.updateVulnerabilitiesJSON = async() => true; - release.updateHackonerReportCveWithoutConfirmation = async(req, report) => report.id === '1'; - - await release.applySuccessfulCVEUpdates({}, {}, [ - { id: '1', cveIds: ['CVE-2026-0001'] }, - { id: '2', cveIds: ['CVE-2026-0002'] } - ]); - - assert.deepStrictEqual(messages, [ - 'CVE requests succeeded:', - '- 1: CVE-2026-0001', - '- 2: CVE-2026-0002', - 'HackerOne reports updated:', - '- 1: CVE-2026-0001' - ]); - assert.deepStrictEqual(warnings, [ - 'HackerOne reports not updated:', - '- 2: CVE-2026-0002' - ]); + assert.deepStrictEqual(events, ['request:1', 'h1:1', 'request:2', 'request:3', 'h1:3']); }); it('keeps successful CVE requests when interrupted', async() => { @@ -525,6 +462,7 @@ describe('security_release: CVE request versions', () => { warnings.push(message); } }); + release.updateHackonerReportCve = async() => true; release.requestReportCVE = async({ report }) => { if (report.id === '1') return true; const error = new Error('User force closed the prompt'); @@ -539,10 +477,9 @@ describe('security_release: CVE request versions', () => { programId: '123', supportedVersions: [], eolVersions: [], - versionCache: new Map(), - requestAll: false + versionCache: new Map() }), - [reports[0]] + { successfulReports: [reports[0]], h1Failed: [] } ); assert.deepStrictEqual(warnings, [ 'CVE request interrupted. Finalizing successful requests.' @@ -1420,7 +1357,6 @@ describe('security_release: OpenJS CNA reservation', () => { supportedVersions: [], eolVersions: [], versionCache: new Map(), - requestAll: true, content: { reports: [report] }, cveSource: 'openjs-cna' }); @@ -1473,7 +1409,6 @@ describe('security_release: OpenJS CNA reservation', () => { supportedVersions: [{ major: 24, version: '24.18.0' }], eolVersions: [], versionCache: new Map(), - requestAll: true, content: { reports: [report] }, cveSource: 'openjs-cna' });