Skip to content

Commit 6e65384

Browse files
authored
feat(git-node): simplify security --start (#1240)
Do not require the local CWD to be the private repo.
1 parent f84e3a5 commit 6e65384

6 files changed

Lines changed: 369 additions & 162 deletions

File tree

‎docs/git-node.md‎

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -598,6 +598,17 @@ $ ncu-config --global set h1_username $H1_TOKEN
598598
access.
599599
- `h1_username`: HackerOne API Token username.
600600

601+
`git node security --start` pushes `vulnerabilities.json` to
602+
`nodejs-private/security-release` through the GitHub API using the token NCU
603+
is configured with, not your local git credentials. That token needs:
604+
605+
- Classic token: the `repo` scope.
606+
- Fine-grained token: access to `nodejs-private/security-release` with
607+
**Contents: Read and write** (to create the `next-security-release` branch
608+
and commit the file) and **Pull requests: Read and write** (to open the
609+
pull request), plus **Pull requests: Read** on `nodejs-private/node-private`
610+
to look up patch authors.
611+
601612
#### Optional: reserve CVEs through the OpenJS Foundation CNA
602613

603614
By default `--request-cve` reserves CVE ids through HackerOne, which acts as
@@ -635,16 +646,16 @@ This command prepares `vulnerabilities.json` and can open the Next Security
635646
Release pull request in `nodejs-private/security-release`, following the
636647
[Security Release Process][] document. It retrieves all pages of triaged
637648
HackerOne reports and uses the same candidate list for exclusions and selection.
638-
The CLI prompts for the release date, report selection, and dependency updates
639-
before writing the draft. Commit, push, and PR creation remain separate
640-
confirmed steps. An existing `next-security-release` branch is checked out
641-
without resetting it. If only `origin/next-security-release` exists locally,
642-
the command creates a tracking branch from that ref. Fetch first when remote
643-
state may have changed.
644-
645-
Security release commits reject unrelated staged changes before staging their
646-
own files. Commit or unstage those changes before continuing. `--start` refuses
647-
to overwrite an existing draft, including one found after switching branches.
649+
The CLI prompts for the release date, report selection, and dependency updates,
650+
then generates the draft in memory (optionally opening it in your editor for
651+
review; the edited file must still be a valid draft). It pushes the draft to the
652+
`next-security-release` branch of `nodejs-private/security-release` using the
653+
GitHub API, so it doesn't need a local clone of that repository. Branch
654+
creation, the push, and PR creation remain separate confirmed steps.
655+
656+
`--start` aborts before prompting for reports if the `next-security-release`
657+
branch already exists upstream, or if `main` already contains
658+
`security-release/next-security-release/vulnerabilities.json`.
648659
Use `--sync`, `--add-report`, or `--remove-report` to update that release.
649660

650661
#### Preparing release data without the CLI
@@ -683,8 +694,9 @@ After reviewing the prepared data, local tools can use
683694
repository path. The helper validates the draft and creates
684695
`security-release/next-security-release/vulnerabilities.json` with an exclusive
685696
write, so an existing file cannot be overwritten. It does not change Git state
686-
or publish anything. Review and authorization belong to the calling tool; the
687-
CLI retains its directory and file-write confirmations.
697+
or publish anything. Review and authorization belong to the calling tool.
698+
`git node security --start` does not use it: it publishes through the GitHub
699+
API instead of writing to a local checkout.
688700

689701
### `git node security --apply-patches`
690702

‎lib/prepare_security.js‎

Lines changed: 109 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1+
import fs from 'node:fs';
2+
import os from 'node:os';
13
import path from 'node:path';
24
import auth from './auth.js';
35
import Request from './request.js';
6+
import { forceRunAsync } from './run.js';
7+
import { getEditor } from './utils.js';
48
import { parsePRFromURL } from './links.js';
5-
import {
6-
assertNewSecurityRelease,
7-
getSecurityReleaseDraftPath,
8-
writeSecurityReleaseDraft
9-
} from './security-release/draft.js';
109
import {
1110
buildIncludedTriagedReport,
1211
getReportPRURL,
@@ -18,7 +17,7 @@ import {
1817

1918
import {
2019
NEXT_SECURITY_RELEASE_BRANCH,
21-
checkoutOnSecurityReleaseBranch,
20+
NEXT_SECURITY_RELEASE_FOLDER,
2221
commitAndPushVulnerabilitiesJSON,
2322
validateDate,
2423
promptDependencies,
@@ -102,7 +101,6 @@ export default class PrepareSecurityRelease extends SecurityRelease {
102101
title = 'Next Security Release';
103102

104103
async start() {
105-
assertNewSecurityRelease(process.cwd());
106104
const credentials = await auth({
107105
github: true,
108106
h1: true
@@ -115,25 +113,43 @@ export default class PrepareSecurityRelease extends SecurityRelease {
115113
if (releaseDate !== 'TBD') {
116114
validateDate(releaseDate);
117115
}
118-
const createVulnerabilitiesJSON = await this.promptVulnerabilitiesJSON();
119116

120117
const content = await this.buildDescription(releaseDate);
121-
if (createVulnerabilitiesJSON) {
122-
const reportSelectionMode = await this.promptReportSelectionMode();
123-
const candidates = await listSecurityReleaseCandidates(this.req);
124-
if (reportSelectionMode === 'review') {
125-
const showTriaged = await this.promptShowTriagedWithoutPR();
126-
if (showTriaged) {
127-
excludedReports = await this.showTriagedReportsWithoutPR(candidates);
128-
}
118+
await this.checkBranchDoesNotExist();
119+
const reportSelectionMode = await this.promptReportSelectionMode();
120+
const candidates = await listSecurityReleaseCandidates(this.req);
121+
if (reportSelectionMode === 'review') {
122+
const showTriaged = await this.promptShowTriagedWithoutPR();
123+
if (showTriaged) {
124+
excludedReports = await this.showTriagedReportsWithoutPR(candidates);
129125
}
130-
await this.startVulnerabilitiesJSONCreation(
131-
releaseDate, content, excludedReports, reportSelectionMode, candidates);
132126
}
127+
await this.startVulnerabilitiesJSONCreation(
128+
releaseDate, content, excludedReports, reportSelectionMode, candidates);
133129

134130
this.cli.ok('Done!');
135131
}
136132

133+
async checkBranchDoesNotExist() {
134+
const { owner, repo } = this.repository;
135+
const branch = NEXT_SECURITY_RELEASE_BRANCH;
136+
this.cli.startSpinner(`Checking that ${branch} does not exist on ${owner}/${repo}...`);
137+
if (await this.req.getBranchSHA({ owner, repo, branch })) {
138+
this.cli.stopSpinner(`${branch} already exists on ${owner}/${repo}`,
139+
this.cli.SPINNER_STATUS.FAILED);
140+
throw new Error('A security release seems to be in progress. Delete the ' +
141+
`https://github.com/${owner}/${repo}/tree/${branch} branch if it is stale.`);
142+
}
143+
const draft = `${NEXT_SECURITY_RELEASE_FOLDER}/vulnerabilities.json`;
144+
if (await this.req.getFileSHA({ owner, repo, path: draft, ref: 'main' })) {
145+
this.cli.stopSpinner(`${draft} already exists on ${owner}/${repo}@main`,
146+
this.cli.SPINNER_STATUS.FAILED);
147+
throw new Error(`Security release draft already exists: ${draft} on main. ` +
148+
'Use --sync, --add-report, or --remove-report to update the existing release.');
149+
}
150+
this.cli.stopSpinner(`${branch} does not exist on ${owner}/${repo}`);
151+
}
152+
137153
async cleanup() {
138154
const credentials = await auth({
139155
github: true,
@@ -203,55 +219,30 @@ export default class PrepareSecurityRelease extends SecurityRelease {
203219
reportSelectionMode = 'review',
204220
candidates
205221
) {
206-
assertNewSecurityRelease(process.cwd());
207-
208222
// choose the reports to include in the security release
209223
const reports = reportSelectionMode === 'include-all'
210224
? await this.includeAllTriagedReports(excludedReports, candidates)
211225
: await this.chooseReports(excludedReports, candidates);
212226
const deps = await this.getDependencyUpdates();
213227
const { release } = prepareSecurityRelease({ releaseDate, reports, dependencies: deps });
214228

215-
// Prepare all data before changing Git state. An existing branch may contain
216-
// a draft that was not present on the branch where this command started.
217-
await checkoutOnSecurityReleaseBranch(this.cli, this.repository);
218-
assertNewSecurityRelease(process.cwd());
229+
let fileContent = this.createVulnerabilitiesJSON(release);
219230

220-
const filePath = await this.createVulnerabilitiesJSON(
221-
release.reports, release.dependencies, release.releaseDate);
222-
223-
// review the vulnerabilities.json file
224231
const review = await this.promptReviewVulnerabilitiesJSON();
225-
226-
if (!review) {
227-
this.cli.info(`To push the vulnerabilities.json file run:
228-
- git add ${filePath}
229-
- git commit -m "chore: create vulnerabilities.json for next security release"
230-
- git push -u origin ${NEXT_SECURITY_RELEASE_BRANCH}
231-
- open a PR on ${this.repository.owner}/${this.repository.repo}`);
232-
return;
232+
if (review) {
233+
fileContent = await this.editVulnerabilitiesJSON(fileContent);
233234
}
234235

235-
// commit and push the vulnerabilities.json file
236-
const commitMessage = 'chore: create vulnerabilities.json for next security release';
237-
await commitAndPushVulnerabilitiesJSON(filePath,
238-
commitMessage,
239-
{ cli: this.cli, repository: this.repository });
240-
241-
const createPr = await this.promptCreatePR();
242-
243-
if (!createPr) return;
236+
await this.pushVulnerabilitiesJSON(
237+
fileContent,
238+
'chore: create vulnerabilities.json for next security release',
239+
{ branchExists: false }
240+
);
244241

245242
// create pr on the security-release repo
246243
return this.createPullRequest(content);
247244
}
248245

249-
promptCreatePR() {
250-
return this.cli.prompt(
251-
'Create the Next Security Release PR?',
252-
{ defaultAnswer: true });
253-
}
254-
255246
async getSecurityIssueTemplate() {
256247
const url = 'https://raw.githubusercontent.com/nodejs/node/main/doc/contributing/security-release-process.md';
257248
try {
@@ -311,10 +302,37 @@ export default class PrepareSecurityRelease extends SecurityRelease {
311302

312303
async promptReviewVulnerabilitiesJSON() {
313304
return this.cli.prompt(
314-
'Please review vulnerabilities.json and press enter to proceed.',
305+
'Do you want to review/edit vulnerabilities.json before pushing it?',
315306
{ defaultAnswer: true });
316307
}
317308

309+
async editVulnerabilitiesJSON(content) {
310+
const editor = await getEditor({ git: true });
311+
const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'ncu-security-'));
312+
const filePath = path.join(dir, 'vulnerabilities.json');
313+
try {
314+
await fs.promises.writeFile(filePath, content);
315+
for (;;) {
316+
await forceRunAsync(editor, [`"${filePath}"`],
317+
{ ignoreFailure: false, spawnArgs: { shell: true } });
318+
const edited = await fs.promises.readFile(filePath, 'utf8');
319+
try {
320+
const { release } = prepareSecurityRelease(JSON.parse(edited));
321+
return this.createVulnerabilitiesJSON(release);
322+
} catch (error) {
323+
this.cli.error(`vulnerabilities.json is not valid: ${error.message}`);
324+
const retry = await this.cli.prompt('Edit vulnerabilities.json again?',
325+
{ defaultAnswer: true });
326+
if (!retry) {
327+
throw new Error('Aborted: vulnerabilities.json is not valid.', { cause: error });
328+
}
329+
}
330+
}
331+
} finally {
332+
await fs.promises.rm(dir, { recursive: true, force: true });
333+
}
334+
}
335+
318336
async promptShowTriagedWithoutPR() {
319337
return this.cli.prompt(
320338
'Do you want to see which reports are triaged but have no PR URL?',
@@ -451,25 +469,47 @@ export default class PrepareSecurityRelease extends SecurityRelease {
451469
}
452470
}
453471

454-
async createVulnerabilitiesJSON(reports, dependencies, releaseDate) {
455-
const { release } = prepareSecurityRelease({ releaseDate, reports, dependencies });
456-
const directory = process.cwd();
457-
const fullPath = getSecurityReleaseDraftPath(directory);
458-
assertNewSecurityRelease(directory);
459-
await confirmSecurityStep(
460-
this.cli,
461-
`create directory \`${path.dirname(fullPath)}\``,
462-
'This creates the security release folder if it does not already exist.'
463-
);
472+
createVulnerabilitiesJSON(release) {
473+
return JSON.stringify(release, null, 2) + '\n';
474+
}
475+
476+
async pushVulnerabilitiesJSON(content, message, { branchExists } = {}) {
477+
const { owner, repo } = this.repository;
478+
const branch = NEXT_SECURITY_RELEASE_BRANCH;
479+
const filePath = `${NEXT_SECURITY_RELEASE_FOLDER}/vulnerabilities.json`;
480+
481+
this.cli.startSpinner(`Looking for ${branch} on ${owner}/${repo}...`);
482+
branchExists ??= !!(await this.req.getBranchSHA({ owner, repo, branch }));
483+
let fileSHA;
484+
if (branchExists) {
485+
fileSHA = await this.req.getFileSHA({ owner, repo, path: filePath, ref: branch });
486+
this.cli.stopSpinner(`Found ${branch} on ${owner}/${repo}`);
487+
} else {
488+
const baseSHA = await this.req.getBranchSHA({ owner, repo, branch: 'main' });
489+
if (!baseSHA) {
490+
this.cli.stopSpinner(`Could not find main on ${owner}/${repo}`,
491+
this.cli.SPINNER_STATUS.FAILED);
492+
throw new Error(`Could not find main on ${owner}/${repo}`);
493+
}
494+
this.cli.stopSpinner(`Found main on ${owner}/${repo}`);
495+
await confirmSecurityStep(
496+
this.cli,
497+
`create branch \`${branch}\` on \`${owner}/${repo}\``,
498+
`This creates the ${branch} branch from main (${baseSHA}).`
499+
);
500+
await this.req.createBranch({ owner, repo, branch, sha: baseSHA });
501+
}
502+
464503
await confirmSecurityStep(
465504
this.cli,
466-
`write \`${fullPath}\``,
467-
'This creates vulnerabilities.json for the next security release.'
505+
`push \`${filePath}\` to \`${owner}/${repo}@${branch}\``,
506+
`This ${fileSHA ? 'replaces' : 'creates'} ${filePath} in a new commit: ${message}`
468507
);
469-
this.cli.startSpinner('Creating vulnerabilities.json...');
470-
writeSecurityReleaseDraft(directory, release);
471-
this.cli.stopSpinner(`Created ${fullPath}`);
472-
return fullPath;
508+
this.cli.startSpinner(`Pushing ${filePath} to ${owner}/${repo}@${branch}...`);
509+
const { commit } = await this.req.createOrUpdateFile({
510+
owner, repo, path: filePath, branch, content, message, sha: fileSHA
511+
});
512+
this.cli.stopSpinner(`Pushed ${commit?.html_url ?? message}`);
473513
}
474514

475515
async createPullRequest(content) {
@@ -486,7 +526,7 @@ export default class PrepareSecurityRelease extends SecurityRelease {
486526
owner,
487527
repo,
488528
base: 'main',
489-
head: 'next-security-release'
529+
head: NEXT_SECURITY_RELEASE_BRANCH
490530
}
491531

492532
);

‎lib/request.js‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,63 @@ export default class Request {
155155
return res;
156156
}
157157

158+
async getBranchSHA({ owner, repo, branch }) {
159+
const url = `/repos/${owner}/${repo}/git/ref/heads/${encodeURIComponent(branch)}`;
160+
const res = await this.fetch(url, {});
161+
if (res.status === 404) return;
162+
if (!res.ok) {
163+
throw new Error(
164+
`Failed to get ${branch} on ${owner}/${repo}: ${res.status} ${res.statusText}`);
165+
}
166+
const { object } = await res.json();
167+
return object.sha;
168+
}
169+
170+
async createBranch({ owner, repo, branch, sha }) {
171+
const url = `/repos/${owner}/${repo}/git/refs`;
172+
const res = await this.fetch(url, {
173+
method: 'POST',
174+
body: JSON.stringify({ ref: `refs/heads/${branch}`, sha })
175+
});
176+
if (!res.ok) {
177+
throw new Error(
178+
`Failed to create ${branch} on ${owner}/${repo}: ${res.status} ${res.statusText}`);
179+
}
180+
return res.json();
181+
}
182+
183+
async getFileSHA({ owner, repo, path, ref }) {
184+
const url = `/repos/${owner}/${repo}/contents/${path}?ref=${encodeURIComponent(ref)}`;
185+
const res = await this.fetch(url, {});
186+
if (res.status === 404) return;
187+
if (!res.ok) {
188+
throw new Error(
189+
`Failed to get ${path} on ${owner}/${repo}@${ref}: ${res.status} ${res.statusText}`);
190+
}
191+
const { sha } = await res.json();
192+
return sha;
193+
}
194+
195+
async createOrUpdateFile({ owner, repo, path, branch, content, message, sha }) {
196+
const url = `/repos/${owner}/${repo}/contents/${path}`;
197+
const res = await this.fetch(url, {
198+
method: 'PUT',
199+
body: JSON.stringify({
200+
message,
201+
content: Buffer.from(content).toString('base64'),
202+
branch,
203+
sha
204+
})
205+
});
206+
if (!res.ok) {
207+
const text = await res.text();
208+
throw new Error(
209+
`Failed to push ${path} to ${owner}/${repo}@${branch}: ` +
210+
`${res.status} ${res.statusText}${text ? `\n${text}` : ''}`);
211+
}
212+
return res.json();
213+
}
214+
158215
async createPullRequest(title, body, { owner, repo, head, base }) {
159216
const url = `/repos/${owner}/${repo}/pulls`;
160217
const options = {

0 commit comments

Comments
 (0)