Skip to content
Open
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,7 @@
!/src/commands/ci/fetch-default-org-slug.test.mts
!/src/commands/ci/handle-ci.mts
!/src/commands/ci/handle-ci.test.mts
!/src/commands/ci/handle-ci-skip.test.mts
!/src/commands/ci/detect-ci-pull-request-context.test.mts
!/src/commands/ci/select-baseline-scan.mts
!/src/commands/ci/select-baseline-scan.test.mts
Expand Down Expand Up @@ -881,6 +882,8 @@
!/src/utils/github.mts
!/src/commands/ci/publish-pr-comments.mts
!/src/commands/ci/publish-pr-comments.test.mts
!/src/commands/ci/skip-unchanged-manifests.mts
!/src/commands/ci/skip-unchanged-manifests.test.mts
!/src/utils/glob-content-dedup.test.mts
!/src/utils/glob.mts
!/src/utils/glob.test.mts
Expand Down
9 changes: 9 additions & 0 deletions docs/commands/ci.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ socket ci
Use `--auto-manifest` to include locally generated manifests for supported
projects. Run `socket ci --help` for all options.

For pull requests, `socket ci` skips the comparison when a clean checkout has
an available base commit, at least one supported manifest is discoverable, and
no supported manifest or lockfile changed in the PR range. The JSON result is
`{ "ok": true, "skipped": true, "reason": "no-manifest-changes" }` so CI can
distinguish this successful no-op from a clean scan. The command runs a normal
scan when the base commit or file patterns are unavailable, the checkout is
dirty, symlinks or submodules make the inputs uncertain, no supported manifests are discoverable, or auto-manifest generation is
enabled.

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
Expand Down
100 changes: 100 additions & 0 deletions src/commands/ci/handle-ci-skip.test.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { afterEach, expect, it, vi } from 'vitest'

const mockFetchSupportedScanFileNames = vi.fn()
const mockGetPackageFilesForScan = vi.fn()
const mockSelectBaselineScan = vi.fn()
const mockHandleCreateNewScan = vi.fn()
const mockLog = vi.fn()

vi.mock('./fetch-default-org-slug.mts', () => ({
getDefaultOrgSlug: async () => ({ ok: true, data: 'org' }),
}))
vi.mock('./detect-ci-pull-request-context.mts', () => ({
detectCiPullRequestContext: async () => ({
baseBranch: 'main',
baseCommitHash: 'a'.repeat(40),
number: 12,
provider: 'github',
}),
}))
vi.mock('./select-baseline-scan.mts', () => ({
selectBaselineScan: mockSelectBaselineScan,
}))
vi.mock('./skip-unchanged-manifests.mts', () => ({
hasTrackedManifestInputs: async (_cwd: string, files: string[]) =>
files.length > 0,
checkCiManifestChanges: async () => ({
decision: 'skip',
changedFiles: ['src/index.ts'],
}),
}))
vi.mock('../../utils/config.mts', () => ({
findSocketYmlSync: () => ({ ok: false }),
}))
vi.mock('../../utils/git.mts', () => ({
detectDefaultBranch: vi.fn(),
getRepoName: vi.fn(async () => 'project'),
gitBranch: vi.fn(async () => 'feature'),
}))
vi.mock('../../utils/logger.mts', () => ({ logger: { log: mockLog } }))
vi.mock('../../utils/path-resolve.mts', () => ({
getPackageFilesForScan: mockGetPackageFilesForScan,
}))
vi.mock('../scan/fetch-supported-scan-file-names.mts', () => ({
fetchSupportedScanFileNames: mockFetchSupportedScanFileNames,
}))
vi.mock('../scan/handle-create-new-scan.mts', () => ({
handleCreateNewScan: mockHandleCreateNewScan,
}))
vi.mock('./publish-pr-comments.mts', () => ({
publishPullRequestComments: vi.fn(),
}))

afterEach(() => {
mockFetchSupportedScanFileNames.mockReset()
mockGetPackageFilesForScan.mockReset()
mockSelectBaselineScan.mockReset()
mockHandleCreateNewScan.mockReset()
mockLog.mockReset()
vi.resetModules()
process.exitCode = undefined
})

