Skip to content

Commit a57cc18

Browse files
committed
feat(ci): post Socket-rendered pull request comments
1 parent caf28ba commit a57cc18

10 files changed

Lines changed: 396 additions & 3 deletions

File tree

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -879,6 +879,8 @@
879879
!/src/utils/github-errors.mts
880880
!/src/utils/github-errors.test.mts
881881
!/src/utils/github.mts
882+
!/src/commands/ci/publish-pr-comments.mts
883+
!/src/commands/ci/publish-pr-comments.test.mts
882884
!/src/utils/glob-content-dedup.test.mts
883885
!/src/utils/glob.mts
884886
!/src/utils/glob.test.mts

‎docs/commands/ci.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,13 @@ socket ci
1010

1111
Use `--auto-manifest` to include locally generated manifests for supported
1212
projects. Run `socket ci --help` for all options.
13+
14+
On GitHub pull request runs, pass a GitHub token with pull request write
15+
permission in `SOCKET_CLI_GITHUB_TOKEN`, `GITHUB_TOKEN`, or `GH_TOKEN`. The
16+
command posts an overview and a security findings comment, and updates them on
17+
reruns. Socket renders these comments from the PR diff scan using the
18+
Socket API token. The token needs `full-scans:list`, `diff-scans:create`,
19+
and `diff-scans:list` for the diff and its comments.
20+
21+
Set `SOCKET_CLI_DISABLE_OVERVIEW_COMMENT=true` or
22+
`SOCKET_CLI_DISABLE_SECURITY_COMMENT=true` to skip either comment.

‎src/commands/ci/handle-ci.mts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { detectCiPullRequestContext } from './detect-ci-pull-request-context.mts'
22
import { getDefaultOrgSlug } from './fetch-default-org-slug.mts'
3+
import { publishPullRequestComments } from './publish-pr-comments.mts'
34
import { selectBaselineScan } from './select-baseline-scan.mts'
45
import constants from '../../constants.mts'
56
import { setCiExitCode } from '../../utils/ci-exit-code.mts'
67
import { debugDir, debugFn } from '../../utils/debug.mts'
8+
import { envAsBoolean } from '../../utils/env.mts'
79
import {
810
detectDefaultBranch,
911
getRepoName,
@@ -57,6 +59,7 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
5759
)
5860
debugDir('inspect', { orgSlug, cwd, branchName, repoName })
5961

