From 456b90edcb2d0115c4fb04ea9ae50221a70397d1 Mon Sep 17 00:00:00 2001 From: jdalton Date: Mon, 30 Nov 2026 17:39:52 -0500 Subject: [PATCH] feat(ci): post Socket-rendered pull request comments --- .gitignore | 2 + docs/commands/ci.md | 10 ++ src/commands/ci/handle-ci.mts | 34 +++++ src/commands/ci/handle-ci.test.mts | 130 ++++++++++++++++++- src/commands/ci/publish-pr-comments.mts | 74 +++++++++++ src/commands/ci/publish-pr-comments.test.mts | 98 ++++++++++++++ src/commands/scan/handle-create-new-scan.mts | 3 + src/commands/scan/handle-diff-scan.mts | 5 + src/constants.mts | 3 +- src/utils/github.mts | 40 +++++- 10 files changed, 396 insertions(+), 3 deletions(-) create mode 100644 src/commands/ci/publish-pr-comments.mts create mode 100644 src/commands/ci/publish-pr-comments.test.mts diff --git a/.gitignore b/.gitignore index da68a5eee..282f2d317 100644 --- a/.gitignore +++ b/.gitignore @@ -879,6 +879,8 @@ !/src/utils/github-errors.mts !/src/utils/github-errors.test.mts !/src/utils/github.mts +!/src/commands/ci/publish-pr-comments.mts +!/src/commands/ci/publish-pr-comments.test.mts !/src/utils/glob-content-dedup.test.mts !/src/utils/glob.mts !/src/utils/glob.test.mts diff --git a/docs/commands/ci.md b/docs/commands/ci.md index dfbb70ea7..f059809e3 100644 --- a/docs/commands/ci.md +++ b/docs/commands/ci.md @@ -10,3 +10,13 @@ socket ci Use `--auto-manifest` to include locally generated manifests for supported projects. Run `socket ci --help` for all options. + +On GitHub pull request runs, pass a GitHub token with pull request write +permission in `SOCKET_CLI_GITHUB_TOKEN`, `GITHUB_TOKEN`, or `GH_TOKEN`. The +command posts an overview and a security findings comment, and updates them on +reruns. Socket renders these comments from the PR diff scan using the +Socket API token. The token needs `full-scans:list`, `diff-scans:create`, +and `diff-scans:list` for the diff and its comments. + +Set `SOCKET_CLI_DISABLE_OVERVIEW_COMMENT=true` or +`SOCKET_CLI_DISABLE_SECURITY_COMMENT=true` to skip either comment. diff --git a/src/commands/ci/handle-ci.mts b/src/commands/ci/handle-ci.mts index 1dba5cc05..d315d5a12 100644 --- a/src/commands/ci/handle-ci.mts +++ b/src/commands/ci/handle-ci.mts @@ -1,9 +1,11 @@ import { detectCiPullRequestContext } from './detect-ci-pull-request-context.mts' import { getDefaultOrgSlug } from './fetch-default-org-slug.mts' +import { publishPullRequestComments } from './publish-pr-comments.mts' import { selectBaselineScan } from './select-baseline-scan.mts' import constants from '../../constants.mts' import { setCiExitCode } from '../../utils/ci-exit-code.mts' import { debugDir, debugFn } from '../../utils/debug.mts' +import { envAsBoolean } from '../../utils/env.mts' import { detectDefaultBranch, getRepoName, @@ -57,6 +59,7 @@ export async function handleCi(autoManifest: boolean): Promise { ) debugDir('inspect', { orgSlug, cwd, branchName, repoName }) + const [owner, repo] = constants.ENV.GITHUB_REPOSITORY.split('/') await handleCreateNewScan({ autoManifest, branchName, @@ -72,6 +75,37 @@ export async function handleCi(autoManifest: boolean): Promise { pendingHead: true, pullRequest, baselineScanId, + onDiffReport: async diffScanId => { + if ( + pullRequestContext.provider !== 'github' || + !owner || + !repo || + !constants.ENV.SOCKET_CLI_GITHUB_TOKEN + ) { + return + } + try { + await publishPullRequestComments({ + diffScanId, + disableOverview: envAsBoolean( + process.env['SOCKET_CLI_DISABLE_OVERVIEW_COMMENT'], + ), + disableSecurity: envAsBoolean( + process.env['SOCKET_CLI_DISABLE_SECURITY_COMMENT'], + ), + orgSlug, + owner, + pullRequest, + repo, + serverUrl: constants.ENV.GITHUB_SERVER_URL, + }) + } catch (error) { + debugFn('warn', 'Could not publish pull request comments', error) + process.stderr.write( + 'Socket could not publish the scan comments. Check the Socket API scopes and GitHub pull request write permission.\n', + ) + } + }, reach: { dynamicSbomInference: undefined, excludePaths: [], diff --git a/src/commands/ci/handle-ci.test.mts b/src/commands/ci/handle-ci.test.mts index 85c1ed5d2..58d2cf28e 100644 --- a/src/commands/ci/handle-ci.test.mts +++ b/src/commands/ci/handle-ci.test.mts @@ -1,4 +1,7 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { once } from 'node:events' +import { createServer } from 'node:http' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { detectCiPullRequestContext } from './detect-ci-pull-request-context.mts' @@ -90,3 +93,128 @@ describe('detectCiPullRequestContext', () => { }) }) }) + +it('uses GH_TOKEN to publish the finished CI report and update comments on rerun', async () => { + const comments: Array<{ id: number; body: string }> = [] + const writes: string[] = [] + const server = createServer(async (request, response) => { + response.setHeader('content-type', 'application/json') + const list = '/repos/example/project/issues/42/comments' + if (request.url?.split('?')[0] === list && request.method === 'GET') { + response.end(JSON.stringify(comments)) + return + } + const chunks: Buffer[] = [] + for await (const chunk of request) { + chunks.push(chunk) + } + const { body } = JSON.parse(Buffer.concat(chunks).toString()) + if (request.method === 'POST' && request.url?.split('?')[0] === list) { + comments.push({ id: comments.length + 1, body }) + } else if (request.method === 'PATCH') { + const comment = comments.find( + item => + request.url === `/repos/example/project/issues/comments/${item.id}`, + ) + if (comment) { + comment.body = body + } + } + writes.push(request.method ?? '') + response.end('{}') + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + try { + const address = server.address() + if (!address || typeof address === 'string') { + throw new Error('Expected a TCP address') + } + vi.stubEnv('GITHUB_API_URL', `http://127.0.0.1:${address.port}`) + vi.stubEnv('SOCKET_CLI_GITHUB_TOKEN', '') + vi.stubEnv('SOCKET_SECURITY_GITHUB_PAT', '') + vi.stubEnv('GITHUB_TOKEN', '') + vi.stubEnv('GH_TOKEN', 'synthetic') + vi.stubEnv('GITHUB_BASE_REF', 'main') + vi.stubEnv('GITHUB_BASE_SHA', 'base-sha') + vi.stubEnv('GITHUB_SERVER_URL', 'https://github.com') + vi.stubEnv('GITHUB_REF', 'refs/pull/42/merge') + vi.stubEnv('GITHUB_REPOSITORY', 'example/project') + vi.stubEnv('SOCKET_CLI_DISABLE_OVERVIEW_COMMENT', '') + vi.stubEnv('SOCKET_CLI_DISABLE_SECURITY_COMMENT', '') + vi.resetModules() + vi.doMock('./fetch-default-org-slug.mts', () => ({ + getDefaultOrgSlug: async () => ({ ok: true, data: 'example' }), + })) + vi.doMock('./select-baseline-scan.mts', () => ({ + selectBaselineScan: async () => ({ ok: true, data: { id: 'base' } }), + })) + const fetchComments = vi.fn(async () => ({ + ok: true, + data: { + diff_scan: { + comments: { overview: 'API overview', alerts: 'API alerts' }, + }, + }, + })) + vi.doMock('../../utils/api.mts', async importOriginal => ({ + ...(await importOriginal()), + queryApiSafeJson: fetchComments, + })) + vi.doMock('../scan/fetch-diff-scan.mts', () => ({ + fetchDiffScan: async () => ({ + ok: true, + data: { + diff_scan: { + id: 'diff-id', + before_full_scan: { id: 'base' }, + after_full_scan: { id: 'test-scan' }, + artifacts: { added: [], updated: [], replaced: [] }, + html_url: null, + }, + }, + }), + })) + vi.doMock('../scan/handle-scan-report.mts', () => ({ + handleScanReport: async () => {}, + })) + vi.doMock('../scan/fetch-supported-scan-file-names.mts', () => ({ + fetchSupportedScanFileNames: async () => ({ ok: true, data: {} }), + })) + vi.doMock('../../utils/path-resolve.mts', () => ({ + getPackageFilesForScan: async () => ['package.json'], + })) + vi.doMock('../scan/fetch-create-org-full-scan.mts', () => ({ + fetchCreateOrgFullScan: async () => ({ + ok: true, + data: { id: 'test-scan' }, + }), + })) + const { handleCi } = await import('./handle-ci.mts') + await handleCi(false) + expect(comments.map(c => c.body)).toEqual([ + expect.stringContaining('API overview'), + expect.stringContaining('API alerts'), + ]) + await handleCi(false) + vi.stubEnv('SOCKET_CLI_DISABLE_OVERVIEW_COMMENT', 'true') + await handleCi(false) + vi.stubEnv('GITHUB_REF', 'refs/heads/main') + await handleCi(false) + expect(fetchComments).toHaveBeenCalledTimes(3) + expect(writes).toEqual(['POST', 'POST', 'PATCH', 'PATCH', 'PATCH']) + expect(comments).toHaveLength(2) + } finally { + vi.unstubAllEnvs() + vi.doUnmock('./fetch-default-org-slug.mts') + vi.doUnmock('./select-baseline-scan.mts') + vi.doUnmock('../../utils/api.mts') + vi.doUnmock('../scan/fetch-diff-scan.mts') + vi.doUnmock('../scan/handle-scan-report.mts') + vi.doUnmock('../scan/fetch-supported-scan-file-names.mts') + vi.doUnmock('../../utils/path-resolve.mts') + vi.doUnmock('../scan/fetch-create-org-full-scan.mts') + vi.resetModules() + await new Promise(resolve => server.close(() => resolve())) + } +}) diff --git a/src/commands/ci/publish-pr-comments.mts b/src/commands/ci/publish-pr-comments.mts new file mode 100644 index 000000000..0f24d83ce --- /dev/null +++ b/src/commands/ci/publish-pr-comments.mts @@ -0,0 +1,74 @@ +import { queryApiSafeJson } from '../../utils/api.mts' +import { upsertPullRequestComment } from '../../utils/github.mts' + +export const PR_OVERVIEW_COMMENT_MARKER = + '' +export const PR_SECURITY_COMMENT_MARKER = + '' + +export async function publishPullRequestComments({ + diffScanId, + disableOverview, + disableSecurity, + orgSlug, + owner, + pullRequest, + repo, + serverUrl, +}: { + diffScanId: string + disableOverview: boolean + disableSecurity: boolean + orgSlug: string + owner: string + pullRequest: number + repo: string + serverUrl: string +}): Promise { + if (disableOverview && disableSecurity) { + return + } + const pullRequestUrl = new URL( + `/${owner}/${repo}/pull/${pullRequest}`, + serverUrl, + ) + const query = new URLSearchParams({ + platform: 'github', + pull_request_url: pullRequestUrl.href, + bot_commands: 'false', + }) + // SDK 4.3.0 does not expose this operation yet. + const result = await queryApiSafeJson<{ + diff_scan?: { comments: { overview: string; alerts: string } } + }>( + `orgs/${encodeURIComponent(orgSlug)}/diff-scans/${encodeURIComponent(diffScanId)}/comments?${query}`, + 'pull request comments', + ) + if (!result.ok) { + throw new Error(result.cause || result.message) + } + const comments = result.data.diff_scan?.comments + if (!comments) { + throw new Error('Socket did not return rendered pull request comments') + } + + if (!disableOverview && comments.overview.trim()) { + await upsertPullRequestComment({ + body: `${PR_OVERVIEW_COMMENT_MARKER}\n${comments.overview}`, + marker: PR_OVERVIEW_COMMENT_MARKER, + owner, + pullRequest, + repo, + }) + } + + if (!disableSecurity && comments.alerts.trim()) { + await upsertPullRequestComment({ + body: `${PR_SECURITY_COMMENT_MARKER}\n${comments.alerts}`, + marker: PR_SECURITY_COMMENT_MARKER, + owner, + pullRequest, + repo, + }) + } +} diff --git a/src/commands/ci/publish-pr-comments.test.mts b/src/commands/ci/publish-pr-comments.test.mts new file mode 100644 index 000000000..1cf80231e --- /dev/null +++ b/src/commands/ci/publish-pr-comments.test.mts @@ -0,0 +1,98 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { + PR_OVERVIEW_COMMENT_MARKER, + PR_SECURITY_COMMENT_MARKER, + publishPullRequestComments, +} from './publish-pr-comments.mts' +import { queryApiSafeJson } from '../../utils/api.mts' +import { upsertPullRequestComment } from '../../utils/github.mts' + +vi.mock('../../utils/api.mts', () => ({ + queryApiSafeJson: vi.fn(), +})) + +vi.mock('../../utils/github.mts', () => ({ + upsertPullRequestComment: vi.fn(), +})) + +const config = { + disableOverview: false, + disableSecurity: false, + diffScanId: 'diff-id', + orgSlug: 'example', + owner: 'SocketDev', + pullRequest: 42, + repo: 'socket-cli', + serverUrl: 'https://github.com', +} + +describe('publishPullRequestComments', () => { + const rendered = { + overview: 'Dependency summary', + alerts: 'Security findings', + } + + beforeEach(() => { + vi.resetAllMocks() + vi.mocked(queryApiSafeJson).mockResolvedValue({ + ok: true, + data: { diff_scan: { comments: rendered } }, + }) + }) + + it('publishes separate marked overview and security comments', async () => { + await publishPullRequestComments(config) + const [route] = vi.mocked(queryApiSafeJson).mock.calls[0]! + const url = new URL(route, 'https://api.socket.dev/v0/') + expect(url.pathname).toBe('/v0/orgs/example/diff-scans/diff-id/comments') + expect(Object.fromEntries(url.searchParams)).toEqual({ + platform: 'github', + pull_request_url: 'https://github.com/SocketDev/socket-cli/pull/42', + bot_commands: 'false', + }) + expect(upsertPullRequestComment).toHaveBeenNthCalledWith(1, { + body: `${PR_OVERVIEW_COMMENT_MARKER}\nDependency summary`, + marker: PR_OVERVIEW_COMMENT_MARKER, + owner: 'SocketDev', + pullRequest: 42, + repo: 'socket-cli', + }) + expect(upsertPullRequestComment).toHaveBeenNthCalledWith(2, { + body: `${PR_SECURITY_COMMENT_MARKER}\nSecurity findings`, + marker: PR_SECURITY_COMMENT_MARKER, + owner: 'SocketDev', + pullRequest: 42, + repo: 'socket-cli', + }) + }) + + it('suppresses each comment type independently', async () => { + await publishPullRequestComments({ + ...config, + disableOverview: true, + }) + expect(upsertPullRequestComment).toHaveBeenCalledTimes(1) + expect(upsertPullRequestComment).toHaveBeenCalledWith( + expect.objectContaining({ marker: PR_SECURITY_COMMENT_MARKER }), + ) + }) + + it('skips empty comments from the API', async () => { + vi.mocked(queryApiSafeJson).mockResolvedValue({ + ok: true, + data: { diff_scan: { comments: { overview: '', alerts: '' } } }, + }) + await publishPullRequestComments(config) + expect(upsertPullRequestComment).not.toHaveBeenCalled() + }) + + it('skips the API request when both comments are disabled', async () => { + await publishPullRequestComments({ + ...config, + disableOverview: true, + disableSecurity: true, + }) + expect(queryApiSafeJson).not.toHaveBeenCalled() + }) +}) diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index e06f466be..b1c504a37 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -93,6 +93,7 @@ export type GeneratedScanFiles = { export type HandleCreateNewScanConfig = { autoManifest: boolean baselineScanId?: string | undefined + onDiffReport?: ((diffScanId: string) => Promise) | undefined branchName: string commitHash: string commitMessage: string @@ -136,6 +137,7 @@ async function createNewScan( defaultBranch, hints = { flags: new Set() }, interactive, + onDiffReport, orgSlug, outputKind, pendingHead, @@ -482,6 +484,7 @@ async function createNewScan( await handlePrDiffScan({ id1: baselineScanId, id2: scanId, + onDiffReport, orgSlug, outputKind, }) diff --git a/src/commands/scan/handle-diff-scan.mts b/src/commands/scan/handle-diff-scan.mts index db96e0f50..c70f5730f 100644 --- a/src/commands/scan/handle-diff-scan.mts +++ b/src/commands/scan/handle-diff-scan.mts @@ -37,11 +37,13 @@ export async function handleDiffScan({ export async function handlePrDiffScan({ id1, id2, + onDiffReport, orgSlug, outputKind, }: { id1: string id2: string + onDiffReport?: ((diffScanId: string) => Promise) | undefined orgSlug: string outputKind: OutputKind }): Promise { @@ -52,4 +54,7 @@ export async function handlePrDiffScan({ outputKind, strictBlocking: false, }) + if (result.ok) { + await onDiffReport?.(result.data.diff_scan.id) + } } diff --git a/src/constants.mts b/src/constants.mts index 263ead084..40970e61d 100644 --- a/src/constants.mts +++ b/src/constants.mts @@ -661,7 +661,8 @@ const LAZY_ENV = () => { envAsString(env['SOCKET_CLI_GITHUB_TOKEN']) || // TODO: Remove undocumented legacy environment variable name. envAsString(env['SOCKET_SECURITY_GITHUB_PAT']) || - GITHUB_TOKEN, + GITHUB_TOKEN || + envAsString(env['GH_TOKEN']), // Make the default API token `undefined`. SOCKET_CLI_NO_API_TOKEN: envAsBoolean(env['SOCKET_CLI_NO_API_TOKEN']), // The absolute location of the npm directory. diff --git a/src/utils/github.mts b/src/utils/github.mts index 1ecc5b7ae..59aaa4b32 100644 --- a/src/utils/github.mts +++ b/src/utils/github.mts @@ -183,7 +183,7 @@ export function getOctokit(): Octokit { auth: SOCKET_CLI_GITHUB_TOKEN, baseUrl: constants.ENV.GITHUB_API_URL, } - debugDir('inspect', { octokitOptions }) + debugDir('inspect', { baseUrl: octokitOptions.baseUrl }) _octokit = new Octokit(octokitOptions) } return _octokit @@ -266,6 +266,44 @@ export async function prExistForBranch( return false } +export async function upsertPullRequestComment({ + body, + marker, + owner, + pullRequest, + repo, +}: { + body: string + marker: string + owner: string + pullRequest: number + repo: string +}): Promise { + const octokit = getOctokit() + const comments = await octokit.paginate(octokit.issues.listComments, { + issue_number: pullRequest, + owner, + per_page: 100, + repo, + }) + const existing = comments.find(comment => comment.body?.includes(marker)) + if (existing) { + await octokit.issues.updateComment({ + body, + comment_id: existing.id, + owner, + repo, + }) + return + } + await octokit.issues.createComment({ + body, + issue_number: pullRequest, + owner, + repo, + }) +} + export async function setGitRemoteGithubRepoUrl( owner: string, repo: string,