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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,8 @@
!/src/commands/scan/output-create-new-scan.test.mts
!/src/commands/scan/output-delete-scan.mts
!/src/commands/scan/output-diff-scan.mts
!/src/commands/scan/python-diff-json.mts
!/src/commands/scan/python-diff-json.test.mts
!/src/commands/scan/output-diff-scan.test.mts
!/src/commands/scan/output-list-scans.mts
!/src/commands/scan/output-scan-config-result.mts
Expand Down
1 change: 1 addition & 0 deletions docs/commands/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Guides for Socket CLI commands:
- [cdxgen](cdxgen.md)
- [patch](patch/README.md)
- [ci](ci.md)
- [scan diff](scan-diff.md)

Patch subcommands:

Expand Down
5 changes: 5 additions & 0 deletions docs/commands/ci.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ 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.

Use `--json-format python-v1` to emit a versioned, Python-compatible diff
payload for pull request comparisons. The selector returns a usage error before
scanning when the run is not in a pull request, because no diff can be
calculated. See [scan diff](scan-diff.md) for fields and status meanings.

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
37 changes: 37 additions & 0 deletions docs/commands/scan-diff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# `socket scan diff`

Compare two full scans:

```sh
socket scan diff <BASE_SCAN_ID> <HEAD_SCAN_ID> --json
```

Use `--json-format python-v1` to emit a versioned payload with Python CLI field
names. This selector implies JSON output and cannot be combined with
`--markdown`:

```sh
socket scan diff <BASE_SCAN_ID> <HEAD_SCAN_ID> --json-format python-v1
```

The JSON object includes `schema_version`, `comparison_status`, `decision`,
`scan_failed`, scan and diff identifiers and URLs, alert lists, and direct
package changes under `new_packages`, `updated_packages`, `removed_packages`,
and `replaced_packages`. Package and alert identifiers retain the Socket IDs
and alert keys. Findings include the Python-compatible names such as
`pkg_type`, `pkg_name`, `pkg_version`, `pkg_id`, `key`, `type`, and `severity`.

`new_alerts` contains error and warning findings for changed packages. With
`--strict-blocking`, unchanged blocking findings are included there as well as
in `unchanged_alerts`; duplicate findings are collapsed by package, alert type,
and advisory ID. `removed_alerts` lists alerts from removed packages.

