47bd02647c
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The commitperclip review workflow runs a security gate as part of CI on every PR > - The security script's header promises it always exits 0 and stays silent/informational, but PRs that triggered a flag were failing with a 5-minute timeout > - Two compounding bugs: `findExistingDraftAdvisory` paginated without an upper bound, and the workflow step did not have `continue-on-error: true`, so any hang inside the script turned into a hard `review` check failure that blocked merge > - This pull request caps the advisory pagination at 20 pages and adds `continue-on-error: true` to the workflow step, aligning runtime behavior with the script's documented "always exit 0" contract > - The benefit is that future PRs flagged by the security gate no longer block merge on a 5-minute timeout, and the gate stays silent/informational as intended ## Linked Issues or Issue Description Fixes: #7849 ## What Changed - `.github/workflows/commitperclip-review.yml`: added `continue-on-error: true` to the `Run security gates` step so a hang or non-zero exit cannot fail the `review` check (matches the script's documented "always exit 0" contract). - `.github/scripts/check-pr-security.mjs`: capped `findExistingDraftAdvisory` pagination at 20 pages (= 2000 advisories) and short-circuited with a `console.warn` when the cap is hit; if no match is found within the cap, callers will simply create a new draft instead of hanging forever. - `.github/scripts/tests/check-pr-security.test.mjs`: added a test asserting the pagination cap is enforced. ## Verification - `node .github/scripts/tests/check-pr-security.test.mjs` — 31/31 pass, including the new cap test. - Step-level guarantee: `continue-on-error: true` makes the `Run security gates` step non-blocking for the job, so even an unexpected hang/timeout in this step can no longer fail the `review` check. ## Risks - Low risk. Pagination cap is a defensive bound; the worst case is a duplicate draft advisory (acceptable — the workflow continues). `continue-on-error: true` is exactly what the script header already promised; the workflow now matches its stated contract. ## Model Used - Claude (claude-opus-4-7), extended thinking, tool use ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] If this change affects the UI, I have included before/after screenshots - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip <noreply@paperclip.ing>
133 lines
4.6 KiB
JavaScript
133 lines
4.6 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* get-bot-token.mjs
|
|
* Generates a short-lived GitHub installation token for the commitperclip app.
|
|
* Reads COMMITPERCLIP_KEY env var (PEM content of private key).
|
|
* Prints the token to stdout.
|
|
*
|
|
* Also exports: generateJWT(privateKey), ghFetch(path, token, options)
|
|
* These are used by all other gate scripts.
|
|
*/
|
|
import { createSign } from 'node:crypto';
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
const APP_ID = '3718661';
|
|
const OWNER_PATTERN = /^[a-zA-Z0-9_.-]+$/;
|
|
const REPO_PATTERN = /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/;
|
|
|
|
export function generateJWT(privateKey) {
|
|
const now = Math.floor(Date.now() / 1000);
|
|
const payload = { iat: now - 10, exp: now + 60, iss: APP_ID };
|
|
const header = Buffer.from(JSON.stringify({ alg: 'RS256', typ: 'JWT' })).toString('base64url');
|
|
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
|
|
const data = `${header}.${body}`;
|
|
const sig = createSign('RSA-SHA256').update(data).sign(privateKey, 'base64url');
|
|
return `${data}.${sig}`;
|
|
}
|
|
|
|
// Per-call timeout so a single slow/hung GitHub endpoint cannot eat the entire
|
|
// workflow budget. Overridable via options.timeoutMs for callers that need
|
|
// different bounds.
|
|
export const GH_FETCH_DEFAULT_TIMEOUT_MS = 15_000;
|
|
|
|
export async function ghFetch(path, token, options = {}) {
|
|
const { timeoutMs = GH_FETCH_DEFAULT_TIMEOUT_MS, signal: externalSignal, ...fetchOptions } = options;
|
|
const controller = new AbortController();
|
|
const timer = setTimeout(() => controller.abort(new Error(`ghFetch timeout after ${timeoutMs}ms: ${path}`)), timeoutMs);
|
|
const abortOnExternal = () => controller.abort(externalSignal?.reason);
|
|
if (externalSignal) {
|
|
if (externalSignal.aborted) abortOnExternal();
|
|
else externalSignal.addEventListener('abort', abortOnExternal, { once: true });
|
|
}
|
|
try {
|
|
const res = await fetch(`https://api.github.com${path}`, {
|
|
...fetchOptions,
|
|
signal: controller.signal,
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
Accept: 'application/vnd.github+json',
|
|
'X-GitHub-Api-Version': '2022-11-28',
|
|
...fetchOptions.headers,
|
|
},
|
|
});
|
|
const text = await res.text();
|
|
if (!res.ok) throw new Error(`GitHub API ${fetchOptions.method ?? 'GET'} ${path} → ${res.status}: ${text}`);
|
|
return JSON.parse(text);
|
|
} finally {
|
|
clearTimeout(timer);
|
|
if (externalSignal) externalSignal.removeEventListener('abort', abortOnExternal);
|
|
}
|
|
}
|
|
|
|
export async function resolveInstallationId(fetchInstallation, token, repo, owner) {
|
|
if (repo) {
|
|
if (!REPO_PATTERN.test(repo)) {
|
|
throw new Error('ERROR: GH_REPO/GITHUB_REPOSITORY must be in owner/repo format.');
|
|
}
|
|
|
|
const installation = await fetchInstallation(`/repos/${repo}/installation`, token);
|
|
return installation.id;
|
|
}
|
|
|
|
const installations = await fetchInstallation('/app/installations', token);
|
|
if (!installations.length) {
|
|
throw new Error(
|
|
'ERROR: No installations found for commitperclip. Install URL: https://github.com/apps/commitperclip/installations/new'
|
|
);
|
|
}
|
|
|
|
if (owner) {
|
|
if (!OWNER_PATTERN.test(owner)) {
|
|
throw new Error('ERROR: GITHUB_REPOSITORY_OWNER must be a valid GitHub owner name.');
|
|
}
|
|
|
|
const match = installations.find(
|
|
installation => installation.account?.login?.toLowerCase() === owner.toLowerCase()
|
|
);
|
|
|
|
if (match) {
|
|
return match.id;
|
|
}
|
|
}
|
|
|
|
if (installations.length === 1) {
|
|
return installations[0].id;
|
|
}
|
|
|
|
throw new Error(
|
|
'ERROR: Multiple commitperclip installations found. Set GH_REPO or GITHUB_REPOSITORY so the correct installation can be selected.'
|
|
);
|
|
}
|
|
|
|
async function main() {
|
|
const privateKey = process.env.COMMITPERCLIP_KEY;
|
|
if (!privateKey) {
|
|
console.error('ERROR: COMMITPERCLIP_KEY env var not set.');
|
|
console.error('Add to ~/.bash_profile: export COMMITPERCLIP_KEY="$(cat ~/.config/commitperclip/private-key.pem)"');
|
|
process.exit(1);
|
|
}
|
|
|
|
const jwt = generateJWT(privateKey);
|
|
const repo = process.env.GH_REPO ?? process.env.GITHUB_REPOSITORY;
|
|
const owner = process.env.GITHUB_REPOSITORY_OWNER ?? repo?.split('/')[0];
|
|
|
|
const installationId = await resolveInstallationId(ghFetch, jwt, repo, owner);
|
|
|
|
const { token } = await ghFetch(
|
|
`/app/installations/${installationId}/access_tokens`,
|
|
jwt,
|
|
{ method: 'POST', headers: { 'Content-Type': 'application/json' } }
|
|
);
|
|
|
|
if (!token) {
|
|
console.error('ERROR: Failed to get installation token from GitHub API.');
|
|
process.exit(1);
|
|
}
|
|
|
|
process.stdout.write(token);
|
|
}
|
|
|
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
main().catch(e => { console.error(e.message); process.exit(1); });
|
|
}
|