62+
const [owner, repo] = constants.ENV.GITHUB_REPOSITORY.split('/')
6063
await handleCreateNewScan({
6164
autoManifest,
6265
branchName,
@@ -72,6 +75,37 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
7275
pendingHead: true,
7376
pullRequest,
7477
baselineScanId,
78+
onDiffReport: async diffScanId => {
79+
if (
80+
pullRequestContext.provider !== 'github' ||
81+
!owner ||
82+
!repo ||
83+
!constants.ENV.SOCKET_CLI_GITHUB_TOKEN
84+
) {
85+
return
86+
}
87+
try {
88+
await publishPullRequestComments({
89+
diffScanId,
90+
disableOverview: envAsBoolean(
91+
process.env['SOCKET_CLI_DISABLE_OVERVIEW_COMMENT'],
92+
),
93+
disableSecurity: envAsBoolean(
94+
process.env['SOCKET_CLI_DISABLE_SECURITY_COMMENT'],
95+
),
96+
orgSlug,
97+
owner,
98+
pullRequest,
99+
repo,
100+
serverUrl: constants.ENV.GITHUB_SERVER_URL,
101+
})
102+
} catch (error) {
103+
debugFn('warn', 'Could not publish pull request comments', error)
104+
process.stderr.write(
105+
'Socket could not publish the scan comments. Check the Socket API scopes and GitHub pull request write permission.\n',
106+
)
107+
}
108+
},
75109
reach: {
76110
dynamicSbomInference: undefined,
77111
excludePaths: [],

‎src/commands/ci/handle-ci.test.mts‎

Lines changed: 129 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
1+
import { once } from 'node:events'
2+
import { createServer } from 'node:http'
3+
4+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
25

36
import { detectCiPullRequestContext } from './detect-ci-pull-request-context.mts'
47

@@ -90,3 +93,128 @@ describe('detectCiPullRequestContext', () => {
9093
})
9194
})
9295
})
96+
97+
it('uses GH_TOKEN to publish the finished CI report and update comments on rerun', async () => {
98+
const comments: Array<{ id: number; body: string }> = []
99+
const writes: string[] = []
100+
const server = createServer(async (request, response) => {
101+
response.setHeader('content-type', 'application/json')
102+
const list = '/repos/example/project/issues/42/comments'
103+
if (request.url?.split('?')[0] === list && request.method === 'GET') {
104+
response.end(JSON.stringify(comments))
105+
return
106+
}
107+
const chunks: Buffer[] = []
108+
for await (const chunk of request) {
109+
chunks.push(chunk)
110+
}
111+
const { body } = JSON.parse(Buffer.concat(chunks).toString())
112+
if (request.method === 'POST' && request.url?.split('?')[0] === list) {
113+
comments.push({ id: comments.length + 1, body })
114+
} else if (request.method === 'PATCH') {
115+
const comment = comments.find(
116+
item =>
117+
request.url === `/repos/example/project/issues/comments/${item.id}`,
118+
)
119+
if (comment) {
120+
comment.body = body
121+
}
122+
}
123+
writes.push(request.method ?? '')
124+
response.end('{}')
125+
})
126+
server.listen(0, '127.0.0.1')
127+
await once(server, 'listening')
128+
try {
129+
const address = server.address()
130+
if (!address || typeof address === 'string') {
131+
throw new Error('Expected a TCP address')
132+
}
133+
vi.stubEnv('GITHUB_API_URL', `http://127.0.0.1:${address.port}`)
134+
vi.stubEnv('SOCKET_CLI_GITHUB_TOKEN', '')
135+
vi.stubEnv('SOCKET_SECURITY_GITHUB_PAT', '')
136+
vi.stubEnv('GITHUB_TOKEN', '')
137+
vi.stubEnv('GH_TOKEN', 'synthetic')
138+
vi.stubEnv('GITHUB_BASE_REF', 'main')
139+
vi.stubEnv('GITHUB_BASE_SHA', 'base-sha')
140+
vi.stubEnv('GITHUB_SERVER_URL', 'https://github.com')
141+
vi.stubEnv('GITHUB_REF', 'refs/pull/42/merge')
142+
vi.stubEnv('GITHUB_REPOSITORY', 'example/project')
143+
vi.stubEnv('SOCKET_CLI_DISABLE_OVERVIEW_COMMENT', '')
144+
vi.stubEnv('SOCKET_CLI_DISABLE_SECURITY_COMMENT', '')
145+
vi.resetModules()
146+
vi.doMock('./fetch-default-org-slug.mts', () => ({
147+
getDefaultOrgSlug: async () => ({ ok: true, data: 'example' }),
148+
}))
149+
vi.doMock('./select-baseline-scan.mts', () => ({
150+
selectBaselineScan: async () => ({ ok: true, data: { id: 'base' } }),
151+
}))
152+
const fetchComments = vi.fn(async () => ({
153+
ok: true,
154+
data: {
155+
diff_scan: {
156+
comments: { overview: 'API overview', alerts: 'API alerts' },
157+
},
158+
},
159+
}))
160+
vi.doMock('../../utils/api.mts', async importOriginal => ({
161+
...(await importOriginal<typeof import('../../utils/api.mts')>()),
162+
queryApiSafeJson: fetchComments,
163+
}))
164+
vi.doMock('../scan/fetch-diff-scan.mts', () => ({
165+
fetchDiffScan: async () => ({
166+
ok: true,
167+
data: {
168+
diff_scan: {
169+
id: 'diff-id',
170+
before_full_scan: { id: 'base' },
171+
after_full_scan: { id: 'test-scan' },
172+
artifacts: { added: [], updated: [], replaced: [] },
173+
html_url: null,
174+
},
175+
},
176+
}),
177+
}))
178+
vi.doMock('../scan/handle-scan-report.mts', () => ({
179+
handleScanReport: async () => {},
180+
}))
181+
vi.doMock('../scan/fetch-supported-scan-file-names.mts', () => ({
182+
fetchSupportedScanFileNames: async () => ({ ok: true, data: {} }),
183+
}))
184+
vi.doMock('../../utils/path-resolve.mts', () => ({
185+
getPackageFilesForScan: async () => ['package.json'],
186+
}))
187+
vi.doMock('../scan/fetch-create-org-full-scan.mts', () => ({
188+
fetchCreateOrgFullScan: async () => ({
189+
ok: true,
190+
data: { id: 'test-scan' },
191+
}),
192+
}))
193+
const { handleCi } = await import('./handle-ci.mts')
194+
await handleCi(false)
195+
expect(comments.map(c => c.body)).toEqual([
196+
expect.stringContaining('API overview'),
197+
expect.stringContaining('API alerts'),
198+
])
199+
await handleCi(false)
200+
vi.stubEnv('SOCKET_CLI_DISABLE_OVERVIEW_COMMENT', 'true')
201+
await handleCi(false)
202+
vi.stubEnv('GITHUB_REF', 'refs/heads/main')
203+
await handleCi(false)
204+
expect(fetchComments).toHaveBeenCalledTimes(3)
205+
expect(writes).toEqual(['POST', 'POST', 'PATCH', 'PATCH', 'PATCH'])
206+
expect(comments).toHaveLength(2)
207+
} finally {
208+
vi.unstubAllEnvs()
209+
vi.doUnmock('./fetch-default-org-slug.mts')
210+
vi.doUnmock('./select-baseline-scan.mts')
211+
vi.doUnmock('../../utils/api.mts')
212+
vi.doUnmock('../scan/fetch-diff-scan.mts')
213+
vi.doUnmock('../scan/handle-scan-report.mts')
214+
vi.doUnmock('../scan/fetch-supported-scan-file-names.mts')
215+
vi.doUnmock('../../utils/path-resolve.mts')
216+
vi.doUnmock('../scan/fetch-create-org-full-scan.mts')
217+
vi.resetModules()
218+
await new Promise<void>(resolve => server.close(() => resolve()))
219+
}
220+
})
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { queryApiSafeJson } from '../../utils/api.mts'
2+
import { upsertPullRequestComment } from '../../utils/github.mts'
3+
4+
export const PR_OVERVIEW_COMMENT_MARKER =
5+
'<!-- socket-overview-comment-actions -->'
6+
export const PR_SECURITY_COMMENT_MARKER =
7+
'<!-- socket-security-comment-actions -->'
8+
9+
export async function publishPullRequestComments({
10+
diffScanId,
11+
disableOverview,
12+
disableSecurity,
13+
orgSlug,
14+
owner,
15+
pullRequest,
16+
repo,
17+
serverUrl,
18+
}: {
19+
diffScanId: string
20+
disableOverview: boolean
21+
disableSecurity: boolean
22+
orgSlug: string
23+
owner: string
24+
pullRequest: number
25+
repo: string
26+
serverUrl: string
27+
}): Promise<void> {
28+
if (disableOverview && disableSecurity) {
29+
return
30+
}
31+
const pullRequestUrl = new URL(
32+
`/${owner}/${repo}/pull/${pullRequest}`,
33+
serverUrl,
34+
)
35+
const query = new URLSearchParams({
36+
platform: 'github',
37+
pull_request_url: pullRequestUrl.href,
38+
bot_commands: 'false',
39+
})
40+
// SDK 4.3.0 does not expose this operation yet.
41+
const result = await queryApiSafeJson<{
42+
diff_scan?: { comments: { overview: string; alerts: string } }
43+
}>(
44+
`orgs/${encodeURIComponent(orgSlug)}/diff-scans/${encodeURIComponent(diffScanId)}/comments?${query}`,
45+
'pull request comments',
46+
)
47+
if (!result.ok) {
48+
throw new Error(result.cause || result.message)
49+
}
50+
const comments = result.data.diff_scan?.comments
51+
if (!comments) {
52+
throw new Error('Socket did not return rendered pull request comments')
53+
}
54+
55+
if (!disableOverview && comments.overview.trim()) {
56+
await upsertPullRequestComment({
57+
body: `${PR_OVERVIEW_COMMENT_MARKER}\n${comments.overview}`,
58+
marker: PR_OVERVIEW_COMMENT_MARKER,
59+
owner,
60+
pullRequest,
61+
repo,
62+
})
63+
}
64+
65+
if (!disableSecurity && comments.alerts.trim()) {
66+
await upsertPullRequestComment({
67+
body: `${PR_SECURITY_COMMENT_MARKER}\n${comments.alerts}`,
68+
marker: PR_SECURITY_COMMENT_MARKER,
69+
owner,
70+
pullRequest,
71+
repo,
72+
})
73+
}
74+
}
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import { beforeEach, describe, expect, it, vi } from 'vitest'
2+
3+
import {
4+
PR_OVERVIEW_COMMENT_MARKER,
5+
PR_SECURITY_COMMENT_MARKER,
6+
publishPullRequestComments,
7+
} from './publish-pr-comments.mts'
8+
import { queryApiSafeJson } from '../../utils/api.mts'
9+
import { upsertPullRequestComment } from '../../utils/github.mts'
10+
11+
vi.mock('../../utils/api.mts', () => ({
12+
queryApiSafeJson: vi.fn(),
13+
}))
14+
15+
vi.mock('../../utils/github.mts', () => ({
16+
upsertPullRequestComment: vi.fn(),
17+
}))
18+
19+
const config = {
20+
disableOverview: false,
21+
disableSecurity: false,
22+
diffScanId: 'diff-id',
23+
orgSlug: 'example',
24+
owner: 'SocketDev',
25+
pullRequest: 42,
26+
repo: 'socket-cli',
27+
serverUrl: 'https://github.com',
28+
}
29+
30+
describe('publishPullRequestComments', () => {
31+
const rendered = {
32+
overview: 'Dependency summary',
33+
alerts: 'Security findings',
34+
}
35+
36+
beforeEach(() => {
37+
vi.resetAllMocks()
38+
vi.mocked(queryApiSafeJson).mockResolvedValue({
39+
ok: true,
40+
data: { diff_scan: { comments: rendered } },
41+
})
42+
})
43+
44+
it('publishes separate marked overview and security comments', async () => {
45+
await publishPullRequestComments(config)
46+
const [route] = vi.mocked(queryApiSafeJson).mock.calls[0]!
47+
const url = new URL(route, 'https://api.socket.dev/v0/')
48+
expect(url.pathname).toBe('/v0/orgs/example/diff-scans/diff-id/comments')
49+
expect(Object.fromEntries(url.searchParams)).toEqual({
50+
platform: 'github',
51+
pull_request_url: 'https://github.com/SocketDev/socket-cli/pull/42',
52+
bot_commands: 'false',
53+
})
54+
expect(upsertPullRequestComment).toHaveBeenNthCalledWith(1, {
55+
body: `${PR_OVERVIEW_COMMENT_MARKER}\nDependency summary`,
56+
marker: PR_OVERVIEW_COMMENT_MARKER,
57+
owner: 'SocketDev',
58+
pullRequest: 42,
59+
repo: 'socket-cli',
60+
})
61+
expect(upsertPullRequestComment).toHaveBeenNthCalledWith(2, {
62+
body: `${PR_SECURITY_COMMENT_MARKER}\nSecurity findings`,
63+
marker: PR_SECURITY_COMMENT_MARKER,
64+
owner: 'SocketDev',
65+
pullRequest: 42,
66+
repo: 'socket-cli',
67+
})
68+
})
69+
70+
it('suppresses each comment type independently', async () => {
71+
await publishPullRequestComments({
72+
...config,
73+
disableOverview: true,
74+
})
75+
expect(upsertPullRequestComment).toHaveBeenCalledTimes(1)
76+
expect(upsertPullRequestComment).toHaveBeenCalledWith(
77+
expect.objectContaining({ marker: PR_SECURITY_COMMENT_MARKER }),
78+
)
79+
})
80+
81+
it('skips empty comments from the API', async () => {
82+
vi.mocked(queryApiSafeJson).mockResolvedValue({
83+
ok: true,
84+
data: { diff_scan: { comments: { overview: '', alerts: '' } } },
85+
})
86+
await publishPullRequestComments(config)
87+
expect(upsertPullRequestComment).not.toHaveBeenCalled()
88+
})
89+
90+
it('skips the API request when both comments are disabled', async () => {
91+
await publishPullRequestComments({
92+
...config,
93+
disableOverview: true,
94+
disableSecurity: true,
95+
})
96+
expect(queryApiSafeJson).not.toHaveBeenCalled()
97+
})
98+
})

0 commit comments

Comments
 (0)