Completed comparisons use empty arrays when a category has no entries. Skipped
comparisons also use empty arrays, with `comparison_status: "skipped"` and
`decision: "not-evaluated"` to distinguish them from a clean comparison. Missing
required diff fields produce `comparison_status: "incomplete"`,
`decision: "unknown"`, and `incomplete_fields`; API errors use the same status
with an `error` object. Unknown scalar package metadata and unavailable IDs or
URLs are `null`. A blocking result has `decision: "fail"`; otherwise the
comparison passes. Native JSON output remains unchanged when the selector is
not used.
14 changes: 13 additions & 1 deletion src/commands/ci/cmd-ci.mts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ const config: CliCommandConfig = {
description:
'Exit code for Socket API errors (default: 3). Ignored with --disable-blocking.',
},
jsonFormat: {
type: 'string',
description:
'Select a versioned JSON payload. Supported: python-v1 (pull request comparisons only).',
},
},
help: (command, _config) => `
Usage
Expand Down Expand Up @@ -109,5 +114,12 @@ async function run(
return
}

await handleCi(Boolean(cli.flags['autoManifest']))
const jsonFormat = String(cli.flags['jsonFormat'] ?? '')
if (jsonFormat && jsonFormat !== 'python-v1') {
logger.fail('--json-format must be python-v1.')
setCiExitCode('usage')
return
}

await handleCi(Boolean(cli.flags['autoManifest']), jsonFormat === 'python-v1')
}
28 changes: 28 additions & 0 deletions src/commands/ci/cmd-ci.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ describe('socket ci', async () => {
--auto-manifest Auto generate manifest files where detected? See autoManifest flag in \`socket scan create\`
--disable-blocking Return success for findings and infrastructure failures, but keep usage errors non-zero.
--exit-code-on-api-error Exit code for Socket API errors (default: 3). Ignored with --disable-blocking.
--json-format Select a versioned JSON payload. Supported: python-v1 (pull request comparisons only).

This command is intended to use in CI runs to allow automated systems to
accept or reject a current build. It will use the default org of the
Expand Down Expand Up @@ -76,4 +77,31 @@ describe('socket ci', async () => {
expect(code, 'dry-run should exit with code 0 if input ok').toBe(0)
},
)

cmdit(
['ci', '--json-format', 'python-v1'],
'should reject Python diff JSON outside a pull request',
async cmd => {
const { code, stdout } = await spawnSocketCli(binCliPath, cmd, {
env: {
GITHUB_REF: '',
GITHUB_BASE_REF: '',
GITHUB_EVENT_PATH: '',
CI_MERGE_REQUEST_IID: '',
SYSTEM_PULLREQUEST_PULLREQUESTNUMBER: '',
SYSTEM_PULLREQUEST_PULLREQUESTID: '',
},
})
expect(code).toBe(2)
expect(JSON.parse(stdout)).toMatchObject({
schema_version: 'python-v1',
comparison_status: 'unsupported',
decision: 'unknown',
error: {
message:
'Python-compatible diff JSON requires a pull request comparison.',
},
})
},
)
})
101 changes: 89 additions & 12 deletions src/commands/ci/handle-ci.mts
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,86 @@ 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'
import {
createPythonDiffJsonFailure,
createSkippedPythonDiffJson,
createUnsupportedPythonDiffJson,
} from '../scan/python-diff-json.mts'

export async function handleCi(autoManifest: boolean): Promise<void> {
export async function handleCi(
autoManifest: boolean,
pythonJsonFormat = false,
): Promise<void> {
debugFn('notice', 'Starting CI scan')
debugDir('inspect', { autoManifest })
debugDir('inspect', { autoManifest, pythonJsonFormat })

const pullRequestContext = await detectCiPullRequestContext()
const { number: pullRequest } = pullRequestContext
const cwd = process.cwd()
const pythonJsonContext = {
repo:
pullRequestContext.provider === 'github'
? constants.ENV.GITHUB_REPOSITORY || null
: pullRequestContext.provider === 'gitlab'
? process.env['CI_PROJECT_PATH'] || null
: pullRequestContext.provider === 'azure'
? process.env['BUILD_REPOSITORY_NAME'] || null
: null,
branch:
pullRequestContext.provider === 'github'
? process.env['GITHUB_HEAD_REF'] || null
: pullRequestContext.provider === 'gitlab'
? process.env['CI_MERGE_REQUEST_SOURCE_BRANCH_NAME'] || null
: pullRequestContext.provider === 'azure'
? (process.env['SYSTEM_PULLREQUEST_SOURCEBRANCH'] || '').replace(
/^refs\/heads\//u,
'',
) || null
: null,
commitSha:
pullRequestContext.provider === 'github'
? process.env['GITHUB_SHA'] || null
: pullRequestContext.provider === 'gitlab'
? process.env['CI_COMMIT_SHA'] || null
: pullRequestContext.provider === 'azure'
? process.env['BUILD_SOURCEVERSION'] || null
: null,
}
if (pythonJsonFormat && !pullRequest) {
setCiExitCode('usage')
logger.log(
`${JSON.stringify(
createUnsupportedPythonDiffJson(pythonJsonContext),
null,
2,
)}\n`,
)
return
}

const orgSlugCResult = await getDefaultOrgSlug()
if (!orgSlugCResult.ok) {
debugFn('warn', 'Failed to get default org slug')
debugDir('inspect', { orgSlugCResult })
setCiExitCode('api', orgSlugCResult.code ?? 1)
// Always assume json mode.
logger.log(serializeResultJson(orgSlugCResult))
logger.log(
pythonJsonFormat
? `${JSON.stringify(
createPythonDiffJsonFailure(
orgSlugCResult.message,
orgSlugCResult.cause,
pythonJsonContext,
),
null,
2,
)}\n`
: serializeResultJson(orgSlugCResult),
)
return
}

const orgSlug = orgSlugCResult.data
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
Expand Down Expand Up @@ -71,11 +132,13 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
if (await hasTrackedManifestInputs(cwd, discoveredFiles)) {
logger.log(
`${JSON.stringify(
{
ok: true,
skipped: true,
reason: 'no-manifest-changes',
},
pythonJsonFormat
? createSkippedPythonDiffJson(pythonJsonContext)
: {
ok: true,
skipped: true,
reason: 'no-manifest-changes',
},
null,
2,
)}\n`,
Expand Down Expand Up @@ -106,7 +169,19 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
})
if (!baselineCResult.ok) {
process.exitCode = baselineCResult.code ?? 1
logger.log(serializeResultJson(baselineCResult))
logger.log(
pythonJsonFormat
? `${JSON.stringify(
createPythonDiffJsonFailure(
baselineCResult.message,
baselineCResult.cause,
pythonJsonContext,
),
null,
2,
)}\n`
: serializeResultJson(baselineCResult),
)
return
}
baselineScanId = baselineCResult.data.id
Expand All @@ -131,6 +206,8 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
interactive: false,
orgSlug,
outputKind: 'json',
pythonJsonFormat,
pythonJsonContext,
// When 'pendingHead' is true, it requires 'branchName' set and 'tmp' false.
pendingHead: true,
pullRequest,
Expand Down
23 changes: 22 additions & 1 deletion src/commands/scan/cmd-scan-diff.mts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ async function run(
description:
'Fail when unchanged blocking alerts are present in the scan diff',
},
jsonFormat: {
type: 'string',
description:
'Select a versioned JSON payload; python-v1 implies --json and cannot be combined with --markdown.',
},
},
help: (command, config) => `
Usage
Expand Down Expand Up @@ -112,6 +117,7 @@ async function run(
dryRun,
file,
json,
jsonFormat,
markdown,
org: orgFlag,
strictBlocking,
Expand All @@ -123,7 +129,9 @@ async function run(
markdown: boolean
org: string
strictBlocking: boolean
jsonFormat: string
}
const pythonJsonFormat = jsonFormat === 'python-v1'

const interactive = !!cli.flags['interactive']

Expand All @@ -144,7 +152,7 @@ async function run(
dryRun,
)

const outputKind = getOutputKind(json, markdown)
const outputKind = pythonJsonFormat ? 'json' : getOutputKind(json, markdown)

const wasValidInput = checkCommandInput(
outputKind,
Expand All @@ -171,6 +179,18 @@ async function run(
message: `The \`${FLAG_JSON}\` and \`${FLAG_MARKDOWN}\` flags can not be used at the same time`,
fail: 'bad',
},
{
nook: true,
test: !jsonFormat || pythonJsonFormat,
message: 'Supported versioned JSON format: python-v1',
fail: `unsupported format ${jsonFormat}`,
},
{
nook: true,
test: !pythonJsonFormat || !markdown,
message: '--json-format python-v1 cannot be combined with --markdown',
fail: 'bad',
},
{
nook: true,
test: dryRun || hasApiToken,
Expand All @@ -195,5 +215,6 @@ async function run(
outputKind,
file,
strictBlocking,
pythonJsonFormat,
})
}
Loading
Loading