From 0c66c6258106edaf9b36343ef735a31e79de92da Mon Sep 17 00:00:00 2001 From: jdalton Date: Wed, 2 Dec 2026 12:57:01 -0500 Subject: [PATCH] feat(python-cli-parity): support Python-compatible diff JSON output --- .gitignore | 2 + docs/commands/README.md | 1 + docs/commands/ci.md | 5 + docs/commands/scan-diff.md | 37 ++ src/commands/ci/cmd-ci.mts | 14 +- src/commands/ci/cmd-ci.test.mts | 28 + src/commands/ci/handle-ci.mts | 101 +++- src/commands/scan/cmd-scan-diff.mts | 23 +- src/commands/scan/cmd-scan-diff.test.mts | 49 ++ src/commands/scan/fetch-diff-scan.mts | 1 + src/commands/scan/handle-create-new-scan.mts | 35 +- src/commands/scan/handle-diff-scan.mts | 13 + src/commands/scan/output-create-new-scan.mts | 27 + src/commands/scan/output-diff-scan.mts | 43 ++ src/commands/scan/python-diff-json.mts | 527 ++++++++++++++++++ src/commands/scan/python-diff-json.test.mts | 312 +++++++++++ .../termless/cli.native.socket-help-ci.svg | 44 +- .../cli.native.socket-help-scan-diff.svg | 24 +- 18 files changed, 1237 insertions(+), 49 deletions(-) create mode 100644 docs/commands/scan-diff.md create mode 100644 src/commands/scan/python-diff-json.mts create mode 100644 src/commands/scan/python-diff-json.test.mts diff --git a/.gitignore b/.gitignore index a91c7573f..50b4098bd 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/docs/commands/README.md b/docs/commands/README.md index e88b5bbd0..f30a6ecb6 100644 --- a/docs/commands/README.md +++ b/docs/commands/README.md @@ -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: diff --git a/docs/commands/ci.md b/docs/commands/ci.md index b11fa1c68..fdd1db5eb 100644 --- a/docs/commands/ci.md +++ b/docs/commands/ci.md @@ -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 diff --git a/docs/commands/scan-diff.md b/docs/commands/scan-diff.md new file mode 100644 index 000000000..b6b000c62 --- /dev/null +++ b/docs/commands/scan-diff.md @@ -0,0 +1,37 @@ +# `socket scan diff` + +Compare two full scans: + +```sh +socket scan diff --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 --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. diff --git a/src/commands/ci/cmd-ci.mts b/src/commands/ci/cmd-ci.mts index 81e76c896..880993cb8 100644 --- a/src/commands/ci/cmd-ci.mts +++ b/src/commands/ci/cmd-ci.mts @@ -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 @@ -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') } diff --git a/src/commands/ci/cmd-ci.test.mts b/src/commands/ci/cmd-ci.test.mts index b429e6761..86b2c5173 100644 --- a/src/commands/ci/cmd-ci.test.mts +++ b/src/commands/ci/cmd-ci.test.mts @@ -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 @@ -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.', + }, + }) + }, + ) }) diff --git a/src/commands/ci/handle-ci.mts b/src/commands/ci/handle-ci.mts index e2075db70..bbee9c47a 100644 --- a/src/commands/ci/handle-ci.mts +++ b/src/commands/ci/handle-ci.mts @@ -21,10 +21,62 @@ 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 { +export async function handleCi( + autoManifest: boolean, + pythonJsonFormat = false, +): Promise { 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) { @@ -32,14 +84,23 @@ export async function handleCi(autoManifest: boolean): Promise { 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 @@ -71,11 +132,13 @@ export async function handleCi(autoManifest: boolean): Promise { 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`, @@ -106,7 +169,19 @@ export async function handleCi(autoManifest: boolean): Promise { }) 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 @@ -131,6 +206,8 @@ export async function handleCi(autoManifest: boolean): Promise { interactive: false, orgSlug, outputKind: 'json', + pythonJsonFormat, + pythonJsonContext, // When 'pendingHead' is true, it requires 'branchName' set and 'tmp' false. pendingHead: true, pullRequest, diff --git a/src/commands/scan/cmd-scan-diff.mts b/src/commands/scan/cmd-scan-diff.mts index 81b2eb9dd..6165f6985 100644 --- a/src/commands/scan/cmd-scan-diff.mts +++ b/src/commands/scan/cmd-scan-diff.mts @@ -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 @@ -112,6 +117,7 @@ async function run( dryRun, file, json, + jsonFormat, markdown, org: orgFlag, strictBlocking, @@ -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'] @@ -144,7 +152,7 @@ async function run( dryRun, ) - const outputKind = getOutputKind(json, markdown) + const outputKind = pythonJsonFormat ? 'json' : getOutputKind(json, markdown) const wasValidInput = checkCommandInput( outputKind, @@ -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, @@ -195,5 +215,6 @@ async function run( outputKind, file, strictBlocking, + pythonJsonFormat, }) } diff --git a/src/commands/scan/cmd-scan-diff.test.mts b/src/commands/scan/cmd-scan-diff.test.mts index 38636ceb1..e4c7133f5 100644 --- a/src/commands/scan/cmd-scan-diff.test.mts +++ b/src/commands/scan/cmd-scan-diff.test.mts @@ -42,6 +42,7 @@ describe('socket scan diff', async () => { --interactive Allow for interactive elements, asking for input. Use --no-interactive to prevent any input questions, defaulting them to cancel/no. --json Output as JSON + --json-format Select a versioned JSON payload; python-v1 implies --json and cannot be combined with --markdown. --markdown Output as Markdown --org Force override the organization slug, overrides the default org from config --strict-blocking Fail when unchanged blocking alerts are present in the scan diff @@ -123,4 +124,52 @@ describe('socket scan diff', async () => { expect(code, 'dry-run should exit with code 0 if input ok').toBe(0) }, ) + + cmdit( + [ + 'scan', + 'diff', + '--json-format', + 'python-v1', + FLAG_ORG, + 'fakeOrg', + FLAG_DRY_RUN, + FLAG_CONFIG, + '{"apiToken":"fakeToken"}', + 'before-id', + 'after-id', + ], + 'should select Python JSON without requiring --json', + async cmd => { + const { code, stdout } = await spawnSocketCli(binCliPath, cmd) + expect(code).toBe(0) + expect(stdout).toBe('[DryRun]: Bailing now') + }, + ) + + cmdit( + [ + 'scan', + 'diff', + '--json-format', + 'python-v1', + FLAG_MARKDOWN, + FLAG_ORG, + 'fakeOrg', + FLAG_DRY_RUN, + FLAG_CONFIG, + '{"apiToken":"fakeToken"}', + 'before-id', + 'after-id', + ], + 'should reject Python JSON with Markdown output', + async cmd => { + const { code, stdout } = await spawnSocketCli(binCliPath, cmd) + expect(code).toBe(2) + expect(stdout).toContain('Input error') + expect(stdout).toContain( + '--json-format python-v1 cannot be combined with --markdown', + ) + }, + ) }) diff --git a/src/commands/scan/fetch-diff-scan.mts b/src/commands/scan/fetch-diff-scan.mts index 8e5a3b78d..fc5cfad42 100644 --- a/src/commands/scan/fetch-diff-scan.mts +++ b/src/commands/scan/fetch-diff-scan.mts @@ -20,6 +20,7 @@ export type DiffScanData = { before_full_scan: ExistingDiffScan['before'] after_full_scan: ExistingDiffScan['after'] html_url: string | null + incomplete?: boolean | undefined artifacts: ExistingDiffScan['artifacts'] } } diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index bf0d4ac1b..54ab2c88c 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -17,6 +17,7 @@ import { } from './run-dynamic-sbom-inference.mts' import constants from '../../constants.mts' import { checkCommandInput } from '../../utils/check-input.mts' +import { setCiExitCode } from '../../utils/ci-exit-code.mts' import { compressSocketFactsForUpload, isFactsOnlyTypes, @@ -41,6 +42,7 @@ import { import { buildToolsFor } from '../manifest/scripts/build-tool.mts' import type { ReachabilityFallback } from './output-create-new-scan.mts' +import type { PythonDiffJsonContext } from './python-diff-json.mts' import type { ReachabilityOptions } from './perform-reachability-analysis.mts' import type { REPORT_LEVEL } from './types.mts' import type { OutputKind } from '../../types.mts' @@ -105,6 +107,8 @@ export type HandleCreateNewScanConfig = { baselineScanId?: string | undefined bazel?: BazelScan | undefined onDiffReport?: ((diffScanId: string) => Promise) | undefined + pythonJsonFormat?: boolean | undefined + pythonJsonContext?: PythonDiffJsonContext | undefined branchName: string commitHash: string commitMessage: string @@ -186,6 +190,8 @@ async function createNewScan( outputKind, pendingHead, pullRequest, + pythonJsonContext, + pythonJsonFormat = false, reach: requestedReach, readOnly, repoName, @@ -337,6 +343,8 @@ async function createNewScan( failureKind: 'api', interactive, outputKind, + pythonJsonFormat, + pythonJsonContext, }) return } @@ -378,15 +386,25 @@ async function createNewScan( `Found ${packagePaths.length} ${pluralize('file', packagePaths.length)} to include in scan.`, ) - const wasValidInput = checkCommandInput(outputKind, { + const inputFailure = { nook: true, test: packagePaths.length > 0, fail: `found no eligible files to scan. See supported manifest files at ${socketDocsLink('/docs/manifest-file-detection-in-socket', 'docs.socket.dev')}`, message: 'TARGET (file/dir) must contain matching / supported file types for a scan', - }) + } + const wasValidInput = pythonJsonFormat + ? inputFailure.test + : checkCommandInput(outputKind, inputFailure) if (!wasValidInput) { debugFn('warn', 'No eligible files found to scan') + if (pythonJsonFormat) { + await outputCreateNewScan( + { ok: false, message: 'Input error', cause: inputFailure.fail }, + { outputKind, pythonJsonFormat, pythonJsonContext }, + ) + setCiExitCode('usage') + } return } @@ -451,7 +469,12 @@ async function createNewScan( `Reachability analysis failed: ${reachResult.message}${reachResult.cause ? ` — ${reachResult.cause}` : ''}. Falling back to a regular SCA scan without reachability results.`, ) } else { - await outputCreateNewScan(reachResult, { interactive, outputKind }) + await outputCreateNewScan(reachResult, { + interactive, + outputKind, + pythonJsonFormat, + pythonJsonContext, + }) return } } else { @@ -566,6 +589,8 @@ async function createNewScan( onDiffReport, orgSlug, outputKind, + pythonJsonFormat, + pythonJsonContext, }) } else { await handleScanReport({ @@ -591,6 +616,8 @@ async function createNewScan( failureKind: 'api', interactive, outputKind, + pythonJsonFormat, + pythonJsonContext, reachabilityFallback, }, ) @@ -602,6 +629,8 @@ async function createNewScan( failureKind: 'api', interactive, outputKind, + pythonJsonFormat, + pythonJsonContext, reachabilityFallback, }) } diff --git a/src/commands/scan/handle-diff-scan.mts b/src/commands/scan/handle-diff-scan.mts index c70f5730f..eba8862b0 100644 --- a/src/commands/scan/handle-diff-scan.mts +++ b/src/commands/scan/handle-diff-scan.mts @@ -1,6 +1,7 @@ import { fetchDiffScan } from './fetch-diff-scan.mts' import { outputDiffScan } from './output-diff-scan.mts' +import type { PythonDiffJsonContext } from './python-diff-json.mts' import type { OutputKind } from '../../types.mts' export async function handleDiffScan({ @@ -10,6 +11,8 @@ export async function handleDiffScan({ id2, orgSlug, outputKind, + pythonJsonContext = {}, + pythonJsonFormat = false, strictBlocking, }: { depth: number @@ -19,6 +22,8 @@ export async function handleDiffScan({ orgSlug: string outputKind: OutputKind strictBlocking: boolean + pythonJsonFormat?: boolean | undefined + pythonJsonContext?: PythonDiffJsonContext | undefined }): Promise { const data = await fetchDiffScan({ id1, @@ -31,6 +36,8 @@ export async function handleDiffScan({ file, outputKind, strictBlocking, + pythonJsonFormat, + pythonJsonContext, }) } @@ -40,12 +47,16 @@ export async function handlePrDiffScan({ onDiffReport, orgSlug, outputKind, + pythonJsonContext = {}, + pythonJsonFormat = false, }: { id1: string id2: string onDiffReport?: ((diffScanId: string) => Promise) | undefined orgSlug: string outputKind: OutputKind + pythonJsonFormat?: boolean | undefined + pythonJsonContext?: PythonDiffJsonContext | undefined }): Promise { const result = await fetchDiffScan({ id1, id2, orgSlug }) await outputDiffScan(result, { @@ -53,6 +64,8 @@ export async function handlePrDiffScan({ file: '', outputKind, strictBlocking: false, + pythonJsonFormat, + pythonJsonContext, }) if (result.ok) { await onDiffReport?.(result.data.diff_scan.id) diff --git a/src/commands/scan/output-create-new-scan.mts b/src/commands/scan/output-create-new-scan.mts index 2a6f0321f..6fc45afa1 100644 --- a/src/commands/scan/output-create-new-scan.mts +++ b/src/commands/scan/output-create-new-scan.mts @@ -1,6 +1,10 @@ import open from 'open' import terminalLink from 'terminal-link' +import { + type PythonDiffJsonContext, + createPythonDiffJsonFailure, +} from './python-diff-json.mts' import constants from '../../constants.mts' import { setCiExitCode } from '../../utils/ci-exit-code.mts' import { failMsgWithBadge } from '../../utils/fail-msg-with-badge.mts' @@ -21,6 +25,8 @@ export type CreateNewScanOptions = { failureKind?: 'api' | 'infrastructure' | undefined interactive?: boolean | undefined outputKind?: OutputKind | undefined + pythonJsonFormat?: boolean | undefined + pythonJsonContext?: PythonDiffJsonContext | undefined // Set when --reach-fallback-to-regular-scan downgraded the run, so machine // consumers can tell a degraded scan from a full one. reachabilityFallback?: ReachabilityFallback | undefined @@ -35,6 +41,8 @@ export async function outputCreateNewScan( failureKind = 'infrastructure', interactive = false, outputKind = 'text', + pythonJsonContext, + pythonJsonFormat = false, reachabilityFallback, spinner = constants.spinner, } = { __proto__: null, ...options } as CreateNewScanOptions @@ -48,6 +56,25 @@ export async function outputCreateNewScan( spinner?.stop() if (outputKind === 'json') { + if (pythonJsonFormat) { + const error = result.ok + ? createPythonDiffJsonFailure( + 'Scan comparison could not be completed', + 'The full scan did not return a usable scan ID.', + pythonJsonContext, + ) + : createPythonDiffJsonFailure( + result.message, + result.cause, + pythonJsonContext, + ) + logger.log(`${JSON.stringify(error, null, 2)}\n`) + if (wasSpinning) { + spinner.start() + } + return + } + const payload: CResult & { reachabilityFallback?: ReachabilityFallback | undefined } = reachabilityFallback ? { ...result, reachabilityFallback } : result diff --git a/src/commands/scan/output-diff-scan.mts b/src/commands/scan/output-diff-scan.mts index d40f236bf..edbc85e26 100644 --- a/src/commands/scan/output-diff-scan.mts +++ b/src/commands/scan/output-diff-scan.mts @@ -3,6 +3,10 @@ import util from 'node:util' import colors from 'yoctocolors-cjs' +import { + type PythonDiffJsonContext, + mapDiffScanToPythonJson, +} from './python-diff-json.mts' import constants from '../../constants.mts' import { setCiExitCode } from '../../utils/ci-exit-code.mts' import { failMsgWithBadge } from '../../utils/fail-msg-with-badge.mts' @@ -19,14 +23,34 @@ export async function outputDiffScan( depth, file, outputKind, + pythonJsonContext = {}, + pythonJsonFormat = false, strictBlocking, }: { depth: number file: string outputKind: OutputKind strictBlocking: boolean + pythonJsonFormat?: boolean | undefined + pythonJsonContext?: PythonDiffJsonContext | undefined }, ): Promise { + if (pythonJsonFormat) { + const payload = mapDiffScanToPythonJson(result, { + ...pythonJsonContext, + strictBlocking, + }) + if (!result.ok) { + setCiExitCode('api', result.code ?? 1) + } else if (payload.decision === 'fail') { + setCiExitCode('blocking') + } else if (payload.decision === 'unknown') { + setCiExitCode('infrastructure') + } + await handlePythonJson(payload, file) + return + } + if (!result.ok) { setCiExitCode('api', result.code ?? 1) if (outputKind === 'json') { @@ -97,6 +121,25 @@ export async function outputDiffScan( logger.info(dashboardMessage) } +async function handlePythonJson( + payload: ReturnType, + file: string, +): Promise { + const json = `${JSON.stringify(payload, null, 2)}\n` + if (file && file !== '-') { + try { + await fs.promises.writeFile(file, json) + logger.success(`Data successfully written to \`${fileLink(file)}\``) + } catch (error) { + setCiExitCode('infrastructure') + logger.fail(`Writing to \`${file}\` failed...`) + logger.error(error) + } + return + } + logger.log(json) +} + async function handleJson( data: CResult, file: string, diff --git a/src/commands/scan/python-diff-json.mts b/src/commands/scan/python-diff-json.mts new file mode 100644 index 000000000..ec0027d16 --- /dev/null +++ b/src/commands/scan/python-diff-json.mts @@ -0,0 +1,527 @@ +import type { DiffScanData } from './fetch-diff-scan.mts' +import constants from '../../constants.mts' +import type { CResult } from '../../types.mts' +import { createPurlObject } from '../../utils/purl.mts' + +type DiffScan = DiffScanData['diff_scan'] +type DiffArtifact = DiffScan['artifacts']['added'][number] +type DiffArtifactGroup = keyof DiffScan['artifacts'] +type DiffArtifacts = DiffScan['artifacts'] +type ArtifactLink = NonNullable[number] +type SocketAlert = NonNullable[number] + +export type PythonDiffJsonContext = { + branch?: string | null | undefined + commitSha?: string | null | undefined + legalMode?: boolean | undefined + repo?: string | null | undefined + strictBlocking?: boolean | undefined +} + +export type PythonCompatiblePackage = { + id: string | null + name: string | null + version: string | null + ecosystem: string | null + direct: boolean + author: string[] + size: number | null + transitives: number | null + introduced_by: Array<[string, string]> + capabilities: string[] + is_new: boolean + author_url: string | null + url: string | null + purl: string | null +} + +export type PythonCompatibleAlert = { + pkg_type: string | null + pkg_name: string | null + pkg_version: string | null + pkg_id: string | null + props: Record + key: string + type: string + severity: string | null + category: string | null + action: string | null + error: boolean + warn: boolean + ignore: boolean + monitor: boolean + description: string | null + title: string | null + suggestion: string | null + next_step_title: string | null + introduced_by: Array<[string, string]> + manifests: string + manifest_files: Array<{ file: string; start?: number; end?: number }> + direct: boolean + purl: string | null + url: string | null + file: string | null + start: number | null + end: number | null +} + +export type PythonDiffJson = { + schema_version: 'python-v1' + comparison_status: 'complete' | 'skipped' | 'incomplete' | 'unsupported' + decision: 'pass' | 'fail' | 'not-evaluated' | 'unknown' + scan_failed: boolean + new_alerts: PythonCompatibleAlert[] + unchanged_alerts: PythonCompatibleAlert[] + removed_alerts: PythonCompatibleAlert[] + new_packages: PythonCompatiblePackage[] + updated_packages: PythonCompatiblePackage[] + removed_packages: PythonCompatiblePackage[] + replaced_packages: PythonCompatiblePackage[] + full_scan_id: string | null + base_scan_id: string | null + head_scan_id: string | null + diff_scan_id: string | null + diff_url: string | null + report_url: string | null + repo: string | null + branch: string | null + commit_sha: string | null + legal_mode: boolean + incomplete_fields?: string[] + error?: { message: string; cause?: string | null } +} + +const emptyArrays = { + new_alerts: [], + unchanged_alerts: [], + removed_alerts: [], + new_packages: [], + updated_packages: [], + removed_packages: [], + replaced_packages: [], +} satisfies Pick< + PythonDiffJson, + | 'new_alerts' + | 'unchanged_alerts' + | 'removed_alerts' + | 'new_packages' + | 'updated_packages' + | 'removed_packages' + | 'replaced_packages' +> + +function packagePurl(artifact: DiffArtifact): string | null { + const { name, namespace, type, version } = artifact + if (!type || !name) { + return null + } + const purl = createPurlObject({ + type, + namespace, + name, + version, + throws: false, + }) + return purl?.toString().replace(/^pkg:/u, '') ?? null +} + +function packageUrl(artifact: DiffArtifact): string | null { + const { name, namespace, type, version } = artifact + if (!type || !name || !version) { + return null + } + const packagePath = `${namespace ? `${namespace.replace(/^\/+|\/+$/gu, '')}/` : ''}${name}` + return `${constants.SOCKET_WEBSITE_URL}/${type}/package/${packagePath}/overview/${version}` +} + +function authorUrl(artifact: DiffArtifact): string | null { + if (!artifact.type || !artifact.author?.length) { + return null + } + return artifact.author + .map( + author => + `[${author}](https://socket.dev/${artifact.type}/user/${author})`, + ) + .join(',') +} + +function getLinks( + artifact: DiffArtifact, + group: DiffArtifactGroup, +): ArtifactLink[] { + const state = group === 'removed' ? artifact.base : artifact.head + return state ?? [] +} + +function getManifestFiles( + artifact: DiffArtifact, + group: DiffArtifactGroup, +): PythonCompatibleAlert['manifest_files'] { + return getLinks(artifact, group).flatMap(link => link.manifestFiles ?? []) +} + +function getDirect(artifact: DiffArtifact, group: DiffArtifactGroup): boolean { + return getLinks(artifact, group).some(link => link.direct === true) +} + +function getIntroducedBy( + manifestFiles: PythonCompatibleAlert['manifest_files'], + direct: boolean, +): Array<[string, string]> { + const files = manifestFiles.map(({ file }) => file).filter(Boolean) + return direct && files.length ? [['direct', files.join(';')]] : [] +} + +function packageFromArtifact( + artifact: DiffArtifact, + group: DiffArtifactGroup, +): PythonCompatiblePackage { + const direct = getDirect(artifact, group) + const manifestFiles = getManifestFiles(artifact, group) + const purl = packagePurl(artifact) + const capabilityNames: Record = { + envVars: 'Environment Variables', + networkAccess: 'Network Access', + filesystemAccess: 'File System Access', + shellAccess: 'Shell Access', + usesEval: 'Uses Eval', + unsafe: 'Unsafe', + } + const capabilities = + artifact.alerts + ?.flatMap(alert => + capabilityNames[alert.type] ? [capabilityNames[alert.type]!] : [], + ) + .filter((value, index, values) => values.indexOf(value) === index) + .sort() ?? [] + return { + id: artifact.id ?? null, + name: artifact.name ?? null, + version: artifact.version ?? null, + ecosystem: artifact.type ?? null, + direct, + author: artifact.author ?? [], + size: artifact.size ?? null, + transitives: null, + introduced_by: getIntroducedBy(manifestFiles, direct), + capabilities, + is_new: false, + author_url: authorUrl(artifact), + url: packageUrl(artifact), + purl, + } +} + +function alertFromArtifact( + artifact: DiffArtifact, + alert: SocketAlert, + group: DiffArtifactGroup, +): PythonCompatibleAlert { + const manifestFiles = getManifestFiles(artifact, group) + const direct = getDirect(artifact, group) + const introducedBy = getIntroducedBy(manifestFiles, direct) + return { + pkg_type: artifact.type ?? null, + pkg_name: artifact.name ?? null, + pkg_version: artifact.version ?? null, + pkg_id: artifact.id ?? null, + props: alert.props ?? {}, + key: alert.key, + type: alert.type, + severity: alert.severity ?? null, + category: alert.category ?? null, + action: alert.action ?? null, + error: alert.action === 'error', + warn: alert.action === 'warn', + ignore: alert.action === 'ignore', + monitor: alert.action === 'monitor', + description: null, + title: null, + suggestion: alert.fix?.description ?? null, + next_step_title: null, + introduced_by: introducedBy, + manifests: introducedBy.map(([, files]) => files).join(';'), + manifest_files: manifestFiles, + direct, + purl: packagePurl(artifact), + url: packageUrl(artifact), + file: alert.file ?? null, + start: alert.start ?? null, + end: alert.end ?? null, + } +} + +function sortedArtifacts(artifacts: DiffArtifact[]): DiffArtifact[] { + return [...artifacts].sort((a, b) => + `${a.type ?? ''}\0${a.namespace ?? ''}\0${a.name ?? ''}\0${a.version ?? ''}\0${a.id ?? ''}`.localeCompare( + `${b.type ?? ''}\0${b.namespace ?? ''}\0${b.name ?? ''}\0${b.version ?? ''}\0${b.id ?? ''}`, + ), + ) +} + +function sortedAlerts( + alerts: PythonCompatibleAlert[], +): PythonCompatibleAlert[] { + return alerts.sort((a, b) => + `${a.pkg_type ?? ''}\0${a.purl ?? ''}\0${a.type}\0${a.key}`.localeCompare( + `${b.pkg_type ?? ''}\0${b.purl ?? ''}\0${b.type}\0${b.key}`, + ), + ) +} + +function alertIdentity(alert: PythonCompatibleAlert): string | undefined { + if (!alert.purl) { + return undefined + } + const props = alert.props + const advisory = [props['ghsaId'], props['cveId']].find( + value => typeof value === 'string' && value.trim(), + ) + return [alert.pkg_type, alert.purl, alert.type, advisory ?? ''] + .map(value => + String(value ?? '') + .trim() + .toLowerCase(), + ) + .join('\0') +} + +function selectOutputAlerts( + changed: PythonCompatibleAlert[], + unchanged: PythonCompatibleAlert[], + strictBlocking: boolean, +): PythonCompatibleAlert[] { + const selected = [...changed] + if (!strictBlocking) { + return sortedAlerts(selected) + } + const seen = new Set(selected.map(alertIdentity).filter(Boolean)) + for (const alert of unchanged) { + const identity = alertIdentity(alert) + if (!identity || !seen.has(identity)) { + selected.push(alert) + if (identity) { + seen.add(identity) + } + } + } + return sortedAlerts(selected) +} + +function isArtifactArray(value: unknown): value is DiffArtifact[] { + return Array.isArray(value) +} + +function emptyPythonDiffJson( + comparisonStatus: PythonDiffJson['comparison_status'], + decision: PythonDiffJson['decision'], + context: PythonDiffJsonContext, +): PythonDiffJson { + return { + schema_version: 'python-v1', + comparison_status: comparisonStatus, + decision, + scan_failed: false, + ...emptyArrays, + full_scan_id: null, + base_scan_id: null, + head_scan_id: null, + diff_scan_id: null, + diff_url: null, + report_url: null, + repo: context.repo ?? null, + branch: context.branch ?? null, + commit_sha: context.commitSha ?? null, + legal_mode: context.legalMode ?? false, + } +} + +export function createSkippedPythonDiffJson( + context: PythonDiffJsonContext = {}, +): PythonDiffJson { + return emptyPythonDiffJson('skipped', 'not-evaluated', context) +} + +export function createUnsupportedPythonDiffJson( + context: PythonDiffJsonContext = {}, +): PythonDiffJson { + return { + ...emptyPythonDiffJson('unsupported', 'unknown', context), + error: { + message: + 'Python-compatible diff JSON requires a pull request comparison.', + cause: 'Run this command in a pull request context with a base scan.', + }, + } +} + +export function createPythonDiffJsonFailure( + message: string, + cause: string | null | undefined, + context: PythonDiffJsonContext = {}, +): PythonDiffJson { + return { + ...emptyPythonDiffJson('incomplete', 'unknown', context), + error: { message, cause: cause ?? null }, + } +} + +function fromFailure( + result: Extract, { ok: false }>, + context: PythonDiffJsonContext, +): PythonDiffJson { + return createPythonDiffJsonFailure(result.message, result.cause, context) +} + +export function mapDiffScanToPythonJson( + result: CResult, + context: PythonDiffJsonContext = {}, +): PythonDiffJson { + if (!result.ok) { + return fromFailure(result, context) + } + + const diff = result.data?.diff_scan as DiffScan | undefined + const artifacts = diff?.artifacts as Partial | undefined + const groups = ['added', 'updated', 'removed', 'replaced'] as const + const afterScan = diff?.after_full_scan + const actualContext = { + ...context, + repo: + typeof afterScan?.repository_slug === 'string' && + afterScan.repository_slug + ? afterScan.repository_slug + : context.repo, + branch: + typeof afterScan?.branch === 'string' && afterScan.branch + ? afterScan.branch + : context.branch, + commitSha: + typeof afterScan?.commit_hash === 'string' && afterScan.commit_hash + ? afterScan.commit_hash + : context.commitSha, + } + const incompleteFields = [ + ...(typeof diff?.id === 'string' && diff.id ? [] : ['diff_scan.id']), + ...(typeof diff?.before_full_scan?.id === 'string' && + diff.before_full_scan.id + ? [] + : ['diff_scan.before_full_scan.id']), + ...(typeof diff?.after_full_scan?.id === 'string' && diff.after_full_scan.id + ? [] + : ['diff_scan.after_full_scan.id']), + ...[...groups, 'unchanged' as const].flatMap(group => + isArtifactArray(artifacts?.[group]) + ? [] + : [`diff_scan.artifacts.${group}`], + ), + ...(diff?.incomplete === true ? ['diff_scan.incomplete'] : []), + ] + if (!diff || !artifacts) { + incompleteFields.push('diff_scan') + } + if (incompleteFields.length) { + return { + ...emptyPythonDiffJson('incomplete', 'unknown', actualContext), + incomplete_fields: incompleteFields, + full_scan_id: + typeof diff?.after_full_scan?.id === 'string' + ? diff.after_full_scan.id + : null, + base_scan_id: + typeof diff?.before_full_scan?.id === 'string' + ? diff.before_full_scan.id + : null, + head_scan_id: + typeof diff?.after_full_scan?.id === 'string' + ? diff.after_full_scan.id + : null, + diff_scan_id: typeof diff?.id === 'string' ? diff.id : null, + diff_url: diff?.html_url ?? null, + report_url: diff?.after_full_scan?.html_url ?? null, + } + } + + const completeDiff = diff! + const completeArtifacts = artifacts! + const groupArtifacts = { + added: sortedArtifacts(completeArtifacts.added!), + updated: sortedArtifacts(completeArtifacts.updated!), + removed: sortedArtifacts(completeArtifacts.removed!), + replaced: sortedArtifacts(completeArtifacts.replaced!), + unchanged: isArtifactArray(completeArtifacts.unchanged) + ? completeArtifacts.unchanged + : [], + } + const alertList = (group: DiffArtifactGroup) => + groupArtifacts[group].flatMap(artifact => + (artifact.alerts ?? []).map(alert => + alertFromArtifact(artifact, alert, group), + ), + ) + const changedAlerts = sortedAlerts( + [ + ...alertList('added'), + ...alertList('updated'), + ...alertList('replaced'), + ].filter(alert => alert.action === 'error' || alert.action === 'warn'), + ) + const unchangedAlerts = sortedAlerts( + alertList('unchanged').filter( + alert => alert.action === 'error' || alert.action === 'warn', + ), + ) + const newAlerts = selectOutputAlerts( + changedAlerts, + unchangedAlerts, + context.strictBlocking === true, + ) + const removedAlerts = sortedAlerts(alertList('removed')) + const changedArtifacts = [ + ...groupArtifacts.added, + ...groupArtifacts.updated, + ...groupArtifacts.replaced, + ] + const scanFailed = newAlerts.some(alert => alert.error) + const blocked = + changedArtifacts.some(artifact => + artifact.alerts?.some(alert => alert.action === 'error'), + ) || + (context.strictBlocking === true && + groupArtifacts.unchanged.some(artifact => + artifact.alerts?.some(alert => alert.action === 'error'), + )) + + return { + schema_version: 'python-v1', + comparison_status: 'complete', + decision: blocked ? 'fail' : 'pass', + scan_failed: scanFailed, + new_alerts: newAlerts, + unchanged_alerts: unchangedAlerts, + removed_alerts: removedAlerts, + new_packages: groupArtifacts.added + .filter(artifact => getDirect(artifact, 'added')) + .map(artifact => packageFromArtifact(artifact, 'added')), + updated_packages: groupArtifacts.updated + .filter(artifact => getDirect(artifact, 'updated')) + .map(artifact => packageFromArtifact(artifact, 'updated')), + removed_packages: groupArtifacts.removed + .filter(artifact => getDirect(artifact, 'removed')) + .map(artifact => packageFromArtifact(artifact, 'removed')), + replaced_packages: groupArtifacts.replaced + .filter(artifact => getDirect(artifact, 'replaced')) + .map(artifact => packageFromArtifact(artifact, 'replaced')), + full_scan_id: completeDiff.after_full_scan.id, + base_scan_id: completeDiff.before_full_scan.id, + head_scan_id: completeDiff.after_full_scan.id, + diff_scan_id: completeDiff.id, + diff_url: completeDiff.html_url, + report_url: completeDiff.after_full_scan.html_url ?? null, + repo: actualContext.repo ?? null, + branch: actualContext.branch ?? null, + commit_sha: actualContext.commitSha ?? null, + legal_mode: context.legalMode ?? false, + } +} diff --git a/src/commands/scan/python-diff-json.test.mts b/src/commands/scan/python-diff-json.test.mts new file mode 100644 index 000000000..5f256c516 --- /dev/null +++ b/src/commands/scan/python-diff-json.test.mts @@ -0,0 +1,312 @@ +import { describe, expect, it } from 'vitest' + +import { + createSkippedPythonDiffJson, + mapDiffScanToPythonJson, +} from './python-diff-json.mts' + +import type { DiffScanData } from './fetch-diff-scan.mts' + +const manifest = [{ file: 'package.json', start: 1, end: 4 }] + +function artifact( + overrides: Record = {}, +): Record { + return { + id: 'artifact-1', + type: 'npm', + namespace: '@example', + name: 'widget', + version: '1.2.3', + diffType: 'added', + author: ['Example Author'], + size: 12, + head: [{ direct: true, manifestFiles: manifest }], + base: [], + capabilities: { envVars: true, networkAccess: false }, + alerts: [], + ...overrides, + } +} + +function diffData( + artifacts: Record = { + added: [], + updated: [], + removed: [], + replaced: [], + unchanged: [], + }, +): DiffScanData { + return { + diff_scan: { + id: 'diff-id', + before_full_scan: { id: 'base-id' }, + after_full_scan: { + id: 'head-id', + html_url: 'https://socket.dev/dashboard/org/acme/sbom/head-id', + repository_slug: 'acme', + branch: 'api-branch', + commit_hash: 'api-commit', + }, + html_url: 'https://socket.dev/dashboard/org/acme/diff/base-id/head-id', + artifacts, + }, + } as unknown as DiffScanData +} + +describe('mapDiffScanToPythonJson', () => { + it('maps package changes, findings, IDs and URLs to the Python v1 contract', () => { + const data = diffData({ + added: [ + artifact({ + alerts: [ + { + action: 'error', + category: 'vulnerability', + end: 4, + file: 'package.json', + key: 'alert-added', + props: { cveId: 'CVE-2026-1234', ghsaId: 'GHSA-1234' }, + severity: 'high', + start: 1, + type: 'criticalCVE', + }, + { + action: 'ignore', + key: 'capability-alert', + type: 'envVars', + }, + ], + }), + artifact({ + id: 'transitive', + name: 'transitive-only', + head: [{ direct: false }], + }), + ], + updated: [ + artifact({ + id: 'artifact-updated', + name: 'updated-widget', + diffType: 'updated', + alerts: [ + { + action: 'warn', + key: 'alert-updated', + props: {}, + type: 'socketDeprecatedPackage', + }, + ], + }), + ], + removed: [ + artifact({ + id: 'artifact-removed', + name: 'removed-widget', + diffType: 'removed', + head: [], + base: [{ direct: true, manifestFiles: manifest }], + alerts: [ + { + action: 'ignore', + key: 'alert-removed', + type: 'removedFinding', + }, + ], + }), + ], + replaced: [ + artifact({ + id: 'artifact-replaced', + name: 'replaced-widget', + diffType: 'replaced', + alerts: [], + }), + ], + unchanged: [ + artifact({ + id: 'artifact-stable', + name: 'stable-widget', + alerts: [ + { + action: 'error', + key: 'alert-unchanged', + props: { cveId: 'CVE-2026-9999' }, + type: 'criticalCVE', + }, + ], + }), + ], + }) + + const report = mapDiffScanToPythonJson( + { ok: true, data }, + { + branch: 'feature', + commitSha: 'head-commit', + legalMode: false, + repo: 'owner/repo', + strictBlocking: true, + }, + ) + const parsed = JSON.parse(JSON.stringify(report)) as typeof report + expect(parsed.schema_version).toBe('python-v1') + expect(parsed.comparison_status).toBe('complete') + expect(parsed.decision).toBe('fail') + expect(parsed.scan_failed).toBe(true) + expect(parsed).toMatchObject({ + full_scan_id: 'head-id', + base_scan_id: 'base-id', + head_scan_id: 'head-id', + diff_scan_id: 'diff-id', + diff_url: 'https://socket.dev/dashboard/org/acme/diff/base-id/head-id', + report_url: 'https://socket.dev/dashboard/org/acme/sbom/head-id', + repo: 'acme', + branch: 'api-branch', + commit_sha: 'api-commit', + legal_mode: false, + }) + expect(parsed.new_alerts.map(alert => alert.key).sort()).toEqual([ + 'alert-added', + 'alert-unchanged', + 'alert-updated', + ]) + expect( + parsed.new_alerts.find(alert => alert.key === 'alert-added'), + ).toMatchObject({ + pkg_type: 'npm', + pkg_name: 'widget', + pkg_version: '1.2.3', + pkg_id: 'artifact-1', + type: 'criticalCVE', + severity: 'high', + action: 'error', + error: true, + warn: false, + purl: 'npm/%40example/widget@1.2.3', + direct: true, + manifest_files: manifest, + }) + expect(parsed.removed_alerts[0]).toMatchObject({ + key: 'alert-removed', + ignore: true, + }) + expect(parsed.new_packages).toHaveLength(1) + expect(parsed.new_packages[0]).toMatchObject({ + id: 'artifact-1', + name: 'widget', + direct: true, + introduced_by: [['direct', 'package.json']], + capabilities: ['Environment Variables'], + is_new: false, + }) + expect(parsed.updated_packages[0]?.id).toBe('artifact-updated') + expect(parsed.removed_packages[0]?.id).toBe('artifact-removed') + expect(parsed.replaced_packages[0]?.id).toBe('artifact-replaced') + expect(report.new_packages).toHaveLength(1) + }) + + it('returns empty lists for a completed clean comparison', () => { + const report = mapDiffScanToPythonJson({ + ok: true, + data: diffData(), + }) + expect(report).toMatchObject({ + comparison_status: 'complete', + decision: 'pass', + scan_failed: false, + new_alerts: [], + unchanged_alerts: [], + removed_alerts: [], + new_packages: [], + updated_packages: [], + removed_packages: [], + replaced_packages: [], + }) + }) + + it('keeps strict-only findings in new_alerts and scan_failed', () => { + const report = mapDiffScanToPythonJson( + { + ok: true, + data: diffData({ + added: [], + updated: [], + removed: [], + replaced: [], + unchanged: [ + artifact({ + alerts: [ + { + action: 'error', + key: 'unchanged-error', + props: { cveId: 'CVE-1' }, + type: 'criticalCVE', + }, + ], + }), + ], + }), + }, + { strictBlocking: true }, + ) + expect(report.decision).toBe('fail') + expect(report.scan_failed).toBe(true) + expect(report.new_alerts.map(alert => alert.key)).toEqual([ + 'unchanged-error', + ]) + }) + + it('marks omitted unchanged artifacts as incomplete instead of passing', () => { + const data = diffData({ + added: [], + updated: [], + removed: [], + replaced: [], + unchanged: null as never, + }) + expect( + mapDiffScanToPythonJson({ ok: true, data }, { strictBlocking: true }), + ).toMatchObject({ + comparison_status: 'incomplete', + decision: 'unknown', + incomplete_fields: ['diff_scan.artifacts.unchanged'], + new_alerts: [], + }) + }) + + it('honors the server incomplete marker even when all diff data is present', () => { + const data = diffData() + data.diff_scan.incomplete = true + expect(mapDiffScanToPythonJson({ ok: true, data })).toMatchObject({ + comparison_status: 'incomplete', + decision: 'unknown', + incomplete_fields: ['diff_scan.incomplete'], + full_scan_id: 'head-id', + diff_scan_id: 'diff-id', + }) + }) + + it('uses explicit no-comparison and failure states', () => { + expect(createSkippedPythonDiffJson()).toMatchObject({ + comparison_status: 'skipped', + decision: 'not-evaluated', + scan_failed: false, + diff_scan_id: null, + new_alerts: [], + new_packages: [], + }) + expect( + mapDiffScanToPythonJson({ + ok: false, + message: 'request failed', + cause: 'timeout', + }), + ).toMatchObject({ + comparison_status: 'incomplete', + decision: 'unknown', + error: { message: 'request failed', cause: 'timeout' }, + }) + }) +}) diff --git a/test/snapshots/termless/cli.native.socket-help-ci.svg b/test/snapshots/termless/cli.native.socket-help-ci.svg index d3eec6e12..ab4439c38 100644 --- a/test/snapshots/termless/cli.native.socket-help-ci.svg +++ b/test/snapshots/termless/cli.native.socket-help-ci.svg @@ -1,4 +1,4 @@ - + CLI: v2.1.1-rc.0 | cmd: socket ci | org: (not set) | token: (not set) @@ -23,43 +23,43 @@ --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 + This command is intended to use in CI runs to allow automated systems to - Socket API token. Exit codes are 0 for success, 1 for blocking findings, 2 + accept or reject a current build. It will use the default org of the - for usage errors, 3 for infrastructure errors, and 130 for interruption. + Socket API token. Exit codes are 0 for success, 1 for blocking findings, 2 - --disable-blocking returns 0 for findings and runtime failures, but not + for usage errors, 3 for infrastructure errors, and 130 for interruption. - usage errors. --exit-code-on-api-error changes the API failure code. + --disable-blocking returns 0 for findings and runtime failures, but not - + usage errors. --exit-code-on-api-error changes the API failure code. - The --auto-manifest flag does the same as the one from `socket scan create` + - but is not enabled by default since the CI is less likely to be set up with + The --auto-manifest flag does the same as the one from `socket scan create` - all the necessary dev tooling. Enable it if you want the scan to include + but is not enabled by default since the CI is less likely to be set up with - locally generated manifests like for gradle and sbt. + all the necessary dev tooling. Enable it if you want the scan to include - + locally generated manifests like for gradle and sbt. - Examples + - $ socket ci + Examples - $ socket ci --auto-manifest + $ socket ci - $ socket ci --disable-blocking + $ socket ci --auto-manifest - $ socket ci --exit-code-on-api-error 5 + $ socket ci --disable-blocking - + $ socket ci --exit-code-on-api-error 5 @@ -68,4 +68,6 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/test/snapshots/termless/cli.native.socket-help-scan-diff.svg b/test/snapshots/termless/cli.native.socket-help-scan-diff.svg index 688a39477..a461eea48 100644 --- a/test/snapshots/termless/cli.native.socket-help-scan-diff.svg +++ b/test/snapshots/termless/cli.native.socket-help-scan-diff.svg @@ -1,4 +1,4 @@ - + CLI: v2.1.1-rc.0 | cmd: socket scan diff | org: (not set) | token: (not set) @@ -49,23 +49,23 @@ --json Output as JSON - --markdown Output as Markdown + --json-format Select a versioned JSON payload; python-v1 implies --json and cannot be combined with --markdown. - --org Force override the organization slug, overrides the default org from config + --markdown Output as Markdown - --strict-blocking Fail when unchanged blocking alerts are present in the scan diff + --org Force override the organization slug, overrides the default org from config - + --strict-blocking Fail when unchanged blocking alerts are present in the scan diff - Examples + - $ socket scan diff aaa0aa0a-aaaa-0000-0a0a-0000000a00a0 aaa1aa1a-aaaa-1111-1a1a-1111111a11a1 + Examples - $ socket scan diff aaa0aa0a-aaaa-0000-0a0a-0000000a00a0 aaa1aa1a-aaaa-1111-1a1a-1111111a11a1 --json + $ socket scan diff aaa0aa0a-aaaa-0000-0a0a-0000000a00a0 aaa1aa1a-aaaa-1111-1a1a-1111111a11a1 - $ socket scan diff aaa0aa0a-aaaa-0000-0a0a-0000000a00a0 aaa1aa1a-aaaa-1111-1a1a-1111111a11a1 --strict-blocking + $ socket scan diff aaa0aa0a-aaaa-0000-0a0a-0000000a00a0 aaa1aa1a-aaaa-1111-1a1a-1111111a11a1 --json - + $ socket scan diff aaa0aa0a-aaaa-0000-0a0a-0000000a00a0 aaa1aa1a-aaaa-1111-1a1a-1111111a11a1 --strict-blocking @@ -74,4 +74,6 @@ - \ No newline at end of file + + + \ No newline at end of file