it('returns a successful JSON no-op before baseline selection for source-only PRs', async () => {
mockFetchSupportedScanFileNames.mockResolvedValue({
ok: true,
data: { npm: { manifest: { pattern: 'package.json' } } },
})
mockGetPackageFilesForScan.mockResolvedValue(['package.json'])

const { handleCi } = await import('./handle-ci.mts')
await handleCi(false)

expect(mockSelectBaselineScan).not.toHaveBeenCalled()
expect(mockHandleCreateNewScan).not.toHaveBeenCalled()
expect(mockLog).toHaveBeenCalledWith(
'{\n "ok": true,\n "skipped": true,\n "reason": "no-manifest-changes"\n}\n',
)
})

it('keeps normal baseline selection when no supported manifests are discoverable', async () => {
mockFetchSupportedScanFileNames.mockResolvedValue({
ok: true,
data: { npm: { manifest: { pattern: 'package.json' } } },
})
mockGetPackageFilesForScan.mockResolvedValue([])
mockSelectBaselineScan.mockResolvedValue({
ok: false,
message: 'baseline unavailable',
cause: 'No baseline',
})

const { handleCi } = await import('./handle-ci.mts')
await handleCi(false)

expect(mockSelectBaselineScan).toHaveBeenCalledOnce()
expect(mockHandleCreateNewScan).not.toHaveBeenCalled()
expect(JSON.parse(mockLog.mock.calls[0]?.[0] ?? '{}')).toMatchObject({
message: 'baseline unavailable',
})
})
60 changes: 60 additions & 0 deletions src/commands/ci/handle-ci.mts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@ 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 {
checkCiManifestChanges,
hasTrackedManifestInputs,
} from './skip-unchanged-manifests.mts'
import constants from '../../constants.mts'
import { setCiExitCode } from '../../utils/ci-exit-code.mts'
import { findSocketYmlSync } from '../../utils/config.mts'
import { debugDir, debugFn } from '../../utils/debug.mts'
import { envAsBoolean } from '../../utils/env.mts'
import {
Expand All @@ -12,7 +17,9 @@ import {
gitBranch,
} from '../../utils/git.mts'
import { logger } from '../../utils/logger.mts'
import { getPackageFilesForScan } from '../../utils/path-resolve.mts'
import { serializeResultJson } from '../../utils/serialize-result-json.mts'
import { fetchSupportedScanFileNames } from '../scan/fetch-supported-scan-file-names.mts'
import { handleCreateNewScan } from '../scan/handle-create-new-scan.mts'

export async function handleCi(autoManifest: boolean): Promise<void> {
Expand All @@ -33,6 +40,59 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
const pullRequestContext = await detectCiPullRequestContext()
const { number: pullRequest } = pullRequestContext
const cwd = process.cwd()

// Only skip when a clean checkout and an authoritative supported-file list
// prove this PR has no dependency manifest changes. Auto-manifest generation
// can derive dependencies from source/build inputs, so it always scans.
if (pullRequestContext.number && !autoManifest) {
const supportedFilesCResult = await fetchSupportedScanFileNames({
orgSlug,
silence: true,
})
if (supportedFilesCResult.ok) {
const check = await checkCiManifestChanges({
baseCommitHash: pullRequestContext.baseCommitHash,
cwd,
supportedFiles: supportedFilesCResult.data,
})
if (check.decision === 'skip') {
try {
const socketYmlResult = findSocketYmlSync(cwd)
const discoveredFiles = await getPackageFilesForScan(
['.'],
supportedFilesCResult.data,
{
cwd,
config: socketYmlResult.ok
? socketYmlResult.data?.parsed
: undefined,
},
)
if (await hasTrackedManifestInputs(cwd, discoveredFiles)) {
logger.log(
`${JSON.stringify(
{
ok: true,
skipped: true,
reason: 'no-manifest-changes',
},
null,
2,
)}\n`,
)
return
}
} catch (error) {
debugFn(
'warn',
'Manifest discovery failed during CI skip check',
error,
)
}
}
}
}

const branchName = (await gitBranch(cwd)) || (await detectDefaultBranch(cwd))
const repoName = await getRepoName(cwd)
let baselineScanId: string | undefined
Expand Down
131 changes: 131 additions & 0 deletions src/commands/ci/skip-unchanged-manifests.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import path from 'node:path'

import {
filterBySupportedScanFiles,
getSupportedFilePatterns,
} from '../../utils/glob.mts'
import { spawn } from '../../utils/spawn.mts'

import type { SocketSdkSuccessResult } from '@socketsecurity/sdk'

export type CiManifestChangeCheck =
| { decision: 'scan'; reason: string }
| { decision: 'skip'; changedFiles: string[] }

/**
* Returns a skip decision only when Git can prove a clean PR range contains
* no changes to files supported by Socket's org-scoped manifest patterns.
* Git or classification uncertainty always falls back to a regular scan.
*/
export async function checkCiManifestChanges({
baseCommitHash,
cwd,
supportedFiles,
}: {
baseCommitHash: string | undefined
cwd: string
supportedFiles: SocketSdkSuccessResult<'getSupportedFiles'>['data']
}): Promise<CiManifestChangeCheck> {
if (!baseCommitHash) {
return { decision: 'scan', reason: 'missing-base-commit' }
}
if (!/^(?:[\da-f]{40}|[\da-f]{64})$/iu.test(baseCommitHash)) {
return { decision: 'scan', reason: 'invalid-base-commit' }
}
try {
const patterns = getSupportedFilePatterns(supportedFiles)
if (
!patterns.length ||
patterns.some(pattern => pattern === '**/undefined' || pattern === '**/')
) {
return { decision: 'scan', reason: 'no-supported-file-patterns' }
}

const status = await spawn(
'git',
['status', '--porcelain', '--untracked-files=all'],
{ cwd },
)
if (status.stdout.trim()) {
return { decision: 'scan', reason: 'working-tree-not-clean' }
}

// NUL delimiters preserve spaces and unusual characters in paths. The
// three-dot range mirrors PR comparison semantics and fails closed when
// the base commit is absent from a shallow checkout. Raw records expose
// file modes too, so links and submodules can be treated conservatively.
const diff = await spawn(
'git',
['diff', '--raw', '--no-renames', '-z', `${baseCommitHash}...HEAD`],
{ cwd },
)
const rawEntries = diff.stdout.split('\0')
const changedFiles: string[] = []
for (let i = 0; i + 1 < rawEntries.length; i += 2) {
const header = rawEntries[i] ?? ''
if (/^:(?:120000|160000) |^:\d{6} (?:120000|160000) /u.test(header)) {
return { decision: 'scan', reason: 'link-or-submodule-changed' }
}
const file = rawEntries[i + 1]
if (file) {
changedFiles.push(file.replaceAll('\\', '/').replace(/^\.\//u, ''))
}
}

// Configuration changes can alter discovery even when they are not
// dependency manifests themselves, so they must keep the normal scan.
if (
changedFiles.some(file =>
/(^|\/)(?:socket\.json|socket\.ya?ml|\.gitignore|\.gitmodules|pyvenv\.cfg)$/iu.test(
file,
),
)
) {
return { decision: 'scan', reason: 'scan-configuration-changed' }
}
if (!changedFiles.length) {
return { decision: 'scan', reason: 'empty-change-set' }
}

const changedManifests = filterBySupportedScanFiles(
changedFiles,
supportedFiles,
)
return changedManifests.length
? { decision: 'scan', reason: 'supported-manifest-changed' }
: { decision: 'skip', changedFiles }
} catch {
return { decision: 'scan', reason: 'git-range-unavailable' }
}
}

/** Git's diff can only prove that tracked, regular manifest inputs are unchanged. */
export async function hasTrackedManifestInputs(
cwd: string,
discovered: readonly string[],
): Promise<boolean> {
if (!discovered.length) {
return false
}
const { stdout } = await spawn('git', ['ls-files', '--stage', '-z'], {
cwd,
stripAnsi: false,
})
const tracked = new Set<string>()
for (const entry of stdout.split('\0')) {
if (!entry) {
continue
}
// A symlinked manifest or directory can change when only its target changes.
// A submodule's files similarly belong to a different index.
if (!entry.startsWith('100644 ') && !entry.startsWith('100755 ')) {
return false
}
tracked.add(entry.slice(entry.indexOf('\t') + 1))
}
return discovered.every(file =>
tracked.has(
path.relative(cwd, path.resolve(cwd, file)).split(path.sep).join('/'),
),
)
}
Loading
Loading