Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions docs/commands/ci.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
34 changes: 34 additions & 0 deletions src/commands/ci/handle-ci.mts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -57,6 +59,7 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
)
debugDir('inspect', { orgSlug, cwd, branchName, repoName })

const [owner, repo] = constants.ENV.GITHUB_REPOSITORY.split('/')
await handleCreateNewScan({
autoManifest,
branchName,
Expand All @@ -72,6 +75,37 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
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: [],
Expand Down
130 changes: 129 additions & 1 deletion src/commands/ci/handle-ci.test.mts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -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<typeof import('../../utils/api.mts')>()),
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<void>(resolve => server.close(() => resolve()))
}
})
74 changes: 74 additions & 0 deletions src/commands/ci/publish-pr-comments.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { queryApiSafeJson } from '../../utils/api.mts'
import { upsertPullRequestComment } from '../../utils/github.mts'

export const PR_OVERVIEW_COMMENT_MARKER =
'<!-- socket-overview-comment-actions -->'
export const PR_SECURITY_COMMENT_MARKER =
'<!-- socket-security-comment-actions -->'

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<void> {
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,
})
}
}
98 changes: 98 additions & 0 deletions src/commands/ci/publish-pr-comments.test.mts
Original file line number Diff line number Diff line change
@@ -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()
})
})
Loading
Loading