OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(imports): preserve Guardian attribution and Snyk evidence on replay (#2316)
Michael D'Angelof03d1a705d36
diff --git a/docs/scanner-imports/semgrep.md b/docs/scanner-imports/semgrep.mdindex 1b545f9b9..5007c96d5 100644--- a/docs/scanner-imports/semgrep.md+++ b/docs/scanner-imports/semgrep.md@@ -98,6 +98,10 @@ codex-security publish findings /path/to/private/guardian.json --provider semgre--to local --repository /path/to/project --source-key example/project/topic --dry-run --format json```+For normalized SDK imports, select the `semgrep` provider and keep each generated+Guardian ID with its original finding and collection scope. The repository URL+in each finding must agree with the report's mapping.+Guardian records retain the original MCP fields. The summary omits end lines,CWEs, package versions and fix versions. Guardian and Web API records keepseparate identities even when their IDs look identical. To verify a pair,diff --git a/docs/scanner-imports/snyk.md b/docs/scanner-imports/snyk.mdindex 5d0ca574b..a4c3d4357 100644--- a/docs/scanner-imports/snyk.md+++ b/docs/scanner-imports/snyk.md@@ -40,7 +40,9 @@ dependencies when a private repository uses an SSH target. The offline readerThe collector writes v2 and preserves the original project and issue evidence.For open Snyk Code issues from an SCM integration, both versions importrepository-relative paths from open coordinates. V2 also imports each-coordinate's reported start line when available. For resolved issues, closed+coordinate's reported start line when available. V2 keeps URI and SSH addresses+in the original evidence and uses only repository file paths for code locations+and package manifests. For resolved issues, closedcoordinates, and projects monitored through the CLI or API, read the originallocation from `evidence.source_data.issue` in v1 or from the JSON text in`evidence.source_data.issueJson` in v2.diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 97adc7705..e8f6974ff 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -237,6 +237,7 @@ import {} from "./github-advisories.js";import {collectSnykIssues,+ snykRestApiVersion,SNYK_REST_ISSUES_FORMAT,} from "./snyk-rest-findings.js";import type { HostedScannerHttpOptions } from "./hosted-scanner-http.js";@@ -4244,7 +4245,7 @@ export async function main(output: z.object({format: z.literal(SNYK_REST_ISSUES_FORMAT),- apiVersion: z.string(),+ apiVersion: z.literal(snykRestApiVersion),apiOrigin: z.string(),organizationId: z.string(),projectId: z.string(),diff --git a/sdk/typescript/src/external-findings-local.ts b/sdk/typescript/src/external-findings-local.tsindex 46400d68a..89f417f6a 100644--- a/sdk/typescript/src/external-findings-local.ts+++ b/sdk/typescript/src/external-findings-local.ts@@ -39,7 +39,10 @@ import {localFindingRepositories,semgrepSarifRepositories,} from "./external-findings-read.js";-import { guardianSelectionFormat } from "./semgrep-guardian-findings.js";+import {+ guardianFindingSourceData,+ guardianSelectionFormat,+} from "./semgrep-guardian-findings.js";import {hasGitMetadata,localGitProtectionRoots,@@ -961,13 +964,10 @@ export async function prepareLocalImport(if (semgrep.migration) Object.assign(finding.evidence, semgrep.migration);}const { evidence } = finding;- const guardian =- evidence.source_data?.["format"] === guardianSelectionFormat;+ const guardian = guardianFindingSourceData(finding);const url = evidence.details?.repository?.url;if (guardian) {- const source = addGuardianSource(- evidence.source_data!["sourceRepositoryUrl"],- );+ const source = addGuardianSource(guardian["sourceRepositoryUrl"]);if ((guardianReport &&!semgrepReferenceMatches(guardianReport, source.url)) ||diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.tsindex 7a3926f35..2a3435652 100644--- a/sdk/typescript/src/external-findings-publish.ts+++ b/sdk/typescript/src/external-findings-publish.ts@@ -27,7 +27,10 @@ import {type PrivateImportJob,} from "./private-finding-import.js";import { readCloudCredentials } from "./cloud-publish.js";-import { guardianSelectionFormat } from "./semgrep-guardian-findings.js";+import {+ guardianFindingId,+ guardianSelectionFormat,+} from "./semgrep-guardian-findings.js";import {cloudBaseUrl,cloudFindingsUrl,@@ -579,7 +582,7 @@ function storedFindingId(finding: ExternalFinding): string {function rejectGuardianSelection(input: ExternalFindings): void {const isGuardian = (row: ExternalFinding) =>row &&- (/^semgrep-guardian:[0-9a-f]{64}$/u.test(storedFindingId(row)) ||+ (guardianFindingId.test(storedFindingId(row)) ||ownData(ownData(row.evidence, "source_data"), "format") ===guardianSelectionFormat);if (diff --git a/sdk/typescript/src/semgrep-guardian-findings.ts b/sdk/typescript/src/semgrep-guardian-findings.tsindex d1e7a9753..2adef9e03 100644--- a/sdk/typescript/src/semgrep-guardian-findings.ts+++ b/sdk/typescript/src/semgrep-guardian-findings.ts@@ -1,5 +1,9 @@import { validateExternalEvidence } from "./external-import-contract.js";-import type { ExternalSourceRepository } from "./external-findings.js";+import { CodexSecurityError } from "./errors.js";+import type {+ ExternalFinding,+ ExternalSourceRepository,+} from "./external-findings.js";import { requireExternalImports } from "./external-imports-feature.js";import { isRecord } from "./record.js";import {@@ -20,6 +24,36 @@ import {export const guardianSelectionFormat = "semgrep-guardian-selection/v1";+export const guardianFindingId = /^semgrep-guardian:[0-9a-f]{64}$/u;++function guardianId(scope: Record<string, unknown>, id: unknown) {+ return stableId("semgrep-guardian", [+ scope["deployment"],+ scope["repository"],+ scope["tool"],+ scope["ref"],+ id,+ ]);+}++export function guardianFindingSourceData({+ source_finding_id,+ evidence,+}: ExternalFinding) {+ const data = evidence.source_data ?? {};+ const generated = guardianFindingId.test(source_finding_id);+ if (data["format"] !== guardianSelectionFormat && !generated) return;+ if (generated) {+ const row = record(data["finding"], "Original Guardian finding");+ requireGuardianRowScope(data, row);+ if (source_finding_id !== guardianId(data, row["id"]))+ throw new CodexSecurityError(+ "The normalized finding ID does not match the original Guardian finding.",+ );+ }+ return data;+}+type GuardianTool ="get_semgrep_sast_findings" | "get_semgrep_supply_chain_findings";@@ -64,6 +98,32 @@ function selectionScope(request: unknown, findingIds: unknown) {return { tool: name, deployment, repository, ref, ids };}+function requireGuardianRowScope(+ scope: Record<string, unknown>,+ row: Record<string, unknown>,+): void {+ const id = row["id"];+ const repository = record(row["repository"], "Guardian finding repository");+ if (+ repository["name"] !== scope["repository"] ||+ (row["ref"] != null && row["ref"] !== scope["ref"])+ )+ throw new Error(+ `Guardian finding ${id} does not match the selected repository and ref.`,+ );+ const expected =+ scope["tool"] === "get_semgrep_sast_findings" ? "sast" : "sca";+ if (+ row["issueType"] != null &&+ text(row["issueType"])+ ?.toLowerCase()+ .replace(/^issue_type_/u, "") !== expected+ )+ throw new Error(+ `Guardian finding ${id} does not match the selected product.`,+ );+}+function selectedRows(scope: ReturnType<typeof selectionScope>,structuredContent: unknown,@@ -80,25 +140,7 @@ function selectedRows(const id = row["id"];if (rows.has(id))throw new Error(`Guardian returned duplicate finding ID ${id}.`);- const repository = record(row["repository"], "Guardian finding repository");- if (- repository["name"] !== scope.repository ||- (row["ref"] != null && row["ref"] !== scope.ref)- )- throw new Error(- `Guardian finding ${id} does not match the selected repository and ref.`,- );- const expected =- scope.tool === "get_semgrep_sast_findings" ? "sast" : "sca";- if (- row["issueType"] != null &&- text(row["issueType"])- ?.toLowerCase()- .replace(/^issue_type_/u, "") !== expected- )- throw new Error(- `Guardian finding ${id} does not match the selected product.`,- );+ requireGuardianRowScope(scope, row);rows.set(id, row);}return Array.from(scope.ids, (id) => {@@ -223,14 +265,7 @@ export function normalizeGuardianSelection();},// Guardian's string ID has not been verified against Web API occurrence IDs.- (finding) =>- stableId("semgrep-guardian", [- deployment,- repository,- tool,- ref,- finding["id"],- ]),+ (finding) => guardianId(scope, finding["id"]),"local",{ report: { format: guardianSelectionFormat, repositoryUrl: url } },);diff --git a/sdk/typescript/src/snyk-rest-findings.ts b/sdk/typescript/src/snyk-rest-findings.tsindex 9261c90cf..1073b87f8 100644--- a/sdk/typescript/src/snyk-rest-findings.ts+++ b/sdk/typescript/src/snyk-rest-findings.ts@@ -48,6 +48,7 @@ import {normalizeRecords,record as scannerRecord,hostedRepositoryPath,+ repositoryFilePath,requiredText,scannerSeverity,stableId,@@ -65,8 +66,11 @@ const issueTimestamp = new RegExp(regexes.datetime({ offset: true }).source,"i",);-const apiVersion = "2026-03-25";-const formatVersion = { format: SNYK_REST_ISSUES_FORMAT, apiVersion } as const;+export const snykRestApiVersion = "2026-03-25";+const formatVersion = {+ format: SNYK_REST_ISSUES_FORMAT,+ apiVersion: snykRestApiVersion,+} as const;const defaultOrigin = "https://api.snyk.io";const origins = new Set([defaultOrigin,@@ -145,7 +149,7 @@ type Resource = Record<string, unknown>;export interface SnykIssuesExport extends SnykScope {format: typeof SNYK_REST_ISSUES_FORMAT;- apiVersion: typeof apiVersion;+ apiVersion: typeof snykRestApiVersion;apiOrigin: string;complete: true;projectJson: string;@@ -194,7 +198,7 @@ function endpoint(selected: Scope, route: string) {`/rest/orgs/${selected.organizationId}/${route}`,selected.apiOrigin,);- url.searchParams.set("version", apiVersion);+ url.searchParams.set("version", snykRestApiVersion);return url;}@@ -790,10 +794,10 @@ function savedContext() {if (document["format"] !== SNYK_REST_ISSUES_FORMAT ||- document["apiVersion"] !== apiVersion+ document["apiVersion"] !== snykRestApiVersion)throw new Error(- `Expected ${SNYK_REST_ISSUES_FORMAT} for API version ${apiVersion}.`,+ `Expected ${SNYK_REST_ISSUES_FORMAT} for API version ${snykRestApiVersion}.`,);const selected = scope(document, document["apiOrigin"]);const project = record(@@ -880,7 +884,7 @@ function linkedSnykResources()return { issue };}- if (!hosted && data["apiVersion"] !== apiVersion) return;+ if (!hosted && data["apiVersion"] !== snykRestApiVersion) return;const project = originalSnykResource(data, "project", json);const attributes = project?.["attributes"];const nativeProject =@@ -1176,8 +1180,8 @@ function problemIds(entries: Resource[], type?: string) {function findingFilePath(value: unknown, v2: boolean) {const path = hostedRepositoryPath(value);- const filename = path?.split("/").at(-1);- return v2 && (!filename || filename === ".") ? null : path;+ if (v2 && (path?.endsWith("/.") || !repositoryFilePath(path))) return null;+ return path;}function packageEvidence(diff --git a/sdk/typescript/src/snyk-rest-v1.ts b/sdk/typescript/src/snyk-rest-v1.tsindex 6f18c4abc..6e7431548 100644--- a/sdk/typescript/src/snyk-rest-v1.ts+++ b/sdk/typescript/src/snyk-rest-v1.ts@@ -37,7 +37,11 @@ function encodeNumbers(data: object): Resource | undefined {values[key] = Number(token);}} else if (value !== null && typeof value === "object") {- const nested = encodeNumbers(value);+ // restoreLegacyHostedNumbers shares branches that had no sidecar.+ // Keep the captured input reusable for another repository projection.+ const child = Array.isArray(value) ? [...value] : { ...value };+ values[key] = child;+ const nested = encodeNumbers(child);if (nested) fields[key] = nested;}}@@ -46,7 +50,7 @@ function encodeNumbers(data: object): Resource | undefined {/** Recover the exact v1 wire representation whether numbers were native or witnessed strings. */export function encodeSnykV1File(document: Resource): Resource {- const source = restoreLegacyHostedNumbers(document);+ const source = { ...restoreLegacyHostedNumbers(document) };delete source["numericFields"];const fields = encodeNumbers(source);if (fields) source["numericFields"] = fields;diff --git a/sdk/typescript/tests-ts/cli-import-snyk.test.ts b/sdk/typescript/tests-ts/cli-import-snyk.test.tsindex 34a1e50e0..289c56e4e 100644--- a/sdk/typescript/tests-ts/cli-import-snyk.test.ts+++ b/sdk/typescript/tests-ts/cli-import-snyk.test.ts@@ -149,6 +149,7 @@ test("Snyk --schema describes the complete saved report", async () => {const { output } = JSON.parse(cli.stdout.text());expect(output.properties).toMatchObject({format: { const: "snyk-rest-issues/v2" },+ apiVersion: { const: "2026-03-25" },complete: { const: true },projectJson: { type: "string" },targetJson: { type: "string" },diff --git a/sdk/typescript/tests-ts/semgrep-guardian-findings.test.ts b/sdk/typescript/tests-ts/semgrep-guardian-findings.test.tsindex fb585fc1e..69700f3e4 100644--- a/sdk/typescript/tests-ts/semgrep-guardian-findings.test.ts+++ b/sdk/typescript/tests-ts/semgrep-guardian-findings.test.ts@@ -180,6 +180,41 @@ test("Guardian Supply Chain retains its summary and checks the operator's checkolocations: [],source_data: { finding: sca.structuredContent.findings[0] },});+ await using wrongProvider = await isolatedGitReportFixture(+ "guardian.json",+ { provider: "wiz", sourceKey: "test" },+ { remote: "https://github.com/other/service" },+ );+ for (const input of [normalized, { ...normalized, report: undefined }]) {+ await expect(wrongProvider.prepareNormalized(input)).rejects.toThrow(+ /semgrep provider/,+ );+ }+ const original = normalized.findings[0]!;+ await using source = await isolatedGitReportFixture(+ "guardian.json",+ { provider: "semgrep", sourceKey: "test" },+ { remote: sourceRepositoryUrl },+ );+ const otherUrl = "https://github.com/other/service";+ source.git("remote", "add", "upstream", otherUrl);+ await expect(+ source.prepareNormalized({+ ...normalized,+ report: { ...normalized.report, repositoryUrl: otherUrl },+ }),+ ).rejects.toThrow(/recorded selection/);+ await expect(+ source.prepareNormalized({+ ...normalized,+ findings: [+ {+ ...original,+ source_finding_id: "semgrep-guardian:" + "0".repeat(64),+ },+ ],+ }),+ ).rejects.toThrow(/original Guardian finding/);expect(normalized.findings[0]!.evidence.packages ?? []).toEqual([]);expect(normalized.findings[0]!.source_finding_id).not.toBe(normalizeSemgrepFindings(capture, {}, "local").findings[0]!@@ -199,6 +234,65 @@ test("Guardian Supply Chain retains its summary and checks the operator's checkoexpect(await fixture.read()).toHaveLength(0);});+test("normalized Guardian imports verify the original finding against the selected scope", async () => {+ await using fixture = await isolatedGitReportFixture(+ "guardian.json",+ { provider: "semgrep", sourceKey: "test" },+ { remote: sourceRepositoryUrl },+ );+ const normalized = normalizeSemgrepFindings(capture, {}, "local");+ const original = normalized.findings[0]!;+ for (const changed of [+ { ...row, repository: { name: "other/service" } },+ { ...row, ref: "refs/heads/other" },+ { ...row, issueType: "ISSUE_TYPE_SCA" },+ ]) {+ await expect(+ fixture.prepareNormalized({+ ...normalized,+ findings: [+ {+ ...original,+ evidence: {+ ...original.evidence,+ source_data: {+ ...original.evidence.source_data,+ finding: changed,+ },+ },+ },+ ],+ }),+ ).rejects.toThrow(/does not match the selected/);+ }+});++test("normalized Guardian repository claims use the checkout's HTTP port identity", async () => {+ await using fixture = await isolatedGitReportFixture(+ "guardian.json",+ { provider: "semgrep", sourceKey: "test" },+ { remote: sourceRepositoryUrl },+ );+ const normalized = normalizeSemgrepFindings(capture, {}, "local");+ const withReportPort = (port: number) => ({+ ...normalized,+ report: {+ ...normalized.report,+ repositoryUrl: sourceRepositoryUrl.replace(+ "github.com/",+ `github.com:${port}/`,+ ),+ },+ });+ expect(+ (await (await fixture.prepareNormalized(withReportPort(443))).import())+ .counts.created,+ ).toBe(1);+ await expect(fixture.prepareNormalized(withReportPort(8443))).rejects.toThrow(+ /recorded selection/,+ );+});+test("SDK exports containing Guardian findings fail before Cloud credential lookup", async () => {const guardian = normalizeSemgrepFindings(capture, {}, "local");const normalized = {diff --git a/sdk/typescript/tests-ts/snyk-rest-findings.test.ts b/sdk/typescript/tests-ts/snyk-rest-findings.test.tsindex 4ee91ecd3..872717a63 100644--- a/sdk/typescript/tests-ts/snyk-rest-findings.test.ts+++ b/sdk/typescript/tests-ts/snyk-rest-findings.test.ts@@ -69,7 +69,14 @@ test.each(["open-source", "code"] as const)(if (code) {const { representations } = record.attributes.coordinates[0]!;const location = representations[0]!.sourceLocation!;- for (const file of [".", "src/", "src/.", "src\\app.ts"])+ for (const file of [+ ".",+ "src/",+ "src/.",+ "src\\app.ts",+ "file:/tmp/app.ts",+ "[email protected]:app.ts",+ ])representations.push({ sourceLocation: { ...location, file } });}const path = `/rest/orgs/${options.organizationId}/issues`;diff --git a/sdk/typescript/tests-ts/snyk-rest-v1.test.ts b/sdk/typescript/tests-ts/snyk-rest-v1.test.tsindex 74f6fa04b..50a6028dc 100644--- a/sdk/typescript/tests-ts/snyk-rest-v1.test.ts+++ b/sdk/typescript/tests-ts/snyk-rest-v1.test.ts@@ -1,6 +1,8 @@import { expect, test } from "bun:test";import { writeFile } from "node:fs/promises";import { gzipSync } from "node:zlib";+import { normalizeSnykFile } from "../src/snyk-findings.js";+import { parseSnykReport } from "../src/snyk-rest-v1.js";import {normalizeSnykIssues,snykRestFindingRepository,@@ -142,3 +144,32 @@ test("replays a v1 Snyk export with its original evidence, then updates the sameunchanged: 1,});});++test("a second projection preserves both native numbers and v1 type witnesses", async () => {+ const token = "9007199254740995";+ const document = parseSnykReport(+ JSON.stringify({+ ...snykOptions,+ format: "snyk-rest-issues/v1",+ apiVersion: "2026-03-25",+ complete: true,+ project: { ...snykProject().data, counter: token },+ target: null,+ pages: [+ {+ startingAfter: null,+ response: {+ data: [{ ...snykIssue(false), counter: "native-number" }],+ },+ },+ ],+ numericFields: { project: { counter: token } },+ }).replace('"native-number"', token),+ );+ const first = await normalizeSnykFile(document, "cloud", []);+ expect(first.findings[0]?.evidence.source_data?.["numericFields"]).toEqual({+ project: { counter: token },+ issue: { counter: token },+ });+ expect(await normalizeSnykFile(document, "cloud", [])).toEqual(first);+});