Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

feat(import): collect and import Checkmarx SAST findings (#2269)

Michael D'Angelo6de45f81ac0c
diff --git a/docs/scanner-imports/README.md b/docs/scanner-imports/README.md
index e3172a3b8..604b0d01a 100644
--- a/docs/scanner-imports/README.md
+++ b/docs/scanner-imports/README.md
@@ -41,6 +41,7 @@ Cloud private inbox imports came after [version 0.8.2](https://github.com/openai
| [Amazon Inspector](inspector.md) | Inspector2 `ListFindings` JSON for one Code Security repository |
| [AWS Continuum](continuum.md) | Code finding summaries or a detailed finding verified for one repository |
| [Black Duck SCA](blackduck.md) | BOM component vulnerabilities for one project version |
+| [Checkmarx SAST](checkmarx.md) | Checkmarx One CLI JSON or self-managed CxSAST XML for one scan |
| [Endor Labs](endor.md) | Finding JSON from `endorctl`, or SARIF with finding UUIDs |
| [GitHub code scanning](github-code-scanning.md) | Alerts selected for one repository and Git ref |
| [GitHub Dependabot](github-dependabot.md) | Dependency alerts exported from one repository |
diff --git a/docs/scanner-imports/checkmarx.md b/docs/scanner-imports/checkmarx.md
new file mode 100644
index 000000000..2cc3bcc7b
--- /dev/null
+++ b/docs/scanner-imports/checkmarx.md
@@ -0,0 +1,72 @@
+# Import Checkmarx SAST findings
+
+Use `--provider checkmarx` for a completed Checkmarx One scan (CLI JSON) or
+self-managed CxSAST scan (XML). Both formats support gzip. [Enable external imports](README.md#preview-a-report).
+
+## Preview, import and verify
+
+From the matching checkout, preview a saved report with its verified Git URL.
+Choose a source key for the product, tenant or instance, project and ref.
+Reuse it for later exports from that stream.
+
+```sh
+report=/private/path/checkmarx-results.json
+codex-security publish findings "$report" --to local --repository . \
+ --provider checkmarx --source-repository-url https://github.com/example/project \
+ --source-key checkmarx-one/example-tenant/example-project/main/sast \
+ --dry-run --format json
+```
+
+For CxSAST, use the XML path and a key such as `cxsast/example-instance/example-project/main/sast`.
+Check `report.scanId`, the SAST findings and any exclusions. A confirmed local import
+with exclusions saves the accepted findings and exits with status 1. Use the same
+file for confirmation and retries. [Save or publish and verify](README.md#save-or-publish-and-verify).
+
+## Collect an existing scan with Codex
+
+Ask **publish-findings** for the full scan from a trusted session. Supply a native
+Python 3.10+ interpreter and vendor tools installed outside the scanned source tree.
+
+> Preview the full Checkmarx One scan `SCAN_ID` for `example-project` on `main`.
+> Its repository is `https://github.com/example/project`.
+
+- **Checkmarx One** uses `cx` 2.3.23+ with your signed-in profile or a complete
+ environment login. Use `CX_CONFIG_FILE_PATH` for a specific trusted profile.
+ On mixed scans, `cx` retrieves all engines and may also generate an SCA package report.
+- **CxSAST** uses Java, CxFlow 1.6.37+ and your trusted SAST-only profile with
+ the `CxXml` writer. Verify the completed scan ID, project and owning team's full path
+ in the selected server’s **Projects & Scans → All Scans** view before collection.
+ CxFlow fetches by ID and exports the full XML even when issue-tracker filters are set.
+ Session credentials require confirmation for that server. [CxSAST All Scans](https://docs.checkmarx.com/en/34965-46419-viewing-results-from-all-scans.html)
+
+For a subset, an older CLI, or a custom runtime, supply a native export from
+your usual environment. Keep reports in a private directory outside the checkout.
+[Supported sign-in and collection settings](../../plugins/codex-security/skills/publish-findings/references/checkmarx-import.md).
+
+## Export one scan manually
+
+For **Checkmarx One**, use the signed-in CLI from outside the checkout. Set
+`cx_path` to the installed executable, `scan_id` to the selected scan, and
+`report_root` to a private directory. Use the printed file after a successful export.
+[Checkmarx One results](https://docs.checkmarx.com/en/34965-68640-results.html)
+
+```sh
+report_dir=$(mktemp -d "$report_root/checkmarx.XXXXXXXX") &&
+ "$cx_path" results show --scan-id "$scan_id" --report-format json \
+ --output-path "$report_dir" --output-name checkmarx-results &&
+ printf '%s\n' "$report_dir/checkmarx-results.json"
+```
+
+For **CxSAST**, open the selected scan and choose **Create Report → XML**.
+Review the result filters before generating the file. [Generate a CxSAST report](https://docs.checkmarx.com/en/34965-46423-generating-scan-result-reports.html).
+
+## Identity and evidence
+
+One combines `similarityId` and `data.resultHash` to identify each occurrence.
+CxSAST uses the project, query, path similarity ID and ordered path nodes,
+or the reported result location for a path without nodes. Moving a node can
+create a new occurrence. [Checkmarx similarity IDs](https://docs.checkmarx.com/en/34965-205026-similarity-id.html)
+
+Findings start as `not_assessed` and retain the native severity, triage state,
+paths and snippets in `evidence.source_data`. A scan may cover a directory or
+archive. Verify how its paths map to the checkout before investigating a finding.
diff --git a/docs/scanner-imports/schema-guide.md b/docs/scanner-imports/schema-guide.md
index 158fb6608..5932b6fdc 100644
--- a/docs/scanner-imports/schema-guide.md
+++ b/docs/scanner-imports/schema-guide.md
@@ -27,6 +27,7 @@ changes.
| ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Amazon Inspector](inspector.md), [Endor Labs](endor.md), [SonarQube Cloud](sonar.md) | Inspector finding ARN, Endor Finding UUID or Sonar issue key. Endor native JSON and SARIF use the same UUID. |
| [AWS Continuum](continuum.md) | Continuum finding ARN. A list summary and a detailed response for that ARN update the same record. |
+| [Checkmarx SAST](checkmarx.md) | Checkmarx One uses the similarity ID and result hash. CxSAST scopes the similarity ID and ordered flow to the project and query. |
| [Wiz](wiz.md) | Package occurrence ID, or a SAST, repository-secret or IaC occurrence ID prefixed with its family. Normalized JSONL uses the supplied ID. |
| [GitHub Dependabot](github-dependabot.md), [code scanning](github-code-scanning.md) | Host, repository, alert family and alert number. Code scanning also includes the selected ref. Two alerts citing one GHSA remain separate. |
| [GitHub advisories](github-security-advisories.md) | Host, repository or global scope, and GHSA ID. This identifies a disclosure. Check installed packages separately. |
diff --git a/evals/triage-finding/scripts/run-promptfoo.mts b/evals/triage-finding/scripts/run-promptfoo.mts
index 90339197c..e0f7acc1d 100644
--- a/evals/triage-finding/scripts/run-promptfoo.mts
+++ b/evals/triage-finding/scripts/run-promptfoo.mts
@@ -26,12 +26,9 @@ const PROMPTFOO_ENTRYPOINT = path.join(
function copyDirectory(
sourceRoot: string,
targetRoot: string,
- excludedNames = new Set<string>(),
+ filter?: (source: string) => boolean,
) {
- fs.cpSync(sourceRoot, targetRoot, {
- recursive: true,
- filter: (source) => !excludedNames.has(path.basename(source)),
- });
+ fs.cpSync(sourceRoot, targetRoot, { recursive: true, filter });
}
/**
@@ -46,12 +43,14 @@ function stageSkillRuntime() {
copyDirectory(
TRIAGE_SKILL_ROOT,
path.join(stagedPluginRoot, "skills", "triage-finding"),
- new Set(["evals"]),
+ (source) => path.basename(source) !== "evals",
);
for (const sharedDirectory of ["references", "schemas"]) {
copyDirectory(
path.join(PLUGIN_ROOT, sharedDirectory),
path.join(stagedPluginRoot, sharedDirectory),
+ // Schema generation atomically renames temporary files in this directory.
+ (source) => sharedDirectory !== "schemas" || !source.endsWith(".tmp"),
);
}
fs.mkdirSync(path.join(stagedPluginRoot, "scripts"));
diff --git a/plugins/codex-security/plugin-files.json b/plugins/codex-security/plugin-files.json
index 6f06ec1dc..ded753096 100644
--- a/plugins/codex-security/plugin-files.json
+++ b/plugins/codex-security/plugin-files.json
@@ -137,7 +137,9 @@
"skills/propose-security-hardening/references/proposal-format.md",
"skills/publish-findings/SKILL.md",
"skills/publish-findings/agents/openai.yaml",
+ "skills/publish-findings/references/checkmarx-import.md",
"skills/publish-findings/references/wiz-import.md",
+ "skills/publish-findings/scripts/collect_checkmarx.py",
"skills/resolve-dependency-alert/SKILL.md",
"skills/resolve-dependency-alert/agents/openai.yaml",
"skills/security-diff-scan/SKILL.md",
diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.md
index d8b90c414..046b07428 100644
--- a/plugins/codex-security/skills/publish-findings/SKILL.md
+++ b/plugins/codex-security/skills/publish-findings/SKILL.md
@@ -43,6 +43,12 @@ Use `--provider continuum` and `--source-repository-url` for an AWS Continuum fo
Use `--provider blackduck` for a BOM-6 vulnerable-components export from one project version. Supply `--source-repository-url` after verifying the project version maps to that repository. Keep the same source key on replay and preview the destination before importing.
+## Checkmarx SAST
+
+Use `--provider checkmarx` for a Checkmarx One CLI JSON or self-managed CxSAST XML report. To retrieve a completed scan, follow the [Checkmarx collection instructions](references/checkmarx-import.md). Collection retrieves the full scan. If the user wants a subset, ask for a filtered vendor export. Before fetching CxSAST XML, verify the scan ID, project and owning team on the selected server.
+
+Preview the report for the verified repository and ref with `--dry-run --format json`. After confirmation, use the same report path and source key for the import and any retries.
+
## Veracode Static Analysis policy findings
Use `--provider veracode` with all Findings API pages for one application’s STATIC policy findings. Verify that the application maps to the repository named by `--source-repository-url`. Keep the source key stable for that application and preview the import before writing.
diff --git a/plugins/codex-security/skills/publish-findings/references/checkmarx-import.md b/plugins/codex-security/skills/publish-findings/references/checkmarx-import.md
new file mode 100644
index 000000000..65e77cea9
--- /dev/null
+++ b/plugins/codex-security/skills/publish-findings/references/checkmarx-import.md
@@ -0,0 +1,37 @@
+# Collect and import Checkmarx SAST findings
+
+Use a supplied One CLI JSON or CxSAST XML report directly. For collection, confirm the product, tenant or server, completed scan ID, project, repository URL and ref. Both collectors retrieve the full scan. If the operator wants a subset, ask for an export scoped to that selection.
+
+## Before launching a vendor tool
+
+- Use a trusted session and a private working and temporary directory outside the source tree, for both local and Cloud imports. Set the working directory **before** starting a process. Use a noninteractive, non-login system shell such as `/bin/sh` with `login: false`.
+- If an IDE or build supplies checkout-controlled startup settings, use a known-clean session or a saved export. A trusted host can exclude `LD_*`, `DYLD_*`, `BASH_ENV` and `ENV` before launching a shell or interpreter. Keep existing exclusions and account for restored shell snapshots. Never start a suspect shell to unset variables or source project files. [Codex shell environment policy](https://developers.openai.com/codex/config-advanced/)
+- Resolve the installed [collector](../scripts/collect_checkmarx.py) and vendor tools to trusted absolute paths outside the source tree. For `python_path`, use trusted system tools to inspect the executable and resolve symlinks without running it. Use the native Python 3.10+ interpreter with `-I -S`. Ask for native installation paths if given a shim or shell launcher.
+- Enable external imports. Pass the absolute checkout or unpacked source as `--source-root` before the product. Omit it only when there is no local source tree.
+
+## Checkmarx One
+
+Use native `cx` 2.3.23+. An explicit `CX_CONFIG_FILE_PATH` selects that trusted profile. Without an explicit profile, the helper uses a complete environment login if present, or `~/.checkmarx/checkmarxcli.yaml`. For an environment login, confirm the destination and keep `CX_APIKEY` or `CX_CLIENT_ID`, `CX_CLIENT_SECRET`, `CX_BASE_URI` and `CX_TENANT` in the operator's environment. A separate OAuth server also uses `CX_BASE_AUTH_URI`. For an older client or a credential-store-only login with no profile file, ask for JSON exported with the operator’s usual setup.
+
+`cx results show` retrieves every engine in a mixed scan and can generate and download an SCA package report. [Checkmarx One results](https://docs.checkmarx.com/en/34965-68640-results.html)
+
+```sh
+"$python_path" -I -S "$collector" --source-root "$source_root" one "$scan_id" --cx "$cx_path"
+```
+
+## Self-managed CxSAST
+
+**Verify ownership before fetching.** CxFlow requests XML by scan ID. Confirm the completed ID, exact project and full owning team path from the same **Projects & Scans → All Scans** row on the selected server. Use trusted read-only metadata or ask the operator to confirm those values from that view. For repeated names, check **View Project Scans** under the intended team. Without confirmation, ask for selected XML. Issue-tracker filters do not narrow the raw XML. [All Scans](https://docs.checkmarx.com/en/34965-46419-viewing-results-from-all-scans.html)
+
+Use native Java, a released CxFlow JAR (1.6.37+), and a trusted SAST-only profile with `CxXml` enabled. Keep the profile and everything it loads outside the checkout. Take the server, authentication and any custom `checkmarx.client-id` from that profile. Only append `--use-env-credentials` when the operator confirms the session's `CHECKMARX_USERNAME`, `CHECKMARX_PASSWORD` or `CHECKMARX_CLIENT_SECRET` belong to that server. For custom JVM settings or project names the installed CxFlow cannot resolve (including CJK project names on 1.7.14), ask for an XML export. [CxFlow credentials](https://github.com/checkmarx-ltd/cx-flow/blob/v1.7.14/docs/Tutorials.md#L382-L390) · [CxXml writer](https://github.com/checkmarx-ltd/cx-flow/blob/v1.7.14/docs/Bug-Trackers-and-Feedback-Channels.md#cxxml)
+
+```sh
+"$python_path" -I -S "$collector" --source-root "$source_root" cxsast "$scan_id" \
+ --java "$java_path" --jar "$jar_path" --config "$config_path" --team "$cx_team" --project "$cx_project"
+```
+
+## Preview and import
+
+Pass the successful helper's printed path as the quoted file argument to `codex-security publish findings` in the next tool call. Use `--provider checkmarx`, the requested destination, verified `--source-repository-url`, a stable product/tenant/project/ref `--source-key`, and `--dry-run --format json`. Review the scope, findings and exclusions. Verify native paths against the checkout before opening source files.
+
+After confirmation, reuse that file and those options for [local import](../SKILL.md#import-locally), [Cloud publication](../SKILL.md#publish-to-cloud) and retries. Remove the helper’s temporary directory after readback unless the operator wants it retained. Keep operator-supplied files. [User guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/checkmarx.md)
diff --git a/plugins/codex-security/skills/publish-findings/scripts/collect_checkmarx.py b/plugins/codex-security/skills/publish-findings/scripts/collect_checkmarx.py
new file mode 100644
index 000000000..2ff6bd803
--- /dev/null
+++ b/plugins/codex-security/skills/publish-findings/scripts/collect_checkmarx.py
@@ -0,0 +1,466 @@
+"""Collect a selected existing scan using the user's installed Checkmarx tools."""
+
+import argparse
+import json
+import os
+import re
+import shutil
+import signal
+import stat
+import subprocess
+import sys
+import tempfile
+import zipfile
+from contextlib import suppress
+from email.parser import BytesHeaderParser
+from pathlib import Path
+from xml.parsers import expat
+
+
+def is_link(info: os.stat_result) -> bool:
+ return stat.S_ISLNK(info.st_mode) or (
+ os.name == "nt" and info.st_reparse_tag == stat.IO_REPARSE_TAG_MOUNT_POINT
+ )
+
+
+def source_root(target: Path | None) -> Path | None:
+ if target is not None and (not target.is_absolute() or not target.is_dir()):
+ raise ValueError("Select an existing absolute source directory.")
+ source = (target or Path.cwd()).resolve()
+ # A nested checkout or submodule is still part of the enclosing source tree.
+ for parent in (*reversed(source.parents), source):
+ marker = parent / ".git"
+ try:
+ info = marker.lstat()
+ if stat.S_ISDIR(info.st_mode) and not is_link(info):
+ info = (marker / "HEAD").lstat()
+ except (FileNotFoundError, NotADirectoryError):
+ continue
+ if stat.S_ISREG(info.st_mode) or is_link(info):
+ return parent
+ return source if target is not None else None
+
+
+def in_source(path: Path, source: Path | None) -> bool:
+ if source is None:
+ return False
+ if path.is_relative_to(source):
+ return True
+ identity = source.stat()
+ current = Path()
+ parts = list(reversed(path.absolute().parts))
+ active_links = set()
+ while parts:
+ part = parts.pop()
+ if isinstance(part, Path):
+ # The link target's components have all been checked.
+ active_links.remove(part)
+ continue
+ current = current.parent if part == ".." else current / part
+ if current == source:
+ return True
+ try:
+ info = current.lstat()
+ except (FileNotFoundError, NotADirectoryError):
+ continue
+ if os.path.samestat(info, identity):
+ return True
+ if is_link(info):
+ if current in active_links:
+ raise OSError(f"Symbolic link loop at {current}")
+ active_links.add(current)
+ parts.append(current)
+ parts.extend(reversed(current.readlink().parts))
+ current = current.parent
+ return False
+
+
+def installed_file(value: str, source: Path | None) -> Path:
+ path = Path(value)
+ if path.is_absolute() and in_source(path, source):
+ raise ValueError("use an installed file outside the source checkout")
+ if not path.is_absolute() or not path.is_file():
+ raise ValueError("expected an absolute path to an existing file")
+ # Invoke the selected name for native multicall binaries.
+ return path.parent.resolve() / path.name
+
+
+def installed_launcher(value: str, source: Path | None) -> Path:
+ path = installed_file(value, source)
+ if sys.platform == "win32" and (
+ path.suffix.lower() not in {".exe", ".com"}
+ or path.resolve().suffix.lower() in {".bat", ".cmd"}
+ ):
+ raise ValueError("use a native Windows executable (.exe or .com)")
+ with path.open("rb") as image:
+ magic = image.read(4)
+ if sys.platform == "win32":
+ # The DOS header points to the PE signature.
+ image.seek(0x3C)
+ pe_offset = int.from_bytes(image.read(4), "little")
+ image.seek(pe_offset)
+ native = magic.startswith(b"MZ") and image.read(4) == b"PE\0\0"
+ elif sys.platform == "darwin":
+ # 32/64-bit thin and universal Mach-O, in either byte order.
+ native = any(
+ int.from_bytes(magic, order) in {0xFEEDFACE, 0xFEEDFACF, 0xCAFEBABE, 0xCAFEBABF}
+ for order in ("big", "little")
+ )
+ else:
+ native = magic == b"\x7fELF"
+ if not native:
+ raise ValueError("use the installed native executable for cx or java")
+ return path
+
+
+def check_cxflow_version(jar: Path) -> None:
+ # Earlier CxFlow versions accept --scanId but silently retrieve the latest scan.
+ advice = "Use a released CxFlow 1.6.37 or later, or supply a scoped CxSAST XML export."
+ try:
+ with zipfile.ZipFile(jar) as archive:
+ manifest = BytesHeaderParser().parsebytes(archive.read("META-INF/MANIFEST.MF"))
+ metadata = archive.read("META-INF/build-info.properties").decode("utf-8")
+ except (KeyError, UnicodeDecodeError, zipfile.BadZipFile) as error:
+ raise ValueError(
+ f"Could not read the CxFlow release metadata: {error}. {advice}"
+ ) from error
+ properties = dict(line.split("=", 1) for line in metadata.splitlines() if "=" in line)
+ if (
+ manifest.get("Start-Class") != "com.checkmarx.flow.CxFlowApplication"
+ or properties.get("build.group") != "com.checkmarx"
+ ):
+ raise ValueError(f"The selected JAR does not identify itself as CxFlow. {advice}")
+ version = properties.get("build.version", "")
+ if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version) or tuple(
+ map(int, version.split("."))
+ ) < (1, 6, 37):
+ raise ValueError(f"Unsupported CxFlow version {version or '(unknown)'}. {advice}")
+
+
+def private_environment(work: str, inherit: tuple[str, ...]) -> dict[str, str]:
+ env = {name: os.environ[name] for name in inherit if name in os.environ}
+ return env | dict.fromkeys(("TEMP", "TMP", "TMPDIR"), work)
+
+
+def cxsast_environment(work: str, use_env_credentials: bool = False) -> dict[str, str]:
+ # CxFlow uses the chosen profile for its server and Spring configuration.
+ credentials = ("CHECKMARX_USERNAME", "CHECKMARX_PASSWORD", "CHECKMARX_CLIENT_SECRET")
+ env = private_environment(work, credentials if use_env_credentials else ())
+ if os.name == "nt":
+ env["SystemRoot"] = os.environ["SystemRoot"]
+ else:
+ # The Java launcher decodes native arguments before applying file.encoding.
+ env["LC_CTYPE"] = "UTF-8" if sys.platform == "darwin" else "C.UTF-8"
+ return env
+
+
+def one_environment(source: Path | None, work: str) -> dict[str, str]:
+ # An inherited endpoint or proxy must never receive credentials from a saved profile.
+ account = ("HOME", "USER", "LOGNAME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "SystemRoot")
+ env = private_environment(work, (*account, "LANG", "LC_ALL", "LC_CTYPE"))
+ configured = os.environ.get("CX_CONFIG_FILE_PATH")
+ oauth = ("CX_CLIENT_ID", "CX_CLIENT_SECRET", "CX_BASE_URI", "CX_TENANT")
+ api_key = os.environ.get("CX_APIKEY")
+ if not configured and (api_key or all(os.environ.get(k) for k in oauth)):
+ # A separate config path also separates the vendor's path-keyed credential store.
+ profile = Path(work, "env-auth.yaml")
+ profile.write_text("{}\n", encoding="utf-8")
+ env["CX_CONFIG_FILE_PATH"] = str(profile)
+ env["CX_KEYRING_MODE"] = "disabled"
+ credentials = ("CX_APIKEY",) if api_key else (*oauth, "CX_BASE_AUTH_URI")
+ env.update((name, os.environ[name]) for name in credentials if os.environ.get(name))
+ return env
+
+ profile = Path(configured) if configured else Path.home() / ".checkmarx" / "checkmarxcli.yaml"
+ if not profile.is_absolute() or in_source(profile, source):
+ raise ValueError(
+ "Set CX_CONFIG_FILE_PATH to a trusted absolute path outside the source checkout. "
+ "The collector runs Checkmarx One from a private directory."
+ )
+ env["CX_CONFIG_FILE_PATH"] = configured or str(profile)
+ if "CX_KEYRING_MODE" in os.environ:
+ env["CX_KEYRING_MODE"] = os.environ["CX_KEYRING_MODE"]
+ return env
+
+
+def verify_one(report: Path, scan_id: str) -> None:
+ with report.open(encoding="utf-8-sig") as stream:
+ data = json.load(stream)
+ reported = data.get("scanID") if isinstance(data, dict) else None
+ if (
+ not isinstance(reported, str)
+ or not reported.isascii()
+ or reported.lower() != scan_id.lower()
+ ):
+ raise ValueError("The Checkmarx One report does not match the requested scan ID.")
+
+
+def team_path(value: str) -> str:
+ path = value.replace("\\", "/").strip("/")
+ return "".join(char.lower() if char.isascii() else char for char in path)
+
+
+def verify_cxsast(report: Path, scan_id: str, project: str, team: str) -> None:
+ parser = expat.ParserCreate()
+
+ def check_root(name, attributes):
+ if name != "CxXMLResults" or not attributes.get("ProjectId"):
+ raise ValueError("Expected a CxSAST XML scan report.")
+ if attributes.get("ScanId") != scan_id or attributes.get("ProjectName") != project:
+ raise ValueError("The CxSAST report does not match the requested scan and project.")
+ actual_team = attributes.get("TeamFullPathOnReportDate")
+ if not actual_team or team_path(actual_team) != team_path(team):
+ raise ValueError("The CxSAST report does not match the requested team.")
+ parser.StartElementHandler = None
+
+ parser.StartElementHandler = check_root
+ with report.open("rb") as stream:
+ parser.ParseFile(stream)
+
+
+def capture_directory(temp: Path) -> Path:
+ if os.name != "nt":
+ return Path(tempfile.mkdtemp(prefix="checkmarx-report-", dir=temp)).resolve()
+
+ import ctypes.wintypes
+ import secrets
+
+ class SecurityAttributes(ctypes.Structure):
+ _fields_ = [
+ ("length", ctypes.wintypes.DWORD),
+ ("descriptor", ctypes.wintypes.LPVOID),
+ ("inherit", ctypes.wintypes.BOOL),
+ ]
+
+ # Older Windows Python releases ignore mkdir's 0700 mode. Apply CPython's
+ # protected, inheritable SYSTEM/Administrators/owner DACL at creation.
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
+ temp = temp.resolve()
+ volume = ctypes.create_unicode_buffer(32768)
+ flags = ctypes.wintypes.DWORD()
+ if not kernel.GetVolumePathNameW(str(temp), volume, len(volume)):
+ raise ctypes.WinError(ctypes.get_last_error())
+ if not kernel.GetVolumeInformationW(volume, None, 0, None, None, ctypes.byref(flags), None, 0):
+ raise ctypes.WinError(ctypes.get_last_error())
+ if not flags.value & 0x8: # FILE_PERSISTENT_ACLS
+ raise ValueError("Select a temporary directory on a Windows volume that supports ACLs.")
+
+ security = ctypes.WinDLL("advapi32", use_last_error=True)
+ descriptor = ctypes.wintypes.LPVOID()
+ dacl = "D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;OW)"
+ if not security.ConvertStringSecurityDescriptorToSecurityDescriptorW(
+ dacl, 1, ctypes.byref(descriptor), None
+ ):
+ raise ctypes.WinError(ctypes.get_last_error())
+ try:
+ path = temp / f"checkmarx-report-{secrets.token_hex(16)}"
+ attributes = SecurityAttributes(ctypes.sizeof(SecurityAttributes), descriptor, False)
+ if not kernel.CreateDirectoryW(str(path), ctypes.byref(attributes)):
+ raise ctypes.WinError(ctypes.get_last_error())
+ return path
+ finally:
+ kernel.LocalFree(descriptor)
+
+
+def create_capture(source: Path | None) -> Path:
+ # gettempdir() probes candidates by writing a file. Check each candidate before
+ # trying to create the actual capture directory in Python's platform order.
+ cached = tempfile.tempdir
+ candidates = [cached] if cached is not None else tempfile._candidate_tempdir_list()
+ last_error = None
+ for candidate in candidates:
+ temp = Path(os.fsdecode(candidate)).absolute()
+ if in_source(temp, source):
+ raise ValueError(
+ "Select a temporary directory outside the source checkout (TMPDIR or TEMP)."
+ )
+ try:
+ return capture_directory(temp)
+ except OSError as error:
+ if cached is not None:
+ raise
+ last_error = error
+ raise FileNotFoundError(
+ f"No usable temporary directory outside the source checkout: {last_error}"
+ )
+
+
+def export_report(args: argparse.Namespace, source: Path | None, work: str, run_vendor) -> Path:
+ def fetch(report, env, *command):
+ # Only the validated report path goes to stdout; vendor diagnostics go to stderr.
+ status = run_vendor(command, cwd=work, env=env, stdin=subprocess.DEVNULL, stdout=sys.stderr)
+ if status:
+ raise ValueError(f"The Checkmarx tool exited with status {status}.")
+ if report.is_symlink() or not report.is_file():
+ raise ValueError("The Checkmarx tool did not produce the requested report.")
+
+ if args.product == "one":
+ env = one_environment(source, work)
+ report = Path(work, "cx_result.json")
+ fetch(
+ report,
+ env,
+ str(args.cx),
+ "results",
+ "show",
+ # Older clients reject this flag instead of authenticating with another profile.
+ "--config-file-path",
+ env["CX_CONFIG_FILE_PATH"],
+ "--scan-id",
+ args.scan_id,
+ "--report-format",
+ "json",
+ "--output-path",
+ work,
+ "--output-name",
+ report.stem,
+ )
+ verify_one(report, args.scan_id)
+ return report
+
+ team = args.team.rstrip("/\\")
+ report = Path(work, "checkmarx-results.xml")
+ fetch(
+ report,
+ cxsast_environment(work, args.use_env_credentials),
+ str(args.java),
+ f"-Djava.io.tmpdir={work}",
+ f"-DLOG_PATH={work}",
+ "-Dfile.encoding=UTF-8",
+ "-jar",
+ str(args.jar),
+ f"--spring.config.location={args.config.as_uri()}",
+ "--logging.config=classpath:logback-spring.xml",
+ f"--logging.file.path={work}",
+ f"--logging.file.name={Path(work, 'cx-flow.log')}",
+ f"--logging.logback.rollingpolicy.file-name-pattern={Path(work, 'cx-flow.%d{yyyy-MM-dd}.%i.gz')}",
+ "--project",
+ f"--scanId={args.scan_id}",
+ f"--cx-team={team}",
+ f"--cx-project={args.project}",
+ f"--app={args.project}",
+ "--bug-tracker=CxXml",
+ "--cx-flow.bug-tracker-impl=CxXml",
+ "--cx-flow.enabled-vulnerability-scanners=sast",
+ "--cx-flow.preserve-project-name=true",
+ "--cx-flow.mail.notification=false",
+ "--cx-flow.filter-script=",
+ "--disable-break-build",
+ "--checkmarx.cx-branch=false",
+ "--checkmarx.preserve-xml=true",
+ f"--cx-xml.data-folder={work}",
+ f"--cx-xml.file-name-format={report.name}",
+ )
+ verify_cxsast(report, str(args.scan_id), args.project, args.team)
+ return report
+
+
+def collect(args: argparse.Namespace, source: Path | None, run_vendor) -> None:
+ output = create_capture(source)
+ try:
+ with tempfile.TemporaryDirectory(dir=output) as work:
+ report = export_report(args, source, work, run_vendor)
+ report.chmod(0o600)
+ saved = report.replace(output / report.name)
+ sys.stdout.buffer.write(f"{saved}\n".encode("utf-8"))
+ sys.stdout.buffer.flush()
+ except BaseException:
+ shutil.rmtree(output)
+ raise
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--source-root", type=Path, help="absolute source directory to protect")
+ products = parser.add_subparsers(dest="product", required=True)
+ one = products.add_parser("one", help="export an existing Checkmarx One scan")
+ one.add_argument("scan_id")
+ one.add_argument("--cx", required=True)
+ cxsast = products.add_parser("cxsast", help="retrieve an existing CxSAST scan with CxFlow")
+ cxsast.add_argument("scan_id", type=int)
+ cxsast.add_argument("--java", required=True)
+ cxsast.add_argument("--jar", required=True)
+ cxsast.add_argument("--config", required=True)
+ cxsast.add_argument("--team", required=True)
+ cxsast.add_argument("--project", required=True)
+ cxsast.add_argument(
+ "--use-env-credentials",
+ action="store_true",
+ help="use the Checkmarx credentials selected for this profile's server",
+ )
+ args = parser.parse_args()
+ if os.environ.get("CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS") != "1":
+ parser.error("Set CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1 to enable external imports.")
+ if args.product == "one":
+ if not re.fullmatch(
+ r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", args.scan_id, re.I | re.ASCII
+ ):
+ parser.error("Select a Checkmarx One scan UUID in hyphenated form.")
+ else:
+ if args.scan_id <= 0:
+ parser.error("Select an existing positive CxSAST scan ID.")
+ if not re.search(r"[^\s/\\]", args.team) or not args.project.strip():
+ parser.error("Select a nonblank CxSAST team path and project.")
+
+ pending_signal = None
+ defer_termination = False
+
+ def terminate(signum, _frame):
+ nonlocal pending_signal
+ if pending_signal is None:
+ pending_signal = signum
+ if not defer_termination:
+ raise SystemExit(128 + signum)
+
+ def run_vendor(command, **kwargs):
+ nonlocal defer_termination
+ child = None
+ # Popen can have spawned the child before it returns the handle needed for cleanup.
+ defer_termination = True
+ try:
+ child = subprocess.Popen(command, start_new_session=os.name == "posix", **kwargs)
+ defer_termination = False
+ if pending_signal is not None:
+ raise SystemExit(128 + pending_signal)
+ return child.wait()
+ except BaseException:
+ defer_termination = True
+ if child is not None:
+ if os.name == "posix":
+ # Kill any surviving credential helper if the process group still exists.
+ with suppress(ProcessLookupError):
+ os.killpg(child.pid, signal.SIGKILL)
+ else:
+ child.kill()
+ child.wait()
+ raise
+ finally:
+ defer_termination = False
+
+ signals = [signal.SIGTERM]
+ if signal.getsignal(signal.SIGINT) != signal.SIG_IGN:
+ signals.append(signal.SIGINT)
+ if os.name == "posix" and signal.getsignal(signal.SIGHUP) != signal.SIG_IGN:
+ signals.append(signal.SIGHUP)
+ previous = {number: signal.signal(number, terminate) for number in signals}
+ try:
+ source = source_root(args.source_root)
+ if args.product == "one":
+ args.cx = installed_launcher(args.cx, source)
+ else:
+ args.java = installed_launcher(args.java, source)
+ args.jar = installed_file(args.jar, source)
+ args.config = installed_file(args.config, source)
+ check_cxflow_version(args.jar)
+ collect(args, source, run_vendor)
+ except (ValueError, OSError, expat.ExpatError) as error:
+ print(error, file=sys.stderr)
+ return 1
+ finally:
+ for number, handler in previous.items():
+ signal.signal(number, handler)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/plugins/codex-security/tests/test_collect_checkmarx.py b/plugins/codex-security/tests/test_collect_checkmarx.py
new file mode 100644
index 000000000..d848342e8
--- /dev/null
+++ b/plugins/codex-security/tests/test_collect_checkmarx.py
@@ -0,0 +1,750 @@
+import io
+import json
+import os
+import re
+import runpy
+import select
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+import zipfile
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+SCRIPT = (
+ Path(__file__).resolve().parents[1] / "skills/publish-findings/scripts/collect_checkmarx.py"
+)
+collector = SimpleNamespace(**runpy.run_path(str(SCRIPT)))
+ONE_SCAN = "abcdef12-0000-4000-8000-123456789abc"
+CXSAST_XML = (
+ '<CxXMLResults ScanId="1234" ProjectId="2" ProjectName="Example Project"'
+ r' TeamFullPathOnReportDate="CXSERVER\Masse Team"/>'
+)
+
+
+def capture_dir(monkeypatch, tmp_path):
+ directory = tmp_path / "private exports"
+ directory.mkdir()
+ source = tmp_path / "source"
+ source.mkdir()
+ monkeypatch.chdir(source)
+ monkeypatch.setattr(tempfile, "tempdir", str(directory))
+ monkeypatch.setenv("CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS", "1")
+ for setting in ("CX_CONFIG_FILE_PATH", "CX_APIKEY", "CX_CLIENT_ID", "CX_CLIENT_SECRET"):
+ monkeypatch.delenv(setting, raising=False)
+ return directory
+
+
+def invoke(monkeypatch, *args):
+ monkeypatch.setattr(sys, "argv", [str(SCRIPT), *args])
+ try:
+ return collector.main()
+ except SystemExit as exit:
+ return exit.code
+
+
+def mock_vendor(monkeypatch, run):
+ def popen(*args, **kwargs):
+ status = run(*args, **kwargs)
+ return SimpleNamespace(wait=lambda: status)
+
+ monkeypatch.setattr(subprocess, "Popen", popen)
+
+
+def executable(directory, name):
+ path = directory / (f"{name}.exe" if os.name == "nt" else name)
+ shutil.copy(shutil.which("true", path=os.defpath) or sys.executable, path)
+ return str(path)
+
+
+def one_args(tmp_path):
+ return ["one", ONE_SCAN, "--cx", executable(tmp_path, "cx")]
+
+
+def write_one(work, scan=ONE_SCAN):
+ report = Path(work, "cx_result.json")
+ report.write_text(json.dumps({"scanID": scan}))
+ return report
+
+
+def reject(monkeypatch, capture_dir, capsys):
+ def unexpected(command, **_kwargs):
+ pytest.fail(f"Invoked vendor before validating the request: {command}")
+
+ def check(args, message):
+ with monkeypatch.context() as patch:
+ patch.setattr(subprocess, "Popen", unexpected)
+ assert invoke(patch, *args) != 0
+ output = capsys.readouterr()
+ assert message in output.err and not output.out
+ assert not list(capture_dir.iterdir())
+
+ return check
+
+
+def directory_link(link, target):
+ if os.name == "nt":
+ subprocess.run(["cmd", "/c", "mklink", "/J", str(link), str(target)], check=True)
+ else:
+ link.symlink_to(os.path.relpath(target, link.parent), target_is_directory=True)
+
+
+def test_refuses_profile_routed_through_the_checkout(one_args, tmp_path, monkeypatch, reject):
+ source = Path.cwd()
+ installed = tmp_path / "installed"
+ installed.mkdir()
+ (installed / "profile.yaml").touch()
+ checkout_link = source / "active"
+ selected = tmp_path / "selected"
+ directory_link(checkout_link, installed)
+ directory_link(selected, checkout_link)
+ profile = selected / "profile.yaml"
+ assert profile.samefile(installed / "profile.yaml")
+ # Stand in for a checkout link to an SMB share. Following it, even to query
+ # the file type, would start authentication before the vendor process runs.
+ following = {selected, profile, checkout_link, checkout_link / "profile.yaml"}
+ original_stat = Path.stat
+ original_resolve = Path.resolve
+ original_readlink = Path.readlink
+
+ def guarded_stat(path, *args, **kwargs):
+ assert path not in following or not kwargs.get("follow_symlinks", True)
+ return original_stat(path, *args, **kwargs)
+
+ def guarded_resolve(path, *args, **kwargs):
+ assert path not in following
+ return original_resolve(path, *args, **kwargs)
+
+ def guarded_readlink(path):
+ assert path != checkout_link
+ return original_readlink(path)
+
+ monkeypatch.setattr(Path, "stat", guarded_stat)
+ monkeypatch.setattr(Path, "resolve", guarded_resolve)
+ monkeypatch.setattr(Path, "readlink", guarded_readlink)
+ with pytest.raises(ValueError, match="outside the source checkout"):
+ collector.installed_file(str(profile), source)
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("CX_CONFIG_FILE_PATH", str(profile))
+ reject(["--source-root", str(source), *one_args], "CX_CONFIG_FILE_PATH")
+
+ monkeypatch.setenv("TMPDIR", str(selected))
+ monkeypatch.setattr(tempfile, "tempdir", None)
+ monkeypatch.setattr(
+ tempfile, "mkdtemp", lambda **kwargs: pytest.fail("created a checkout-selected temp")
+ )
+ with pytest.raises(ValueError, match="temporary directory outside"):
+ collector.create_capture(source)
+
+
+def test_checkout_git_marker_does_not_follow_links(capture_dir, tmp_path, monkeypatch):
+ source = Path.cwd()
+ marker = source / ".git"
+ directory_link(marker, tmp_path)
+ original_stat = Path.stat
+
+ def guarded_stat(path, *args, **kwargs):
+ if path == marker or marker in path.parents:
+ assert path == marker and not kwargs.get("follow_symlinks", True)
+ return original_stat(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "stat", guarded_stat)
+ assert collector.source_root(source) == source
+
+
+def cxflow_jar(path, version="1.7.14", main="com.checkmarx.flow.CxFlowApplication"):
+ with zipfile.ZipFile(path, "w") as archive:
+ archive.writestr(
+ "META-INF/MANIFEST.MF", f"Manifest-Version: 1.0\r\nStart-Class: {main}\r\n\r\n"
+ )
+ archive.writestr(
+ "META-INF/build-info.properties",
+ f"build.group=com.checkmarx\nbuild.version={version}\n",
+ )
+
+
+def cxsast_args(tmp_path):
+ jar, config = tmp_path / "Cx Flow.jar", tmp_path / "private config,west.yml"
+ cxflow_jar(jar)
+ config.touch()
+ return [
+ "cxsast",
+ "1234",
+ "--team",
+ "/CxServer/Masse Team/",
+ "--project",
+ "Example Project",
+ "--jar",
+ str(jar),
+ "--config",
+ str(config),
+ "--java",
+ executable(tmp_path, "java"),
+ ]
+
+
+ "version, main",
+ [
+ ("1.6.36", "com.checkmarx.flow.CxFlowApplication"),
+ ("unknown", "com.checkmarx.flow.CxFlowApplication"),
+ ("1.7.14", "other.Application"),
+ ],
+)
+def test_refuses_unknown_or_unsupported_scan_selection(version, main, cxsast_args, reject):
+ jar = Path(cxsast_args[cxsast_args.index("--jar") + 1])
+ cxflow_jar(jar, version=version, main=main)
+ reject(cxsast_args, "scoped CxSAST XML export")
+
+
+def direct_and_symlink(target, alias):
+ yield target
+ if os.name != "nt":
+ alias.symlink_to(target, target_is_directory=target.is_dir())
+ yield alias
+
+
[email protected]("option", ["--cx", "--java", "--jar", "--config"])
+def test_refuses_vendor_files_inside_the_scan_source(
+ option, one_args, cxsast_args, monkeypatch, tmp_path, reject
+):
+ source = Path.cwd()
+ selected = source
+ args = one_args if option == "--cx" else cxsast_args
+ if option != "--cx":
+ # Select a nested checkout while the tool lives in its enclosing repository.
+ (source / ".git").mkdir()
+ (source / ".git/HEAD").touch()
+ selected = source / "src"
+ selected.mkdir()
+ (selected / ".git").write_text("gitdir: ../.git/modules/sub")
+ monkeypatch.chdir(tmp_path)
+ index = args.index(option) + 1
+ target = source / Path(args[index]).name
+ target.touch()
+ for path in direct_and_symlink(target, tmp_path / "configured-file"):
+ args[index] = str(path)
+ reject(["--source-root", str(selected), *args], "outside the source checkout")
+
+
[email protected]("suffix", [".cmd", ".BAT"])
+def test_refuses_windows_batch_launchers(suffix, cxsast_args, monkeypatch, tmp_path, reject):
+ launcher = tmp_path / f"java{suffix}"
+ launcher.touch()
+ monkeypatch.setattr(sys, "platform", "win32")
+ for path in direct_and_symlink(launcher, tmp_path / "alias.exe"):
+ cxsast_args[cxsast_args.index("--java") + 1] = str(path)
+ reject(cxsast_args, "native Windows executable")
+
+
[email protected]("setting", ["CX_CONFIG_FILE_PATH", "TMPDIR"])
+def test_refuses_vendor_paths_that_resolve_into_source(
+ setting, one_args, monkeypatch, tmp_path, reject
+):
+ selected = Path.cwd()
+ target = selected / "private"
+ if setting == "TMPDIR":
+ target.mkdir()
+ monkeypatch.setattr(tempfile, "tempdir", None)
+ else:
+ target.touch()
+ monkeypatch.chdir(tmp_path)
+ for path in direct_and_symlink(target, tmp_path / "external-alias"):
+ monkeypatch.setenv(setting, str(path))
+ reject(["--source-root", str(selected), *one_args], "outside the source checkout")
+ if target.is_dir():
+ assert not list(target.iterdir())
+
+
[email protected](os.name == "nt", reason="exercises Bash startup on Unix")
+def test_shell_launcher_cannot_load_checkout_startup_hook(capture_dir, monkeypatch, tmp_path):
+ hook = Path.cwd() / "bash-env"
+ marker = tmp_path / "hook-ran"
+ hook.write_text('printf x > "$COLLECT_HOOK_MARKER"\n')
+ monkeypatch.setenv("BASH_ENV", str(hook))
+ monkeypatch.setenv("COLLECT_HOOK_MARKER", str(marker))
+ monkeypatch.setenv("TMPDIR", str(capture_dir))
+ cx = tmp_path / "vendor cx"
+ cx.write_text("#!/usr/bin/env bash\nexit 19\n")
+ cx.chmod(0o755)
+ result = subprocess.run(
+ [sys.executable, "-I", "-S", str(SCRIPT), "one", ONE_SCAN, "--cx", str(cx)],
+ capture_output=True,
+ text=True,
+ )
+ assert result.returncode != 0 and not marker.exists()
+ assert "installed native executable" in result.stderr
+ assert not list(capture_dir.iterdir())
+
+
+def test_omitted_source_protects_only_an_enclosing_checkout(capture_dir, monkeypatch, capsys):
+ bootstrap = Path.cwd()
+ cx = executable(bootstrap, "cx")
+ temp = bootstrap / "private temp"
+ temp.mkdir()
+ monkeypatch.setattr(tempfile, "tempdir", str(temp))
+
+ def run(args, *, cwd, **kwargs):
+ write_one(cwd)
+
+ mock_vendor(monkeypatch, run)
+ request = ["one", ONE_SCAN, "--cx", cx]
+ assert invoke(monkeypatch, *request) == 0
+ assert Path(capsys.readouterr().out.strip()).is_relative_to(temp)
+
+ (bootstrap / ".git").mkdir()
+ (bootstrap / ".git" / "HEAD").touch()
+ monkeypatch.chdir(temp)
+ assert invoke(monkeypatch, *request) != 0
+ assert "outside the source checkout" in capsys.readouterr().err
+
+
+def test_one_collects_exact_scan_to_a_fresh_private_path(
+ capture_dir, monkeypatch, tmp_path, capsys
+):
+ # Pin the symlink name for native multicall binaries that dispatch on argv[0].
+ cx = executable(tmp_path, "launcher")
+ if os.name != "nt":
+ alias = tmp_path / "vendor cx"
+ alias.symlink_to(cx)
+ cx = str(alias)
+ config = tmp_path / "my cx config"
+ config.touch()
+ monkeypatch.setenv("CX_CONFIG_FILE_PATH", str(config))
+ loaders = ["LD_LIBRARY_PATH", "LD_PRELOAD", "DYLD_INSERT_LIBRARIES"]
+ checkout_bin = str(Path.cwd() / "bin")
+ for name in ["PATH", *loaders]:
+ monkeypatch.setenv(name, checkout_bin)
+ request = ["--source-root", str(Path.cwd()), "one", ONE_SCAN.upper(), "--cx", cx]
+ monkeypatch.chdir(tmp_path)
+
+ def run(args, *, cwd, env, stdout, **kwargs):
+ assert Path(cwd).is_relative_to(capture_dir)
+ assert env["CX_CONFIG_FILE_PATH"] == str(config)
+ assert {"PATH", *loaders}.isdisjoint(env)
+ assert tuple(args[:3]) == (cx, "results", "show")
+ assert dict(zip(args[3::2], args[4::2], strict=True)) == {
+ "--config-file-path": str(config),
+ "--scan-id": ONE_SCAN.upper(),
+ "--report-format": "json",
+ "--output-path": cwd,
+ "--output-name": "cx_result",
+ }
+ stdout.write("retrieved existing scan\n")
+ write_one(cwd) # Servers can return a different case for the same UUID.
+ Path(cwd, "vendor-log.txt").write_text("vendor diagnostic")
+
+ mock_vendor(monkeypatch, run)
+ reports = []
+ for _ in range(2):
+ assert invoke(monkeypatch, *request) == 0
+ output = capsys.readouterr()
+ assert "retrieved existing scan" in output.err
+ saved = Path(output.out.rstrip("\n"))
+ assert saved.is_absolute() and saved.parent.parent == capture_dir
+ assert list(saved.parent.iterdir()) == [saved]
+ assert json.loads(saved.read_text())["scanID"] == ONE_SCAN
+ if os.name == "posix":
+ assert saved.stat().st_mode & 0o777 == 0o600
+ assert saved.parent.stat().st_mode & 0o777 == 0o700
+ reports.append(saved.parent)
+ assert reports[0] != reports[1]
+ assert all(os.environ[name] == checkout_bin for name in loaders)
+
+
[email protected]("failure", ["wrong scan", "invalid JSON", "missing file", "nonzero exit"])
+def test_one_discards_failed_exports(failure, capture_dir, one_args, monkeypatch, capsys):
+ def run(args, *, cwd, **kwargs):
+ if failure == "wrong scan":
+ write_one(cwd, "00000000-0000-4000-8000-000000000002")
+ if failure in {"invalid JSON", "nonzero exit"}:
+ (Path(cwd) / "cx_result.json").write_text('{"partial":')
+ if failure == "nonzero exit":
+ kwargs["stdout"].write("vendor error while fetching the scan\n")
+ return 1 if failure == "nonzero exit" else 0
+
+ mock_vendor(monkeypatch, run)
+ assert invoke(monkeypatch, *one_args) != 0
+ output = capsys.readouterr()
+ assert not output.out
+ if failure == "nonzero exit":
+ assert "vendor error while fetching the scan" in output.err
+ assert not list(capture_dir.iterdir())
+
+
[email protected]("refusal", ["opt-in disabled", "relative config"])
+def test_one_refuses_before_vendor_invocation(refusal, one_args, monkeypatch, reject):
+ if refusal == "relative config":
+ monkeypatch.setenv("CX_CONFIG_FILE_PATH", "my-config.yaml")
+ reject(one_args, "CX_CONFIG_FILE_PATH to a trusted absolute path")
+ else:
+ monkeypatch.delenv("CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS")
+ monkeypatch.setattr(
+ Path, "is_file", lambda path: pytest.fail(f"Probed {path} before opt-in")
+ )
+ reject(one_args, "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS")
+
+
[email protected]("use_env_credentials", [False, True])
+def test_cxsast_collects_selected_scan_with_xml_tracker(
+ cxsast_args, use_env_credentials, capture_dir, monkeypatch, capsys
+):
+ credentials = {
+ "CHECKMARX_USERNAME": "synthetic-user",
+ "CHECKMARX_PASSWORD": "synthetic-password",
+ "CHECKMARX_CLIENT_SECRET": "synthetic-client-secret",
+ }
+ # Competing JVM, Spring and vendor settings must not redirect the chosen profile.
+ monkeypatch.setenv("JAVA_TOOL_OPTIONS", "-javaagent:/checkout/agent.jar")
+ monkeypatch.setenv("SPRING_MAIN_SOURCES", "file:/checkout/beans.xml")
+ monkeypatch.setenv("CHECKMARX_BASE_URL", "https://unselected.invalid")
+ for name, value in credentials.items():
+ monkeypatch.setenv(name, value)
+ if use_env_credentials:
+ cxsast_args.append("--use-env-credentials")
+
+ def run(args, *, cwd, env, **kwargs):
+ allowed = {name: str(cwd) for name in ("TMP", "TEMP", "TMPDIR")}
+ if os.name == "nt":
+ allowed["SystemRoot"] = os.environ["SystemRoot"]
+ else:
+ allowed["LC_CTYPE"] = "UTF-8" if sys.platform == "darwin" else "C.UTF-8"
+ if use_env_credentials:
+ allowed.update(credentials)
+ assert env == allowed
+ config = Path(cxsast_args[cxsast_args.index("--config") + 1])
+ assert args[0] == cxsast_args[cxsast_args.index("--java") + 1]
+ assert args[args.index("-jar") + 1] == cxsast_args[cxsast_args.index("--jar") + 1]
+ assert {
+ f"-Djava.io.tmpdir={cwd}",
+ f"-DLOG_PATH={cwd}",
+ "-Dfile.encoding=UTF-8",
+ f"--spring.config.location={config.as_uri()}",
+ "--logging.config=classpath:logback-spring.xml",
+ f"--logging.file.path={cwd}",
+ f"--logging.file.name={Path(cwd, 'cx-flow.log')}",
+ f"--logging.logback.rollingpolicy.file-name-pattern={Path(cwd, 'cx-flow.%d{yyyy-MM-dd}.%i.gz')}",
+ "--project",
+ "--scanId=1234",
+ "--cx-team=/CxServer/Masse Team",
+ "--cx-project=Example Project",
+ "--app=Example Project",
+ "--bug-tracker=CxXml",
+ "--cx-flow.bug-tracker-impl=CxXml",
+ "--cx-flow.enabled-vulnerability-scanners=sast",
+ "--cx-flow.preserve-project-name=true",
+ "--cx-flow.mail.notification=false",
+ "--cx-flow.filter-script=",
+ "--checkmarx.cx-branch=false",
+ "--checkmarx.preserve-xml=true",
+ f"--cx-xml.data-folder={cwd}",
+ "--cx-xml.file-name-format=checkmarx-results.xml",
+ } <= set(args)
+ assert "--scan" not in args
+ Path(cwd, "checkmarx-results.xml").write_text(CXSAST_XML)
+
+ mock_vendor(monkeypatch, run)
+ assert invoke(monkeypatch, *cxsast_args) == 0
+ saved = Path(capsys.readouterr().out.strip())
+ assert saved.is_relative_to(capture_dir) and saved.read_text() == CXSAST_XML
+
+
+ "before, after",
+ [
+ ("1234", "5678"),
+ ("Example Project", "Other Project"),
+ ("Masse Team", "Other Team"),
+ ("Masse Team", "Maße Team"),
+ (' TeamFullPathOnReportDate="CXSERVER\\Masse Team"', ""),
+ ("/>", ""),
+ ],
+ ids=["scan", "project", "team", "expanded-team", "missing-team", "invalid-xml"],
+)
+def test_cxsast_discards_invalid_or_mismatched_xml(
+ cxsast_args, before, after, capture_dir, monkeypatch, capsys
+):
+ def run(args, *, cwd, **kwargs):
+ Path(cwd, "checkmarx-results.xml").write_text(
+ CXSAST_XML.replace(before, after), encoding="utf-8"
+ )
+
+ mock_vendor(monkeypatch, run)
+ assert invoke(monkeypatch, *cxsast_args) != 0
+ assert not capsys.readouterr().out
+ assert not list(capture_dir.iterdir())
+
+
[email protected](os.name != "posix", reason="exercises the Unix Java launcher")
+def test_java_receives_team_and_project_names_in_the_cxsast_environment(tmp_path):
+ java = shutil.which("java")
+ if not java:
+ pytest.skip("requires a Java runtime")
+ env = collector.cxsast_environment(str(tmp_path))
+ modules = subprocess.run([java, "--list-modules"], env=env, capture_output=True)
+ compiler = re.search(rb"^jdk\.compiler@(\d+)", modules.stdout, re.MULTILINE)
+ if not compiler or int(compiler[1]) < 11:
+ pytest.skip("the Java source-file probe requires a JDK 11+ compiler module")
+ probe = tmp_path / "Names.java"
+ probe.write_text(
+ """import java.nio.file.*;
+import java.util.Arrays;
+
+class Names {
+ public static void main(String[] args) throws Exception {
+ Files.write(Path.of("arguments.txt"), Arrays.asList(args));
+ }
+}
+""",
+ encoding="ascii",
+ )
+ names = ["--cx-team=/CxServer/Équipe 東京", "--cx-project=Projet Maße"]
+ subprocess.run(
+ [java, "-Dfile.encoding=UTF-8", probe, *names], cwd=tmp_path, env=env, check=True
+ )
+ assert (tmp_path / "arguments.txt").read_text(encoding="utf-8").splitlines() == names
+
+
+def test_excludes_source_by_filesystem_identity(monkeypatch, reject):
+ source = Path.cwd()
+ checkout_file = executable(source, "cx")
+ alias = source.with_name(source.name.upper())
+ if not alias.exists():
+ # Model a filesystem preserving alternate case spellings on realpath.
+ alias.symlink_to(source, target_is_directory=True)
+ resolve = Path.resolve
+ monkeypatch.setattr(
+ Path,
+ "resolve",
+ lambda path, *args, **kw: (
+ path if path.is_relative_to(alias) else resolve(path, *args, **kw)
+ ),
+ )
+ assert source.samefile(alias)
+ args = ["one", ONE_SCAN, "--cx", str(alias / Path(checkout_file).name)]
+ reject(["--source-root", str(source), *args], "outside the source checkout")
+
+
[email protected]("scan_id", ["?limit=1", ONE_SCAN.replace("-", ""), ONE_SCAN + "\n"])
+def test_one_rejects_invalid_uuid_before_vendor_lookup(scan_id, one_args, reject):
+ one_args[1] = scan_id
+ reject(one_args, "scan UUID")
+
+
+ ("option", "name"),
+ [
+ ("--team", ""),
+ ("--team", " / \\ \t/"),
+ ("--project", "\t "),
+ ],
+)
+def test_cxsast_rejects_unselected_scope_before_vendor_lookup(option, name, cxsast_args, reject):
+ cxsast_args[cxsast_args.index(option) + 1] = name
+ reject(cxsast_args, "CxSAST team path and project")
+
+
[email protected](os.name != "posix", reason="exercises POSIX termination signals")
[email protected]("name", ["SIGTERM", "SIGHUP", "SIGINT"])
[email protected]("when", ["during launch", "while waiting", "after vendor exit"])
+def test_cancellation_reaps_vendor_and_helper(
+ when, name, one_args, capture_dir, monkeypatch, capfd
+):
+ popen = subprocess.Popen
+ child = None
+ signum = getattr(signal, name)
+ vendor = """
+import os, signal, subprocess, sys, time
+from pathlib import Path
+
+subprocess.Popen([sys.executable, "-I", "-S", "-c", "import sys; sys.stdin.read()"])
+Path("cx_result.json").write_text("partial")
+"""
+ if when == "while waiting":
+ vendor += f"os.kill(os.getppid(), signal.{name})\n"
+ if when != "after vendor exit":
+ vendor += "time.sleep(30)"
+
+ def start_child(_command, **kwargs):
+ nonlocal child
+ kwargs.update(stdin=subprocess.PIPE, stdout=subprocess.PIPE)
+ child = popen([sys.executable, "-I", "-S", "-c", vendor], **kwargs)
+ if when == "after vendor exit":
+ assert child.wait(timeout=10) == 0
+ if when != "while waiting":
+ signal.raise_signal(signum)
+ return child
+
+ monkeypatch.setattr(subprocess, "Popen", start_child)
+ previous = signal.signal(signum, lambda *_: None)
+ try:
+ assert invoke(monkeypatch, *one_args) == 128 + signum
+ assert child.returncode == (0 if when == "after vendor exit" else -signal.SIGKILL)
+ # The helper inherits stdout. EOF proves it exited along with the vendor.
+ assert select.select([child.stdout], [], [], 5)[0] and child.stdout.read(1) == b""
+ assert not capfd.readouterr().out and not list(capture_dir.iterdir())
+ finally:
+ signal.signal(signum, previous)
+ if child is not None:
+ child.stdin.close() # Release the helper even if cancellation failed.
+ child.kill()
+ child.wait()
+ child.stdout.close()
+
+
+def test_preserves_an_ignored_interrupt(capture_dir, one_args, monkeypatch):
+ def run(args, *, cwd, **kwargs):
+ assert signal.getsignal(signal.SIGINT) == signal.SIG_IGN
+ write_one(cwd)
+
+ mock_vendor(monkeypatch, run)
+ previous = signal.signal(signal.SIGINT, signal.SIG_IGN)
+ try:
+ assert invoke(monkeypatch, *one_args) == 0
+ assert signal.getsignal(signal.SIGINT) == signal.SIG_IGN
+ finally:
+ signal.signal(signal.SIGINT, previous)
+
+
[email protected](os.name != "nt", reason="requires Windows directory ACLs")
+def test_capture_private_before_vendor_writes_on_legacy_windows_python(
+ capture_dir, monkeypatch, tmp_path, capsys
+):
+ icacls = Path(os.environ["SystemRoot"]) / "System32" / "icacls.exe"
+ subprocess.run([icacls, capture_dir, "/grant", "*S-1-1-0:(OI)(CI)R"], check=True)
+
+ def dacl(path):
+ saved = tmp_path / "acl.txt"
+ subprocess.run([icacls, path, "/save", saved, "/q"], check=True)
+ value = saved.read_text(encoding="utf-16-le").rstrip().splitlines()[-1]
+ assert value.startswith("D:")
+ return value
+
+ shared = capture_dir / "control.txt"
+ shared.touch()
+ assert ";;;WD)" in dacl(shared)
+ # Windows 3.10.11 does not apply a security descriptor for mkdir(0700).
+ mkdir = os.mkdir
+ monkeypatch.setattr(os, "mkdir", lambda path, mode=0o777: mkdir(path))
+ profile = tmp_path / "trusted.yaml"
+ profile.touch()
+ monkeypatch.setenv("CX_CONFIG_FILE_PATH", str(profile))
+
+ def run(_command, *, cwd, **_kwargs):
+ work = Path(cwd)
+ root_acl = dacl(work.parent)
+ assert root_acl.startswith("D:P") and ";;;WD)" not in root_acl
+ assert ";;;WD)" not in dacl(work)
+ assert ";;;WD)" not in dacl(write_one(work))
+
+ args = SimpleNamespace(product="one", scan_id=ONE_SCAN, cx="unused")
+ collector.collect(args, None, run)
+ assert ";;;WD)" not in dacl(Path(capsys.readouterr().out.strip()))
+
+
[email protected]("login", ["named-profile", "default-profile", "env-oauth", "env-key"])
+def test_one_keeps_credentials_with_the_selected_login(
+ one_args, capture_dir, tmp_path, monkeypatch, login
+):
+ selected = tmp_path / "signed in.yaml"
+ selected.write_text("cx_client_id: saved-account\n")
+ oauth = {
+ "CX_CLIENT_ID": "test-account",
+ "CX_CLIENT_SECRET": "synthetic-secret",
+ "CX_BASE_URI": "https://api.example.invalid",
+ "CX_TENANT": "example",
+ "CX_BASE_AUTH_URI": "https://identity.example.invalid",
+ }
+ for name, value in oauth.items():
+ monkeypatch.setenv(name, value)
+ for proxy in ["CX_HTTP_PROXY", "http_proxy", "HTTP_PROXY"]:
+ monkeypatch.setenv(proxy, "http://proxy.example.invalid")
+ monkeypatch.setenv("CX_KEYRING_MODE", "required")
+ if login == "named-profile":
+ monkeypatch.setenv("CX_CONFIG_FILE_PATH", str(selected))
+ if login == "default-profile":
+ monkeypatch.delenv("CX_CLIENT_ID")
+ if login in {"named-profile", "env-key"}:
+ monkeypatch.setenv("CX_APIKEY", "synthetic-key")
+
+ def run(command, *, cwd, env, **_kwargs):
+ assert command[command.index("--config-file-path") + 1] == env["CX_CONFIG_FILE_PATH"]
+ assert {"HTTP_PROXY", "http_proxy", "CX_HTTP_PROXY"}.isdisjoint(env)
+ if login in {"named-profile", "default-profile"}:
+ assert oauth.keys().isdisjoint(env) and "CX_APIKEY" not in env
+ assert env.get("CX_CONFIG_FILE_PATH") == (
+ str(selected)
+ if login == "named-profile"
+ else str(Path.home() / ".checkmarx" / "checkmarxcli.yaml")
+ )
+ assert env["CX_KEYRING_MODE"] == "required"
+ else:
+ profile = Path(env["CX_CONFIG_FILE_PATH"])
+ assert profile.parent == Path(cwd) and profile.read_text() == "{}\n"
+ assert env["CX_KEYRING_MODE"] == "disabled"
+ if login == "env-key":
+ assert env["CX_APIKEY"] == "synthetic-key" and oauth.keys().isdisjoint(env)
+ else:
+ assert {name: env[name] for name in oauth} == oauth and "CX_APIKEY" not in env
+ write_one(cwd)
+
+ mock_vendor(monkeypatch, run)
+ assert invoke(monkeypatch, *one_args) == 0
+
+
[email protected]("reader_open", [True, False])
+def test_report_path_handoff_uses_utf8_on_a_redirected_pipe(
+ capture_dir, monkeypatch, one_args, reader_open
+):
+ temp = capture_dir / "東京"
+ temp.mkdir()
+ monkeypatch.setattr(tempfile, "tempdir", str(temp))
+ monkeypatch.setenv("CX_CONFIG_FILE_PATH", str(capture_dir / "profile.yaml"))
+
+ def export(_command, *, cwd, **_kwargs):
+ write_one(cwd)
+
+ mock_vendor(monkeypatch, export)
+
+ read_fd, write_fd = os.pipe()
+ with os.fdopen(read_fd, "rb") as reader, os.fdopen(write_fd, "wb", buffering=0) as writer:
+ with io.TextIOWrapper(writer, encoding="cp1252") as stdout, monkeypatch.context() as patch:
+ patch.setattr(sys, "stdout", stdout)
+ if not reader_open:
+ reader.close()
+ assert invoke(patch, *one_args) == (0 if reader_open else 1)
+ if reader_open:
+ saved = next(temp.glob("checkmarx-report-*/cx_result.json"))
+ assert reader.read() == f"{saved}\n".encode("utf-8")
+ else:
+ assert not list(temp.iterdir())
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 96a8d1c11..8dbd5c147 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -703,6 +703,13 @@ with a saved list or detail response, or `normalizeContinuumFindings(input, sour
with parsed JSON. Verify the repository for the selected findings before passing its Git URL.
[Continuum import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/continuum.md)
+For a saved Checkmarx One CLI JSON or CxSAST XML report, use
+`readCheckmarxFindings(path, sourceRepositoryUrl, "local")` to inspect its evidence.
+To prepare a local import, pass `provider: "checkmarx"` and the verified
+`sourceRepositoryUrl` to `prepareLocalExternalImport`. Keep each batch of normalized
+Checkmarx findings scoped to one scan and its repository.
+[Checkmarx SAST import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/checkmarx.md)
+
Use `collectSelectedSemgrepGuardianFindings` with a connected Guardian MCP client to
[capture selected Code or Supply Chain findings](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#import-selected-guardian-findings) using the user's Guardian sign-in.
Use `normalizeSelectedSemgrepPlatformFindings` for selected SAST findings from saved
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index b2d253b30..caacaae95 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -1388,6 +1388,9 @@ To [collect a full Semgrep project and branch](https://github.com/openai/codex-s
For completed scans exported in the Codex Security JSON or CSV format, use
[scan import](#import-findings-as-a-saved-scan).
+For Checkmarx One CLI JSON or CxSAST XML, use `--provider checkmarx` and pass the
+verified Git URL with `--source-repository-url`. See the [Checkmarx SAST guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/checkmarx.md).
+
## Import Endor Labs findings
Use `--provider endor` for one Endor project and context. The
diff --git a/sdk/typescript/schemas/external-findings.schema.json b/sdk/typescript/schemas/external-findings.schema.json
index 54f05f1b9..c79c9a22c 100644
--- a/sdk/typescript/schemas/external-findings.schema.json
+++ b/sdk/typescript/schemas/external-findings.schema.json
@@ -388,7 +388,8 @@
"blackduck",
"veracode",
"sonar",
- "continuum"
+ "continuum",
+ "checkmarx"
],
"title": "Provider",
"type": "string"
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index 01e6d793b..c6daf912f 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -32,6 +32,11 @@ const distModules = [
"scanner-import",
"inspector-findings",
"continuum-findings",
+ "checkmarx-evidence",
+ "checkmarx-findings",
+ "checkmarx-one",
+ "checkmarx-repository",
+ "checkmarx-xml",
"snyk-findings",
"snyk-rest-findings",
"snyk-rest-v1",
diff --git a/sdk/typescript/src/checkmarx-evidence.ts b/sdk/typescript/src/checkmarx-evidence.ts
new file mode 100644
index 000000000..e4c43909f
--- /dev/null
+++ b/sdk/typescript/src/checkmarx-evidence.ts
@@ -0,0 +1,66 @@
+import {
+ type ExternalImportTarget,
+ validateExternalEvidence,
+} from "./external-import-contract.js";
+import { scannerSeverity, text } from "./scanner-import.js";
+
+interface CheckmarxReport extends Record<string, unknown> {
+ format: "checkmarx-one-json" | "cxsast-xml";
+ sourceRepositoryUrl: string;
+ scanId: string;
+}
+
+interface CheckmarxOccurrence {
+ title: string;
+ ruleId: unknown;
+ severity: unknown;
+ description?: unknown;
+ status?: unknown;
+ verdict?: unknown;
+ cwe?: unknown;
+ sourceData: Record<string, unknown>;
+}
+
+function idText(value: unknown) {
+ return typeof value === "number" ? String(value) : text(value);
+}
+
+export function checkmarxEvidence(
+ report: CheckmarxReport,
+ row: CheckmarxOccurrence,
+ target: ExternalImportTarget,
+) {
+ const severity = text(row.severity)?.toLowerCase();
+ const cwe = idText(row.cwe) ?? "";
+ return validateExternalEvidence(
+ {
+ title: row.title,
+ severity:
+ severity === "info" || severity === "information"
+ ? "informational"
+ : scannerSeverity(severity),
+ description: text(row.description),
+ source_scan_id: report.scanId,
+ // Filenames are relative to the scanned sources, which can be a ZIP or subdirectory.
+ locations: [],
+ details: {
+ kind: "sast",
+ repository: { url: report.sourceRepositoryUrl },
+ scanner_origin:
+ report.format === "checkmarx-one-json"
+ ? "Checkmarx One SAST"
+ : "CxSAST",
+ rule: { id: idText(row.ruleId), name: row.title },
+ source_status: text(row.status),
+ scanner_verdict: text(row.verdict),
+ weakness_ids: /^[1-9]\d*$/u.test(cwe) ? [`CWE-${cwe}`] : [],
+ },
+ source_data: {
+ ...row.sourceData,
+ format: report.format,
+ sourceRepositoryUrl: report.sourceRepositoryUrl,
+ },
+ },
+ target,
+ );
+}
diff --git a/sdk/typescript/src/checkmarx-findings.ts b/sdk/typescript/src/checkmarx-findings.ts
new file mode 100644
index 000000000..68257e4e9
--- /dev/null
+++ b/sdk/typescript/src/checkmarx-findings.ts
@@ -0,0 +1,38 @@
+import { normalizeCheckmarxOne } from "./checkmarx-one.js";
+import { normalizeCheckmarxXml } from "./checkmarx-xml.js";
+import type { ExternalImportTarget } from "./external-import-contract.js";
+import { readScannerBytes } from "./scanner-import.js";
+import { declaredScannerRepositoryUrl } from "./scanner-repository-url.js";
+
+// XML can signal its byte order with a BOM or the opening '<' code unit.
+function reportEncoding(bytes: Buffer) {
+ const [first, second] = bytes;
+ if ((first === 0xff && second === 0xfe) || (first === 0x3c && second === 0))
+ return "utf-16le";
+ if ((first === 0xfe && second === 0xff) || (first === 0 && second === 0x3c))
+ return "utf-16be";
+ return "utf-8";
+}
+
+/** Read a Checkmarx One CLI JSON export or a self-managed CxSAST XML report. */
+export async function readCheckmarxFindings(
+ path: string,
+ sourceRepositoryUrl: string,
+ target: ExternalImportTarget = "cloud",
+) {
+ const repository = declaredScannerRepositoryUrl(
+ sourceRepositoryUrl,
+ "Checkmarx",
+ target,
+ );
+ const bytes = await readScannerBytes(path);
+ const encoding = reportEncoding(bytes);
+ const contents = new TextDecoder(encoding, { fatal: true }).decode(bytes);
+ const first = contents.trimStart()[0];
+ if (first === "<") return normalizeCheckmarxXml(contents, repository, target);
+ if (first === "{" && encoding === "utf-8")
+ return normalizeCheckmarxOne(contents, repository, target);
+ throw new Error(
+ "Expected a Checkmarx One CLI JSON report or a CxSAST XML report.",
+ );
+}
diff --git a/sdk/typescript/src/checkmarx-one.ts b/sdk/typescript/src/checkmarx-one.ts
new file mode 100644
index 000000000..0973c0daf
--- /dev/null
+++ b/sdk/typescript/src/checkmarx-one.ts
@@ -0,0 +1,92 @@
+import { checkmarxEvidence } from "./checkmarx-evidence.js";
+import type { ExternalImportTarget } from "./external-import-contract.js";
+import {
+ array,
+ normalizeRecords,
+ record,
+ requiredText,
+ stableId,
+} from "./scanner-import.js";
+
+export function checkmarxOneId(value: unknown): string {
+ const row = record(value, "Checkmarx One result");
+ const type = requiredText(row["type"], "Checkmarx One result type");
+ if (type !== "sast")
+ throw new Error(
+ `Checkmarx One result type ${type} is outside the SAST import.`,
+ );
+ const data = record(row["data"], "Checkmarx One SAST data");
+ return stableId("checkmarx-one", [
+ requiredText(row["similarityId"], "Checkmarx One similarityId"),
+ requiredText(data["resultHash"], "Checkmarx One resultHash"),
+ ]);
+}
+
+export function normalizeCheckmarxOne(
+ contents: string,
+ repository: string,
+ target: ExternalImportTarget,
+) {
+ // SAST query IDs can be 64-bit integers. Keep their exact digits in evidence.
+ function preserveQueryId(
+ key: string,
+ value: unknown,
+ context?: { source: string },
+ ) {
+ if (
+ key === "queryId" &&
+ Number.isInteger(value) &&
+ !Number.isSafeInteger(value)
+ )
+ return context!.source;
+ return value;
+ }
+ const document = record(
+ JSON.parse(contents, preserveQueryId),
+ "Checkmarx One CLI JSON report",
+ );
+ const scanId = requiredText(document["scanID"], "Checkmarx One scanID");
+ const rows =
+ document["results"] === null && document["totalCount"] === 0
+ ? []
+ : array(document["results"], "Checkmarx One results");
+ if (document["totalCount"] !== rows.length)
+ throw new Error(
+ "Checkmarx One totalCount must equal the number of exported results.",
+ );
+ const report = {
+ format: "checkmarx-one-json",
+ scanId,
+ sourceRepositoryUrl: repository,
+ totalCount: rows.length,
+ } as const;
+ return normalizeRecords(
+ rows,
+ (value) => {
+ const row = record(value, "Checkmarx One result");
+ const data = record(row["data"], "Checkmarx One SAST data");
+ for (const node of array(data["nodes"] ?? [], "Checkmarx One SAST nodes"))
+ record(node, "Checkmarx One SAST node");
+ return checkmarxEvidence(
+ report,
+ {
+ title: requiredText(data["queryName"], "Checkmarx One queryName"),
+ ruleId: data["queryId"],
+ severity: row["severity"],
+ description: row["description"],
+ status: row["status"],
+ verdict: row["state"],
+ cwe: record(
+ row["vulnerabilityDetails"] ?? {},
+ "Checkmarx One vulnerability details",
+ )["cweId"],
+ sourceData: { row },
+ },
+ target,
+ );
+ },
+ checkmarxOneId,
+ target,
+ { report },
+ );
+}
diff --git a/sdk/typescript/src/checkmarx-repository.ts b/sdk/typescript/src/checkmarx-repository.ts
new file mode 100644
index 000000000..c23af52d5
--- /dev/null
+++ b/sdk/typescript/src/checkmarx-repository.ts
@@ -0,0 +1,240 @@
+import type { ExternalFinding, ExternalFindings } from "./external-findings.js";
+import type { ExternalImportTarget } from "./external-import-contract.js";
+import type { Provider } from "./external-import-models.js";
+import { isRecord } from "./record.js";
+import { requiredText, text } from "./scanner-import.js";
+import { checkmarxOneId } from "./checkmarx-one.js";
+import {
+ checkmarxResultViewer,
+ checkmarxXmlId,
+ checkmarxXmlInstance,
+ checkmarxXmlScope,
+} from "./checkmarx-xml.js";
+import {
+ declaredScannerRepositoryUrl,
+ repositoryScopeValidator,
+} from "./scanner-repository-url.js";
+
+const nativeId = /^checkmarx-(?:one|cxsast):[a-f0-9]{64}$/u;
+
+function checkmarxFormat(value: unknown) {
+ return value === "cxsast-xml" || value === "checkmarx-one-json";
+}
+
+function scanKey(value: unknown, xml: boolean) {
+ const uuid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/iu;
+ return !xml && typeof value === "string" && uuid.test(value)
+ ? value.toLowerCase()
+ : value;
+}
+
+/** A native payload can verify its occurrence ID. A projection can still identify its source. */
+function checkmarxSource(
+ { source_finding_id: id, evidence }: ExternalFinding,
+ provider?: Provider,
+) {
+ const data = evidence.source_data;
+ const format = data?.["format"];
+ if (checkmarxFormat(format)) return format;
+ const scanner = evidence.details?.scanner_origin;
+ const projected =
+ nativeId.test(id) ||
+ scanner === "CxSAST" ||
+ scanner === "Checkmarx One SAST" ||
+ Boolean(checkmarxResultViewer(data));
+ if (
+ data &&
+ (provider === "checkmarx" || projected || "sourceRepositoryUrl" in data)
+ ) {
+ const row = data["row"];
+ if (isRecord(row) && row["type"] === "sast" && "similarityId" in row)
+ return "checkmarx-one-json";
+ const path = data["path"];
+ if ("projectId" in data && isRecord(path) && "SimilarityId" in path)
+ return "cxsast-xml";
+ }
+ if (projected) return "projection";
+}
+
+const mismatch =
+ "Checkmarx finding does not match the retained report format, scan or project.";
+
+/** Compare the claims present across the whole batch, including projected SDK rows. */
+function checkBatchScope(
+ findings: readonly ExternalFinding[],
+ formats: Iterable<string>,
+ report: ExternalFindings["report"],
+) {
+ const claims = new Map<string, unknown>();
+ function claim(key: string, value: unknown) {
+ if (value == null) return;
+ if (claims.has(key) && claims.get(key) !== value)
+ throw new Error(
+ report
+ ? mismatch
+ : "Checkmarx occurrences must belong to the same product, project and scan.",
+ );
+ claims.set(key, value);
+ }
+
+ for (const format of [report?.["format"], ...formats])
+ if (checkmarxFormat(format))
+ claim(
+ "scanner",
+ format === "cxsast-xml" ? "CxSAST" : "Checkmarx One SAST",
+ );
+ const sources = [report];
+ for (const { evidence } of findings) {
+ claim("scanner", evidence.details?.scanner_origin);
+ if (evidence.source_data) sources.push(evidence.source_data);
+ }
+ if (sources.some(checkmarxResultViewer)) claim("scanner", "CxSAST");
+ const xml = claims.get("scanner") === "CxSAST";
+ const named =
+ xml || sources.some((data) => text(data?.["teamFullPathOnReportDate"]));
+ claim("scan", scanKey(report?.["scanId"], xml));
+ for (const { evidence } of findings)
+ claim("scan", scanKey(evidence.source_scan_id, xml));
+
+ let instance: string | undefined;
+ for (const data of sources) {
+ if (!data) continue;
+ claim("project", data["projectId"]);
+ if (named) {
+ claim("project name", text(data["projectName"]));
+ claim(
+ "team",
+ text(data["teamFullPathOnReportDate"])
+ ?.replaceAll("\\", "/")
+ .replace(/^\/+|\/+$/gu, "")
+ .replace(/[A-Z]/gu, (c) => c.toLowerCase()),
+ );
+ }
+ // A URL identifies a deployment; other instance metadata in SDK rows is opaque.
+ const url = data["instance"];
+ if (
+ xml ||
+ (typeof url === "string" &&
+ /^https?:$/u.test(URL.parse(url)?.protocol ?? ""))
+ ) {
+ const scope = checkmarxXmlScope(data);
+ instance = checkmarxXmlInstance(instance, scope.instance);
+ claim("project", scope.projectId);
+ claim("scan", scope.scanId);
+ }
+ }
+}
+
+/** Identify report and row provenance once for both import destinations. */
+export function checkmarxSelection(
+ provider: Provider,
+ findings: ExternalFindings["findings"],
+ report: ExternalFindings["report"],
+ target: ExternalImportTarget,
+ historical = false,
+) {
+ const selected = provider === "checkmarx";
+ const replay = historical && !selected;
+ const format = report?.["format"];
+ const nativeReport = checkmarxFormat(format);
+ const formats = new Map<ExternalFinding, string>();
+ for (const finding of findings) {
+ const kind = checkmarxSource(finding, provider);
+ if (kind) formats.set(finding, kind);
+ }
+ const validateUrl = (value: unknown) =>
+ declaredScannerRepositoryUrl(value, "Checkmarx", target);
+ function requireProvider() {
+ if (!selected)
+ throw new Error(
+ "Retained Checkmarx evidence requires the checkmarx provider.",
+ );
+ }
+ if (selected) checkBatchScope(findings, formats.values(), report);
+ let reportUrl: string | undefined;
+ if (report && nativeReport && !replay) {
+ requireProvider();
+ const xml = format === "cxsast-xml";
+ const scan = scanKey(
+ requiredText(report["scanId"], "Checkmarx report scan ID"),
+ xml,
+ );
+ const project = xml
+ ? requiredText(report["projectId"], "CxSAST report project ID")
+ : undefined;
+ for (const finding of findings) {
+ const { evidence } = finding;
+ const data = evidence.source_data;
+ if (
+ (data && "format" in data ? data["format"] : formats.get(finding)) !==
+ format ||
+ scanKey(evidence.source_scan_id, xml) !== scan ||
+ (xml && data?.["projectId"] !== project)
+ )
+ throw new Error(mismatch);
+ }
+ reportUrl = validateUrl(report["sourceRepositoryUrl"]);
+ } else if (report) {
+ if (selected && "sourceRepositoryUrl" in report && "scanId" in report)
+ throw new Error("Expected the original Checkmarx report format.");
+ if (
+ typeof report["sourceRepositoryUrl"] === "string" &&
+ (selected || nativeReport || formats.size)
+ )
+ reportUrl = validateUrl(report["sourceRepositoryUrl"]);
+ }
+ const marked = new Set(nativeReport || reportUrl ? findings : formats.keys());
+ function projectedRepository({ evidence }: ExternalFinding) {
+ const source = evidence.source_data?.["sourceRepositoryUrl"];
+ const url =
+ typeof source === "string"
+ ? validateUrl(source)
+ : evidence.details?.repository?.url;
+ return url ? { url } : undefined;
+ }
+ const validateRows = repositoryScopeValidator(
+ {
+ provider: "checkmarx",
+ label: "Checkmarx",
+ scope: "product, project and scan",
+ },
+ (_, finding) => {
+ const { source_finding_id: id, evidence } = finding;
+ const data = evidence.source_data;
+ const kind = formats.get(finding);
+ if (checkmarxFormat(kind) && data) {
+ requireProvider();
+ requiredText(evidence.source_scan_id, "Checkmarx source scan ID");
+ const expected =
+ kind === "cxsast-xml"
+ ? checkmarxXmlId(data)
+ : checkmarxOneId(data["row"]);
+ if (id !== expected)
+ throw new Error(
+ "Checkmarx source finding ID does not match the retained occurrence.",
+ );
+ return { url: validateUrl(data["sourceRepositoryUrl"]), scope: kind };
+ }
+ if (selected && nativeId.test(id))
+ throw new Error(
+ "Checkmarx source finding ID requires its original evidence.",
+ );
+ if (selected && data && "sourceRepositoryUrl" in data)
+ return { url: validateUrl(data["sourceRepositoryUrl"]) };
+ return kind ? projectedRepository(finding) : undefined;
+ },
+ );
+ return {
+ reportUrl,
+ projections: selected ? new Set<ExternalFinding>() : marked,
+ repositories(sameRepositories?: (urls: Iterable<string>) => boolean) {
+ const rows =
+ replay || (!selected && !formats.size)
+ ? undefined
+ : validateRows(provider, findings, target, sameRepositories);
+ return (finding: ExternalFinding) =>
+ rows?.get(finding.source_finding_id) ??
+ (marked.has(finding) ? projectedRepository(finding) : undefined);
+ },
+ };
+}
diff --git a/sdk/typescript/src/checkmarx-xml.ts b/sdk/typescript/src/checkmarx-xml.ts
new file mode 100644
index 000000000..3e3f67c85
--- /dev/null
+++ b/sdk/typescript/src/checkmarx-xml.ts
@@ -0,0 +1,268 @@
+import { SaxesParser } from "saxes";
+import { asRecord } from "./record.js";
+import { checkmarxEvidence } from "./checkmarx-evidence.js";
+import type { ExternalImportTarget } from "./external-import-contract.js";
+import {
+ array,
+ normalizeRecords,
+ record,
+ requiredText,
+ stableId,
+ text,
+} from "./scanner-import.js";
+
+type Attributes = Record<string, string>;
+interface Element {
+ name: string;
+ attributes: Attributes;
+ children: Element[];
+ text: string;
+}
+
+function fields(element: Element): Attributes {
+ return Object.fromEntries(
+ element.children
+ .filter((child) => !child.children.length)
+ .map((child) => [child.name, child.text]),
+ );
+}
+
+function pathNode(element: Element): Record<string, unknown> {
+ const node: Record<string, unknown> = fields(element);
+ const snippet = element.children.find((child) => child.name === "Snippet");
+ if (snippet)
+ node["Snippet"] = snippet.children
+ .filter((child) => child.name === "Line")
+ .map(fields);
+ return node;
+}
+
+interface Row extends Record<string, unknown> {
+ projectId: string;
+ query: Attributes;
+ result: Attributes;
+ path: Attributes | null;
+ nodes: Record<string, unknown>[];
+}
+
+const viewerPath = "/cxwebclient/viewermain.aspx";
+
+function viewerLink(value: unknown) {
+ const url = typeof value === "string" ? URL.parse(value) : null;
+ if (
+ url &&
+ /^https?:$/u.test(url.protocol) &&
+ url.pathname.toLowerCase().endsWith(viewerPath)
+ )
+ return url;
+}
+
+function viewerInstance(link: URL | undefined) {
+ return link && link.origin + link.pathname.slice(0, -viewerPath.length);
+}
+
+function instanceKey(value: string) {
+ const url = URL.parse(value);
+ return url && /^https?:$/u.test(url.protocol) ? url.href : value;
+}
+
+export function checkmarxXmlInstance(
+ current: string | undefined,
+ next: string | undefined,
+) {
+ if (
+ current !== undefined &&
+ next !== undefined &&
+ current !== next &&
+ instanceKey(current) !== instanceKey(next)
+ )
+ throw new Error("CxSAST viewer links must identify the same instance.");
+ return current ?? next;
+}
+
+function viewerId(link: URL | undefined, field: string, expected?: string) {
+ let selected = expected;
+ for (const [key, id] of link?.searchParams ?? []) {
+ if (!id || key.toLowerCase() !== field) continue;
+ if (selected !== undefined && selected !== id)
+ throw new Error(`CxSAST DeepLink ${field} does not match the report.`);
+ selected = id;
+ }
+ return selected;
+}
+
+export function checkmarxResultViewer(
+ source: Record<string, unknown> | null | undefined,
+) {
+ return viewerLink(asRecord(source?.["result"])?.["DeepLink"]);
+}
+
+export function checkmarxXmlScope(
+ source: Record<string, unknown>,
+ scanId?: string,
+ projectId?: string,
+) {
+ const link = checkmarxResultViewer(source);
+ viewerId(
+ link,
+ "pathid",
+ text(asRecord(source["path"])?.["PathId"]) ?? undefined,
+ );
+ const instance = source["instance"];
+ return {
+ instance: checkmarxXmlInstance(
+ instance === undefined
+ ? undefined
+ : requiredText(instance, "CxSAST instance"),
+ viewerInstance(link),
+ ),
+ scanId: viewerId(link, "scanid", scanId),
+ projectId: viewerId(link, "projectid", projectId),
+ };
+}
+
+function readReport(contents: string) {
+ const rows: Row[] = [];
+ const stack: Element[] = [];
+ const parser = new SaxesParser({ xmlns: false });
+ let scanId = "";
+ let rootInstance: string | undefined;
+ const project: Attributes & { projectId: string } = { projectId: "" };
+ parser.on("opentag", ({ name, attributes }) => {
+ const element: Element = { name, attributes, children: [], text: "" };
+ if (!stack.length) {
+ if (name !== "CxXMLResults")
+ throw new Error("Expected a Checkmarx CxSAST CxXMLResults report.");
+ project.projectId = requiredText(
+ attributes["ProjectId"],
+ "CxSAST ProjectId",
+ );
+ scanId = requiredText(attributes["ScanId"], "CxSAST ScanId");
+ const projectName = text(attributes["ProjectName"]);
+ const team = text(attributes["TeamFullPathOnReportDate"]);
+ if (projectName) project["projectName"] = projectName;
+ if (team) project["teamFullPathOnReportDate"] = team;
+ const link = viewerLink(attributes["DeepLink"]);
+ viewerId(link, "scanid", scanId);
+ viewerId(link, "projectid", project.projectId);
+ rootInstance = viewerInstance(link);
+ } else if (
+ (stack.length === 1 && name !== "Query") ||
+ (stack.length === 2 && name !== "Result")
+ ) {
+ throw new Error("Expected CxSAST results directly under their Query.");
+ }
+ // Only build subtrees within the current result, then release them.
+ if (stack.length >= 3) stack.at(-1)!.children.push(element);
+ stack.push(element);
+ });
+ function appendText(value: string) {
+ const element = stack.at(-1);
+ if (element) element.text += value;
+ }
+ parser.on("text", appendText);
+ parser.on("cdata", appendText);
+ parser.on("closetag", () => {
+ const element = stack.pop()!;
+ const parent = stack.at(-1);
+ if (parent?.name !== "Query" || stack.length !== 2) return;
+ const paths = element.children.filter((child) => child.name === "Path");
+ const path = paths.length === 1 ? paths[0] : undefined;
+ rows.push({
+ ...project,
+ query: parent.attributes,
+ result: element.attributes,
+ path: path?.attributes ?? null,
+ nodes:
+ path?.children
+ .filter((child) => child.name === "PathNode")
+ .map(pathNode) ?? [],
+ });
+ });
+ parser.write(contents).close();
+ return { rows, project, scanId, rootInstance };
+}
+
+/** SimilarityId groups paths, including paths with different intermediate nodes. */
+export function checkmarxXmlId(source: Record<string, unknown>): string {
+ const projectId = requiredText(source["projectId"], "CxSAST ProjectId");
+ const query = record(source["query"], "CxSAST Query");
+ const result = record(source["result"], "CxSAST Result");
+ const path = record(source["path"], "CxSAST Path");
+ const nodes = array(source["nodes"], "CxSAST Path nodes");
+ const route = (nodes.length ? nodes : [result]).map((value) => {
+ const node = record(value, "CxSAST path node");
+ return ["FileName", "Line", "Column", "Name", "Type"].map((field) =>
+ text(node[field]),
+ );
+ });
+ return stableId("checkmarx-cxsast", [
+ projectId,
+ requiredText(query["id"], "CxSAST Query id"),
+ requiredText(path["SimilarityId"], "CxSAST SimilarityId"),
+ route,
+ ]);
+}
+
+export function normalizeCheckmarxXml(
+ contents: string,
+ repository: string,
+ target: ExternalImportTarget,
+) {
+ const { rows, project, scanId, rootInstance } = readReport(contents);
+ function normalize(instance: string | undefined) {
+ const report = {
+ format: "cxsast-xml",
+ scanId,
+ ...project,
+ ...(instance && { instance }),
+ sourceRepositoryUrl: repository,
+ } as const;
+ return normalizeRecords(
+ rows,
+ (row) => {
+ const { query, result } = row;
+ return checkmarxEvidence(
+ report,
+ {
+ title: requiredText(query["name"], "CxSAST Query name"),
+ ruleId: query["id"],
+ severity: text(result["Severity"]) ?? query["Severity"],
+ description: result["Remark"],
+ status: result["Status"],
+ verdict:
+ result["FalsePositive"]?.toLowerCase() === "true"
+ ? "False positive"
+ : result["state"],
+ cwe: query["cweId"],
+ sourceData:
+ !row["instance"] && instance ? { ...row, instance } : row,
+ },
+ target,
+ );
+ },
+ (row) => {
+ const scope = checkmarxXmlScope(row, scanId, project.projectId);
+ if (scope.instance) row["instance"] = scope.instance;
+ return checkmarxXmlId(row);
+ },
+ target,
+ { report },
+ );
+ }
+
+ const result = normalize(rootInstance);
+ let instance = rootInstance;
+ let hasUnboundRows = false;
+ for (const { evidence } of result.findings) {
+ const rowInstance = text(evidence.source_data?.["instance"]);
+ if (rowInstance) instance = checkmarxXmlInstance(instance, rowInstance);
+ else hasUnboundRows = true;
+ }
+ if (instance && !rootInstance) {
+ // Count inherited instance bytes before accepting linkless findings for Cloud.
+ if (hasUnboundRows) return normalize(instance);
+ result.report!["instance"] = instance;
+ }
+ return result;
+}
diff --git a/sdk/typescript/src/endor-findings.ts b/sdk/typescript/src/endor-findings.ts
index c65ed60e6..cb207e955 100644
--- a/sdk/typescript/src/endor-findings.ts
+++ b/sdk/typescript/src/endor-findings.ts
@@ -1,7 +1,7 @@
import type { ExternalImportTarget } from "./external-import-contract.js";
import { validateExternalEvidence } from "./external-import-contract.js";
import type { ExternalFindings } from "./external-findings.js";
-import { isRecord } from "./record.js";
+import { asRecord } from "./record.js";
import {
array,
hasSarifExternalPropertyReferences,
@@ -17,10 +17,20 @@ import {
} from "./scanner-import.js";
/** @internal Repository claims retained in the adapter's original SARIF context. */
-export function endorRepositoryUrls(sourceData: unknown): string[] {
- if (!isRecord(sourceData)) return [];
- const run = sourceData["runContext"];
+export function endorRepositoryUrls(
+ sourceData: unknown,
+ retainedUrlsOnly = false,
+): string[] {
+ const run = asRecord(sourceData)?.["runContext"];
if (run == null) return [];
+ if (retainedUrlsOnly) {
+ // Historical projections can retain opaque run metadata alongside explicit URLs.
+ const entries = asRecord(run)?.["versionControlProvenance"];
+ if (!Array.isArray(entries)) return [];
+ return entries
+ .map((entry) => asRecord(entry)?.["repositoryUri"])
+ .filter((url) => typeof url === "string");
+ }
return array(
record(run, "Endor run context")["versionControlProvenance"] ?? [],
"Endor version control provenance",
diff --git a/sdk/typescript/src/external-findings-local.ts b/sdk/typescript/src/external-findings-local.ts
index e7fe7ad12..245449b67 100644
--- a/sdk/typescript/src/external-findings-local.ts
+++ b/sdk/typescript/src/external-findings-local.ts
@@ -56,6 +56,7 @@ import {
isGitSsh,
parseGitRemote,
} from "./git-remote.js";
+import { checkmarxSelection } from "./checkmarx-repository.js";
import { continuumReportRepositories } from "./continuum-findings.js";
import { veracodeReportRepositories } from "./veracode-findings.js";
import { inspectorReportRepository } from "./inspector-findings.js";
@@ -275,7 +276,8 @@ function remoteRepository(
const name = gitPathToHttpPath(gitPath.slice(0, suffix?.index));
// Azure's generated SCP clone URL spells spaces as %20, even though Git sends SCP paths literally.
const azure =
- provider === "sonar" && !(scpStyle && path.startsWith("/"))
+ (provider === "sonar" || provider === "checkmarx") &&
+ !(scpStyle && path.startsWith("/"))
? azureReposHttpsUrl(
url,
scpStyle ? name.replace(/%2520/gu, "%20") : name,
@@ -530,8 +532,9 @@ export async function configuredFetchRemotes(
throw error;
}
const remotes: ConfiguredFetchRemote[] = [];
+ const firstUrlOnly = provider === "sonar" || provider === "checkmarx";
for (const name of remoteNames.split(/\r?\n/u).filter(Boolean)) {
- if (provider === "sonar") {
+ if (firstUrlOnly) {
// Git fetches from only the first URL, after insteadOf rewrites.
const url = await readGit(["remote", "get-url", "--", name]);
if (/[\r\n]/u.test(url))
@@ -560,6 +563,7 @@ async function requireMatchingRepository(
signal?: AbortSignal,
possibleSshHost?: string,
fetchRemotes?: readonly ConfiguredFetchRemote[],
+ isCheckmarxSource?: (url: string) => boolean,
): Promise<boolean> {
if (!snyk && sources.length === 0 && hostedSources.length === 0) return false;
let allSourcesMatched = true;
@@ -594,17 +598,20 @@ async function requireMatchingRepository(
}
if (!sources.length) return allSourcesMatched;
}
+ const remoteProvider = (checkmarx?: boolean) =>
+ checkmarx && provider !== "sonar" ? "checkmarx" : provider;
const remotes =
fetchRemotes ??
(await configuredFetchRemotes(
repository,
- provider,
+ remoteProvider(Boolean(isCheckmarxSource)),
protectedRoots,
environment,
signal,
));
const boundProvider =
provider === "sonar" ||
+ provider === "checkmarx" ||
provider === "continuum" ||
provider === "inspector" ||
provider === "blackduck" ||
@@ -621,8 +628,9 @@ async function requireMatchingRepository(
const bound = boundProvider || strictSources.has(source.url);
const platform =
strictSources.get(source.url) ?? platformFor(source, bound);
- const identity = (url: string) =>
- remoteRepository(url, provider, bound, platform);
+ const sourceProvider = remoteProvider(isCheckmarxSource?.(source.url));
+ const identity = (url: string, fallbackHost?: string) =>
+ remoteRepository(url, sourceProvider, bound, platform, fallbackHost);
const targets = comparable.flatMap((remote) => identity(remote) ?? []);
const target = identity(source.url);
if (target && targets.some((remote) => matchingRemote(remote, target)))
@@ -631,9 +639,7 @@ async function requireMatchingRepository(
// A custom SSH upstream can agree with a manual mapping even when a
// recognized HTTPS remote points at a fork. It cannot prove a Cloud binding.
const configured = unverified.flatMap(
- (remote) =>
- remoteRepository(remote, provider, bound, platform, possibleSshHost) ??
- [],
+ (remote) => identity(remote, possibleSshHost) ?? [],
);
if (target && configured.some((remote) => matchingRemote(remote, target)))
continue;
@@ -818,12 +824,18 @@ export async function prepareLocalImport(
"local",
options.inspectorProjectMap,
);
- const projected =
- options.provider === "blackduck"
- ? []
- : current.findings.filter((finding) =>
- projectedBlackDuckRepositoryUrl(finding, "local"),
- );
+ const checkmarx = checkmarxSelection(
+ options.provider,
+ current.findings,
+ current.report,
+ "local",
+ );
+ const projected = current.findings.filter(
+ (finding) =>
+ (options.provider !== "blackduck" &&
+ projectedBlackDuckRepositoryUrl(finding, "local")) ||
+ checkmarx.projections.has(finding),
+ );
const mixed = projected.length > 0 && readerSources.length > 0;
const nativeSources = new Map(
(mixed ? current.findings : projected)
@@ -870,6 +882,7 @@ export async function prepareLocalImport(
"local",
sameRepositories,
);
+ const checkmarxRepository = checkmarx.repositories(sameRepositories);
for (const repositories of [
veracodeReportRepositories,
continuumReportRepositories,
@@ -884,6 +897,7 @@ export async function prepareLocalImport(
}
}
const strictSources = new Map<string, Provider>();
+ const checkmarxKeys = new Set<string>();
const hostedSources = new Map<string, ExternalSourceRepository>();
const semgrepReportScope = semgrepPlatformReportScope(
current,
@@ -924,7 +938,8 @@ export async function prepareLocalImport(
let hasOrdinaryRows = false;
let ordinaryRowNeedsReferences = false;
for (const finding of current.findings) {
- const retained = bound.get(finding.source_finding_id);
+ const retained =
+ bound.get(finding.source_finding_id) ?? checkmarxRepository(finding);
const native = nativeSources.get(finding) ?? [];
const sarif = hasPlatformEvidence ? semgrepSarifRepositories(finding) : [];
const semgrep = semgrepPlatformFindingBinding(
@@ -970,11 +985,12 @@ export async function prepareLocalImport(
}
}
}
- if (retained) {
+ const projectedCheckmarx = checkmarx.projections.has(finding);
+ if (retained || (projectedCheckmarx && native.length)) {
+ const rowSources = retained ? [retained, ...native] : native;
const claims = [
- retained.url,
+ ...rowSources.map((ref) => ref.url),
...(url ? [url] : []),
- ...native.map((ref) => ref.url),
];
const rowPlatform = (claim: string) =>
options.provider !== "wiz"
@@ -1000,9 +1016,9 @@ export async function prepareLocalImport(
throw new CodexSecurityError(
"The retained scanner repository does not match the original provider finding.",
);
- for (const source of [retained, ...native])
- sources.set(source.url, source);
+ for (const source of rowSources) sources.set(source.url, source);
for (const claim of claims) {
+ if (projectedCheckmarx) checkmarxKeys.add(identify(claim).key);
const platform = rowPlatform(claim);
if (!strictSources.has(claim) || platform !== "github")
strictSources.set(claim, platform);
@@ -1152,6 +1168,23 @@ export async function prepareLocalImport(
options.inspectorProjectMap ? { url: source.url } : source,
);
}
+ const reportUrl = checkmarx.reportUrl;
+ if (reportUrl) {
+ const source = sources.get(reportUrl) ?? { url: reportUrl };
+ sources.set(reportUrl, source);
+ checkmarxKeys.add(identify(reportUrl).key);
+ if (!strictSources.has(reportUrl))
+ strictSources.set(reportUrl, platformFor(source));
+ }
+ if (
+ ((options.provider === "checkmarx" || reportUrl) &&
+ !sameRepositories(sources.keys())) ||
+ (reportUrl &&
+ hosted.some((source) => !semgrepReferenceMatches(source, reportUrl)))
+ )
+ throw new Error(
+ "The retained Checkmarx report repository does not match the finding repository.",
+ );
const sonarSources = sonarRepositoryUrls(
options.provider,
current.findings,
@@ -1240,6 +1273,9 @@ export async function prepareLocalImport(
dependencies.signal,
selected?.protocol === "https:" ? selected.hostname : undefined,
fetchRemotes,
+ checkmarx.projections.size
+ ? (url) => checkmarxKeys.has(identify(url).key)
+ : undefined,
);
dependencies.signal?.throwIfAborted();
const preview = {
diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.ts
index ea693fe80..7a3926f35 100644
--- a/sdk/typescript/src/external-findings-publish.ts
+++ b/sdk/typescript/src/external-findings-publish.ts
@@ -96,6 +96,7 @@ import {
blackDuckReportRepositories,
projectedBlackDuckRepositoryUrl,
} from "./blackduck-findings.js";
+import { checkmarxSelection } from "./checkmarx-repository.js";
import { continuumReportRepositories } from "./continuum-findings.js";
import { veracodeReportRepositories } from "./veracode-findings.js";
import { inspectorReportRepository } from "./inspector-findings.js";
@@ -2705,8 +2706,8 @@ async function preparePublicationInput(
if (legacyTypedUrl) requireApprovedSource(legacyTypedUrl);
function checkRepositories(
- findings: ExternalFindings["findings"],
- report?: ExternalFindings["report"],
+ { findings, report }: Pick<ExternalFindings, "findings" | "report">,
+ historicalCheckmarx = Boolean(saved),
) {
// A catalog casing or spelling change keeps the original source comparison target.
const approved = hosted ? saved?.approvedRepositoryUrl : undefined;
@@ -2748,9 +2749,18 @@ async function preparePublicationInput(
))
requireDestination("Sonar source", url);
}
+ const checkmarx = checkmarxSelection(
+ options.provider,
+ findings,
+ report,
+ "cloud",
+ historicalCheckmarx,
+ );
+ requireDestination("Checkmarx source", checkmarx.reportUrl);
const repositories = replay
? undefined
: blackDuckReportRepositories(options.provider, findings, "cloud");
+ const checkmarxRepository = checkmarx.repositories();
for (const [provider, repositories] of [
["veracode", veracodeReportRepositories],
["continuum", continuumReportRepositories],
@@ -2778,23 +2788,27 @@ async function preparePublicationInput(
}
for (const finding of findings) {
const { source_finding_id: id, evidence } = finding;
- const projected = repositories
+ const blackDuckUrl = repositories
? repositories.get(id)?.url
: projectedBlackDuckRepositoryUrl(finding, "cloud");
+ const hasProjection =
+ !!blackDuckUrl || checkmarx.projections.has(finding);
if (
replay &&
- !projected &&
+ !hasProjection &&
options.provider !== "inspector" &&
options.provider !== "veracode" &&
+ options.provider !== "checkmarx" &&
options.provider !== "continuum" &&
options.provider !== "sonar"
)
continue;
const urls = [
- projected,
+ blackDuckUrl,
+ checkmarxRepository(finding)?.url,
evidence.details?.repository?.url,
options.provider === "wiz"
- ? projected
+ ? hasProjection
? wizFindingRepository(evidence, "cloud")?.url
: wizCsvRepositoryUrl(evidence)
: undefined,
@@ -2804,7 +2818,10 @@ async function preparePublicationInput(
})
: []),
...(options.provider === "endor"
- ? endorRepositoryUrls(evidence.source_data)
+ ? endorRepositoryUrls(
+ evidence.source_data,
+ Boolean(replay && !blackDuckUrl),
+ )
: []),
options.provider === "github"
? dependabotRepository(finding)
@@ -2828,16 +2845,21 @@ async function preparePublicationInput(
);
}
}
- checkRepositories(parsed.findings, parsed.report);
+ // Existing repository submissions keep their original request bodies and receipts.
+ const privatePath = join(state, `${key}.private-import.json`);
+ const privateSaved = await readOptionalFile(privatePath);
+ const usePrivateImport =
+ !saved &&
+ (privateProviders?.has(source.provider) || privateSaved !== undefined);
+ if (!usePrivateImport) checkRepositories(parsed);
// A retry sends its saved projection, which may differ from today's reader.
if (saved) {
- // A common Sonar ref can supply missing row refs. Only use the report
- // associated with the input digest in the saved checkpoint.
+ // Only use the report associated with the input digest in the saved checkpoint.
const report =
saved.inputProjection?.inputDigest === inputDigest
? parsed.report
: undefined;
- checkRepositories(submissionFindings(saved.requests), report);
+ checkRepositories({ findings: submissionFindings(saved.requests), report });
}
// An older, genuinely unbound checkpoint first acquires a URL on a matching preview.
@@ -2872,13 +2894,8 @@ async function preparePublicationInput(
saved.approvedRepositoryPlatform = current.approvedRepositoryPlatform;
});
}
- // Existing repository submissions keep their original request bodies and receipts.
- const privatePath = join(state, `${key}.private-import.json`);
- const privateSaved = await readOptionalFile(privatePath);
- if (
- !saved &&
- (privateProviders?.has(source.provider) || privateSaved !== undefined)
- ) {
+
+ if (usePrivateImport) {
const client = privateImportClient(
apiBaseUrl,
credentials,
@@ -2939,6 +2956,8 @@ async function preparePublicationInput(
context.formats.includes(report.format)
? previous?.jobId
: undefined;
+ const resumed = previous !== undefined && retryOfJobId === undefined;
+ checkRepositories(parsed, resumed);
const privateImport = {
format: report.format,
contextVersion: binding.contextVersion,
@@ -2952,7 +2971,7 @@ async function preparePublicationInput(
accountId: credentials.account_id,
destination,
source,
- resumed: previous !== undefined && !retryOfJobId,
+ resumed,
requests: [],
privateImport,
};
@@ -2972,6 +2991,7 @@ async function preparePublicationInput(
const retrying =
retryOfJobId !== undefined && stored?.receipt?.id === retryOfJobId;
const active = retrying ? undefined : stored;
+ if (resumed && !active) checkRepositories(parsed);
requireAccess(current, !!active?.fileId, !!active?.jobId);
if (await selectedCheckpoint())
throw new CodexSecurityError(
diff --git a/sdk/typescript/src/external-findings-read.ts b/sdk/typescript/src/external-findings-read.ts
index 750068d0f..5f53c2f24 100644
--- a/sdk/typescript/src/external-findings-read.ts
+++ b/sdk/typescript/src/external-findings-read.ts
@@ -20,6 +20,7 @@ import { readSonarFindings } from "./sonar-findings.js";
import { readVeracodeFindings } from "./veracode-findings.js";
import { readBlackDuckFindings } from "./blackduck-findings.js";
import { readContinuumFindings } from "./continuum-findings.js";
+import { readCheckmarxFindings } from "./checkmarx-findings.js";
import { readInspectorFindings } from "./inspector-findings.js";
import { isRecord } from "./record.js";
import {
@@ -42,6 +43,7 @@ export const EXTERNAL_FINDINGS_PROVIDERS = {
veracode: "veracode",
sonar: "sonar",
continuum: "continuum",
+ checkmarx: "checkmarx",
} as const satisfies Record<string, Provider>;
export type ExternalFindingsReader = keyof typeof EXTERNAL_FINDINGS_PROVIDERS;
@@ -188,6 +190,7 @@ export async function readExternalFindings(
if (
options.provider === "inspector" ||
options.provider === "continuum" ||
+ options.provider === "checkmarx" ||
options.provider === "blackduck" ||
options.provider === "veracode"
) {
@@ -195,6 +198,7 @@ export async function readExternalFindings(
const read = {
inspector: readInspectorFindings,
continuum: readContinuumFindings,
+ checkmarx: readCheckmarxFindings,
blackduck: readBlackDuckFindings,
veracode: readVeracodeFindings,
}[options.provider];
diff --git a/sdk/typescript/src/external-import-models.ts b/sdk/typescript/src/external-import-models.ts
index c2c0d7be4..e5dd99c81 100644
--- a/sdk/typescript/src/external-import-models.ts
+++ b/sdk/typescript/src/external-import-models.ts
@@ -15,7 +15,8 @@ export type Provider =
| "blackduck"
| "veracode"
| "sonar"
- | "continuum";
+ | "continuum"
+ | "checkmarx";
export type SourceKey = string;
export type ClientId = string;
export type SourceFindingId = string;
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
index 2b483d7aa..cd9edf7dd 100644
--- a/sdk/typescript/src/index.ts
+++ b/sdk/typescript/src/index.ts
@@ -350,6 +350,7 @@ export {
normalizeContinuumFindings,
readContinuumFindings,
} from "./continuum-findings.js";
+export { readCheckmarxFindings } from "./checkmarx-findings.js";
export {
normalizeInspectorFindings,
readInspectorFindings,
diff --git a/sdk/typescript/src/scanner-import.ts b/sdk/typescript/src/scanner-import.ts
index 723f479bf..82e69d9c9 100644
--- a/sdk/typescript/src/scanner-import.ts
+++ b/sdk/typescript/src/scanner-import.ts
@@ -80,7 +80,9 @@ export function stableId(prefix: string, fields: unknown[]): string {
const strictUtf8 = new TextDecoder("utf-8", { fatal: true });
const gunzipAsync = promisify(gunzip);
-async function readScannerBytes(path: string | FileHandle): Promise<Buffer> {
+export async function readScannerBytes(
+ path: string | FileHandle,
+): Promise<Buffer> {
const bytes = await readFile(path);
return bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipAsync(bytes) : bytes;
}
diff --git a/sdk/typescript/tests-ts/checkmarx-import.test.ts b/sdk/typescript/tests-ts/checkmarx-import.test.ts
new file mode 100644
index 000000000..9e1e1da49
--- /dev/null
+++ b/sdk/typescript/tests-ts/checkmarx-import.test.ts
@@ -0,0 +1,249 @@
+import { expect, test } from "bun:test";
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { gzipSync } from "node:zlib";
+import { readCheckmarxFindings } from "../src/checkmarx-findings.js";
+import { main } from "../src/cli.js";
+import type { ExternalFinding } from "../src/external-findings.js";
+import { dependencies } from "./cli-fixtures.js";
+import {
+ createAndReplayFinding,
+ localReportFixture,
+ updateStoredFinding,
+} from "./external-findings-local-helpers.js";
+import { createCliTest } from "./support/cli-run.js";
+import { scopedTemporaryDirectory } from "./support/temporary-directories.js";
+
+const repositoryUrl = "https://github.com/example/project";
+const checkmarx = {
+ provider: "checkmarx",
+ sourceKey: "example/project/main",
+ sourceRepositoryUrl: repositoryUrl,
+} as const;
+
+function projectedRow(
+ url: string,
+ scanner: string | null = "CxSAST",
+): ExternalFinding {
+ return {
+ source_finding_id: url,
+ evidence: {
+ title: "Synthetic issue",
+ severity: "low",
+ details: { kind: "sast", scanner_origin: scanner, repository: { url } },
+ },
+ };
+}
+
+function oneReport(severity: string) {
+ return JSON.stringify({
+ scanID: "00000000-0000-4000-8000-000000000001",
+ totalCount: 1,
+ results: [
+ {
+ type: "sast",
+ similarityId: "-202",
+ severity,
+ data: {
+ queryName: "SQL_Injection",
+ resultHash: "a1b2c3",
+ nodes: [{ fileName: "/src/query.ts", line: 3, column: 7 }],
+ },
+ },
+ ],
+ });
+}
+
+function xmlReport(severity: string) {
+ return `<?xml version="1.0" encoding="UTF-8"?>
+<CxXMLResults ScanId="100" ProjectId="7">
+ <Query id="17" name="SQL_Injection">
+ <Result Severity="${severity}">
+ <Path SimilarityId="-202">
+ <PathNode><FileName>src/query.ts</FileName><Line>3</Line><Column>7</Column></PathNode>
+ </Path>
+ </Result>
+ </Query>
+</CxXMLResults>`;
+}
+
+for (const [format, report] of [
+ ["json", oneReport],
+ ["xml", xmlReport],
+] as const) {
+ test(`Checkmarx ${format} previews in the CLI and replays one unassessed finding in the workbench`, async () => {
+ await using fixture = await localReportFixture(
+ `checkmarx.${format}.gz`,
+ checkmarx,
+ { remote: repositoryUrl },
+ );
+ await writeFile(fixture.file, gzipSync(report("High")));
+ const cli = createCliTest(main);
+ const code = await cli.runCli(
+ [
+ "publish",
+ "findings",
+ fixture.file,
+ "--to",
+ "local",
+ "--repository",
+ fixture.repository,
+ "--provider",
+ "checkmarx",
+ "--source-key",
+ fixture.sourceKey,
+ "--source-repository-url",
+ repositoryUrl,
+ "--dry-run",
+ "--format",
+ "json",
+ ],
+ dependencies({ environment: fixture.environment }),
+ );
+ expect({ code, stderr: cli.stderr.text() }).toEqual({
+ code: 0,
+ stderr: "",
+ });
+ expect(JSON.parse(cli.stdout.text())).toMatchObject({
+ dryRun: true,
+ source: { provider: "checkmarx", source_key: fixture.sourceKey },
+ read: 1,
+ excluded: [],
+ findings: [{ evidence: { severity: "high", details: { kind: "sast" } } }],
+ });
+ await expect(
+ fixture.prepare({
+ sourceRepositoryUrl: "https://github.com/example/other",
+ }),
+ ).rejects.toThrow(/does not match/iu);
+ const stored = await createAndReplayFinding(fixture);
+ expect(stored.evidence.locations).toEqual([]);
+ await writeFile(fixture.file, gzipSync(report("Medium")));
+ expect((await updateStoredFinding(fixture, stored)).evidence.severity).toBe(
+ "medium",
+ );
+ });
+}
+
+test.each([
+ ["[email protected]:v3/team/project/repo", "project"],
+ ["ssh://[email protected]:22/v3/team/My%20Project/repo", "My%20Project"],
+ ["[email protected]:v3/team/My%20Project/repo", "My%20Project"],
+])(
+ "Checkmarx matches its HTTPS repository to Azure Repos clone %s",
+ async (remote, project) => {
+ const url = `https://dev.azure.com/team/${project}/_git/repo`;
+ await using fixture = await localReportFixture(
+ "checkmarx.json",
+ { ...checkmarx, sourceRepositoryUrl: url },
+ { remote },
+ );
+ await writeFile(fixture.file, oneReport("High"));
+ expect((await fixture.prepare()).matchesRepositoryRemote).toBe(true);
+ await expect(
+ fixture.prepare({ sourceRepositoryUrl: url + "-other" }),
+ ).rejects.toThrow(/does not match a configured remote/);
+ },
+);
+
+test("Wiz imports match Azure SSH remotes for their projected Checkmarx rows", async () => {
+ const url = "https://dev.azure.com/team/project/_git/repo";
+ const remote = "[email protected]:v3/team/project/repo";
+ await using fixture = await localReportFixture(
+ "wiz.json",
+ { provider: "wiz", sourceKey: "team/project" },
+ { remote },
+ );
+ const prepare = (...findings: ExternalFinding[]) =>
+ fixture.prepareNormalized({
+ read: findings.length,
+ excluded: [],
+ findings,
+ });
+ expect((await prepare(projectedRow(url))).matchesRepositoryRemote).toBe(true);
+ await expect(prepare(projectedRow(url + "-other"))).rejects.toThrow(
+ /does not match a configured remote/,
+ );
+ fixture.git("remote", "add", "second", remote + "-other");
+ const sibling = {
+ ...projectedRow(url + "-other", null),
+ source_finding_id: "blackduck-bom:" + "a".repeat(64),
+ };
+ await expect(prepare(projectedRow(url), sibling)).rejects.toThrow(
+ /repo-other.*does not match a configured remote/,
+ );
+});
+
+test("reads plain and gzipped UTF-16 CxSAST XML while keeping Checkmarx One JSON UTF-8", async () => {
+ await using dir = await scopedTemporaryDirectory("checkmarx-encodings-");
+ const file = join(dir.path, "report");
+ const read = () => readCheckmarxFindings(file, repositoryUrl, "local");
+ const xml = xmlReport("High").replaceAll("src/query.ts", "src/résumé.ts");
+ await writeFile(file, xml);
+ const expected = await read();
+ expect(expected.findings).toHaveLength(1);
+
+ for (const order of ["LE", "BE"]) {
+ for (const prefix of ["", "\uFEFF"]) {
+ const declaration = prefix ? "UTF-16" : "UTF-16" + order;
+ const bytes = Buffer.from(
+ prefix + xml.replace("UTF-8", declaration),
+ "utf16le",
+ );
+ if (order === "BE") bytes.swap16();
+ for (const report of [bytes, gzipSync(bytes)]) {
+ await writeFile(file, report);
+ expect(await read()).toEqual(expected);
+ }
+ }
+ }
+ await writeFile(file, Buffer.from("\uFEFF" + oneReport("High"), "utf16le"));
+ await expect(read()).rejects.toThrow();
+
+ const malformed = Buffer.from(
+ "\uFEFF" + xml.replace("UTF-8", "UTF-16"),
+ "utf16le",
+ );
+ malformed.writeUInt16LE(
+ 0xd800,
+ malformed.indexOf(Buffer.from("résumé.ts", "utf16le")),
+ );
+ await writeFile(file, malformed);
+ await expect(read()).rejects.toMatchObject({
+ code: "ERR_ENCODING_INVALID_ENCODED_DATA",
+ });
+});
+
+test.each(["checkmarx", "wiz"] as const)(
+ "%s binds Checkmarx evidence only to the effective Git fetch URL",
+ async (provider) => {
+ const primary = "https://github.com/example/primary";
+ await using fixture = await localReportFixture(
+ "checkmarx.json",
+ { provider, sourceKey: checkmarx.sourceKey },
+ { remote: primary, isolatedGit: true },
+ );
+ await writeFile(fixture.file, oneReport("High"));
+ const prepare = () =>
+ provider === "checkmarx"
+ ? fixture.prepare({ sourceRepositoryUrl: repositoryUrl })
+ : fixture.prepareNormalized({
+ read: 1,
+ excluded: [],
+ report: { format: "sdk-selection" },
+ findings: [projectedRow(repositoryUrl)],
+ });
+
+ fixture.git("config", "--add", "remote.origin.url", repositoryUrl);
+ await expect(prepare()).rejects.toThrow(
+ /does not match a configured remote/,
+ );
+ const setOrigin = (value: string) =>
+ fixture.git("config", "--replace-all", "remote.origin.url", value);
+ setOrigin(primary + "\n" + repositoryUrl);
+ await expect(prepare()).rejects.toThrow(/contains a line break/);
+ setOrigin("alias:example/project");
+ fixture.git("config", "url.https://github.com/.insteadOf", "alias:");
+ expect((await prepare()).matchesRepositoryRemote).toBe(true);
+ },
+);
diff --git a/sdk/typescript/tests-ts/checkmarx-one.test.ts b/sdk/typescript/tests-ts/checkmarx-one.test.ts
new file mode 100644
index 000000000..55fb77fe7
--- /dev/null
+++ b/sdk/typescript/tests-ts/checkmarx-one.test.ts
@@ -0,0 +1,136 @@
+import { expect, test } from "bun:test";
+import { normalizeCheckmarxOne } from "../src/checkmarx-one.js";
+
+const repository = "https://github.com/example/sample";
+const scanID = "71000000-0000-4000-8000-000000000001";
+const sast = {
+ type: "sast",
+ id: "101",
+ similarityId: "-2001",
+ status: "RECURRENT",
+ state: "TO_VERIFY",
+ severity: "HIGH",
+ description: "Input flows to the database call.",
+ data: {
+ queryId: 101,
+ queryName: "SQL_Injection",
+ resultHash: "cGF0aC1vbmU=",
+ nodes: [
+ { fileName: "/src/input.ts", line: 12, column: 3 },
+ { fileName: "/src/database.ts", line: 27, column: 5 },
+ ],
+ },
+ vulnerabilityDetails: { cweId: 89 },
+};
+
+const read = (json: string) => normalizeCheckmarxOne(json, repository, "local");
+const report = (results: unknown[], scan = scanID) =>
+ JSON.stringify({ scanID: scan, results, totalCount: results.length });
+
+test("retains native SAST flow and vendor triage from mixed-engine CLI JSON", () => {
+ // A query ID emitted as a JSON integer can exceed JavaScript's exact range.
+ const contents = report([{ type: "sca" }, sast, { type: "kics" }]).replace(
+ '"queryId":101',
+ '"queryId":9007199254740993',
+ );
+ const normalized = read(contents);
+ expect(normalized.read).toBe(3);
+ expect(normalized.excluded.map(({ position }) => position)).toEqual([1, 3]);
+ expect(normalized.findings).toHaveLength(1);
+ expect(normalized.findings[0]!.evidence).toMatchObject({
+ title: "SQL_Injection",
+ severity: "high",
+ description: sast.description,
+ source_scan_id: scanID,
+ locations: [],
+ details: {
+ repository: { url: repository },
+ source_status: "RECURRENT",
+ scanner_verdict: "TO_VERIFY",
+ rule: { id: "9007199254740993" },
+ weakness_ids: ["CWE-89"],
+ },
+ source_data: {
+ row: { ...sast, data: { ...sast.data, queryId: "9007199254740993" } },
+ },
+ });
+});
+
+test("separates paths sharing a similarity ID and excludes every exact identity collision", () => {
+ const anotherPath = {
+ ...sast,
+ data: { ...sast.data, resultHash: "cGF0aC10d28=" },
+ };
+ const initial = read(report([sast, anotherPath]));
+ expect(initial.excluded).toEqual([]);
+ const firstId = initial.findings[0]!.source_finding_id;
+ const secondId = initial.findings[1]!.source_finding_id;
+ expect(firstId).not.toBe(secondId);
+ const changed = read(
+ report(
+ [{ ...sast, id: "202", severity: "MEDIUM" }],
+ "71000000-0000-4000-8000-000000000002",
+ ),
+ );
+ expect(changed.findings[0]!.source_finding_id).toBe(firstId);
+ const overlap = read(report([sast, anotherPath, sast]));
+ expect(overlap.findings.map((f) => f.source_finding_id)).toEqual([secondId]);
+ expect(overlap.excluded).toMatchObject([
+ { position: 1, source_finding_id: firstId },
+ { position: 3, source_finding_id: firstId },
+ ]);
+});
+
+test("rejects partial and other JSON formats while accepting the CLI's empty collection", () => {
+ for (const results of [[], null]) {
+ expect(
+ read(JSON.stringify({ scanID, results, totalCount: 0 })),
+ ).toMatchObject({
+ read: 0,
+ findings: [],
+ excluded: [],
+ });
+ }
+ for (const document of [
+ { results: [], totalCount: 0 },
+ { scanID, totalCount: 0 },
+ { scanID, results: [sast], totalCount: 2 },
+ { scanID, results: null, totalCount: 3 },
+ { ScanSummary: {}, ScanResults: [] },
+ ]) {
+ expect(() => read(JSON.stringify(document))).toThrow();
+ }
+});
+
+test("reports malformed SAST identities and evidence at their original positions", () => {
+ const malformed = read(
+ report([
+ { ...sast, similarityId: "" },
+ { ...sast, data: { ...sast.data, resultHash: null } },
+ {
+ ...sast,
+ data: { ...sast.data, resultHash: "another-hash", nodes: {} },
+ },
+ sast,
+ ]),
+ );
+ expect(malformed.read).toBe(4);
+ expect(malformed.findings).toHaveLength(1);
+ expect(malformed.excluded).toMatchObject([
+ {
+ position: 1,
+ source_finding_id: null,
+ reason: expect.stringContaining("similarityId"),
+ },
+ {
+ position: 2,
+ source_finding_id: null,
+ reason: expect.stringContaining("resultHash"),
+ },
+ {
+ position: 3,
+ source_finding_id: expect.any(String),
+ reason: expect.stringContaining("nodes"),
+ },
+ ]);
+});
diff --git a/sdk/typescript/tests-ts/checkmarx-repository.test.ts b/sdk/typescript/tests-ts/checkmarx-repository.test.ts
new file mode 100644
index 000000000..b4388498f
--- /dev/null
+++ b/sdk/typescript/tests-ts/checkmarx-repository.test.ts
@@ -0,0 +1,491 @@
+import { expect, test } from "bun:test";
+import { normalizeCheckmarxOne } from "../src/checkmarx-one.js";
+import { normalizeCheckmarxXml } from "../src/checkmarx-xml.js";
+import { prepareNormalizedLocalImport } from "../src/external-findings-local.js";
+import type {
+ ExternalFinding,
+ ExternalFindings,
+} from "../src/external-findings.js";
+import type { Provider } from "../src/external-import-models.js";
+import { normalizeSemgrepPlatformFindings } from "../src/semgrep-platform-findings.js";
+import { localFindingsFixture } from "./external-findings-local-helpers.js";
+
+const source = "https://github.com/example/project";
+const other = source + "-other";
+const projectedId = "checkmarx-one:" + "a".repeat(64);
+const viewer = "https://one.example/CxWebClient/ViewerMain.aspx?";
+type Report = ExternalFindings["report"];
+const conflictingScope = /same product, project and scan/i;
+const mismatchedRemote = /does not match a configured remote/i;
+
+async function selectionFixture(remote?: string) {
+ const fixture = await localFindingsFixture({ remote, isolatedGit: true });
+ // Every admitted selection in these tests must preserve every supplied row.
+ async function check(
+ findings: ExternalFinding[],
+ {
+ provider = "checkmarx",
+ report,
+ reader,
+ }: {
+ provider?: Provider;
+ report?: Report;
+ reader?: string;
+ } = {},
+ ) {
+ const { preview } = await prepareNormalizedLocalImport(
+ { findings, report, read: findings.length, excluded: [] },
+ {
+ provider,
+ repository: fixture.repository,
+ sourceKey: "example/project/main",
+ },
+ {
+ environment: fixture.environment,
+ sourceRepositories: reader ? [{ url: reader }] : [],
+ },
+ );
+ expect(preview.findings).toHaveLength(findings.length);
+ return preview;
+ }
+ return { ...fixture, check };
+}
+
+function sdk(
+ id: string,
+ evidence: Partial<ExternalFinding["evidence"]> = {},
+): ExternalFinding {
+ return {
+ source_finding_id: id,
+ evidence: { title: "SDK finding", severity: "low", ...evidence },
+ };
+}
+
+const one = (scanID: string, resultHash: string) =>
+ normalizeCheckmarxOne(
+ JSON.stringify({
+ scanID,
+ totalCount: 1,
+ results: [
+ {
+ type: "sast",
+ severity: "LOW",
+ similarityId: "7",
+ data: { resultHash, queryName: "Example_Query" },
+ },
+ ],
+ }),
+ source,
+ "local",
+ );
+
+function xml(projectId: string, scanId = "1", similarity = "7", names = "") {
+ return normalizeCheckmarxXml(
+ `<CxXMLResults ScanId="${scanId}" ProjectId="${projectId}" ${names}>
+ <Query id="3" name="Example_Query"><Result Severity="Low" FileName="src/read.ts" Line="3">
+ <Path SimilarityId="${similarity}"><PathNode><FileName>src/read.ts</FileName><Line>3</Line></PathNode></Path>
+ </Result></Query></CxXMLResults>`,
+ source,
+ "local",
+ );
+}
+
+test("native Checkmarx batches without report metadata belong to one scan", async () => {
+ await using selection = await selectionFixture(source);
+ for (const make of [one, (scan: string, id: string) => xml("1", scan, id)]) {
+ const first = make("1", "7").findings[0]!;
+ const second = make("2", "8").findings[0]!;
+ expect(first.source_finding_id).not.toBe(second.source_finding_id);
+ await expect(selection.check([first, second])).rejects.toThrow(
+ conflictingScope,
+ );
+ await selection.check([first, make("1", "8").findings[0]!]);
+ const later = make("2", "7").findings[0]!;
+ expect(later.source_finding_id).toBe(first.source_finding_id);
+ await selection.check([later]);
+ delete first.evidence.source_scan_id;
+ await expect(selection.check([first])).rejects.toThrow(/source scan ID/i);
+ }
+ await expect(
+ selection.check([...xml("1").findings, ...xml("2").findings]),
+ ).rejects.toThrow(conflictingScope);
+});
+
+test("SDK-only Checkmarx rows compare declared scan IDs, repositories and instances", async () => {
+ await using selection = await selectionFixture();
+ const row = (scan: string, url: string) =>
+ sdk(scan + url, {
+ source_scan_id: scan,
+ details: { kind: "sast", repository: { url } },
+ });
+ const first = row("1", source);
+ const partial = sdk("sdk-unspecified");
+ await expect(
+ selection.check([partial, first, row("2", source)]),
+ ).rejects.toThrow(conflictingScope);
+ await expect(
+ selection.check([partial, first, row("1", other)]),
+ ).rejects.toThrow(/repository/i);
+ await selection.check([partial, first, row("1", source + ".git")]);
+ await selection.check([first, row("2", other)], { provider: "wiz" });
+
+ const withInstance = (instance: unknown) =>
+ sdk(String(instance), {
+ ...first.evidence,
+ source_data: { projectId: "17", instance },
+ });
+ const deployment = withInstance("https://one.example/sast");
+ const second = withInstance("https://one.example/other");
+ const alternate = "https://ONE.EXAMPLE:443/sast";
+ const preview = await selection.check([deployment, withInstance(alternate)]);
+ expect(preview.findings[1]!.evidence.source_data?.["instance"]).toBe(
+ alternate,
+ );
+ await selection.check([
+ withInstance("https://one.example"),
+ withInstance("https://ONE.EXAMPLE:443/"),
+ ]);
+ await expect(selection.check([deployment, second])).rejects.toThrow(
+ /same instance/i,
+ );
+ await selection.check([
+ deployment,
+ withInstance(2),
+ withInstance("worker-17"),
+ withInstance(alternate),
+ ]);
+ await selection.check([deployment, second], { provider: "wiz" });
+ await selection.check(
+ ["alpha", "beta"].map((projectName) =>
+ sdk(projectName, { source_data: { projectName } }),
+ ),
+ );
+});
+
+test("a projected Checkmarx report under Wiz binds the configured Git fetch URL", async () => {
+ await using selection = await selectionFixture(source + "?other=target");
+ for (const format of [undefined, "custom-projection"]) {
+ const report = {
+ ...(format && { format }),
+ sourceRepositoryUrl: source,
+ scanId: "123",
+ };
+ await expect(
+ selection.check([sdk(projectedId)], { provider: "wiz", report }),
+ ).rejects.toThrow(mismatchedRemote);
+ }
+});
+
+test("a projected Checkmarx row under Wiz retains the report and original asset repositories", async () => {
+ await using selection = await selectionFixture(source);
+ const check = (rows: ExternalFinding[], url?: string) =>
+ selection.check(rows, {
+ provider: "wiz",
+ report: url
+ ? { format: "custom-projection", sourceRepositoryUrl: url }
+ : undefined,
+ });
+ const asset = (id: string, url: string) =>
+ sdk(id, {
+ source_data: {
+ vulnerableAsset: {
+ type: "REPOSITORY_BRANCH",
+ cloudProviderURL: url + "/tree/main",
+ },
+ },
+ });
+ const retained = (id: string, url: string) =>
+ sdk(id, { source_data: { sourceRepositoryUrl: url } });
+ const anchor = sdk(projectedId);
+ await expect(check([asset(projectedId, other)], source)).rejects.toThrow(
+ /does not match/,
+ );
+ await expect(check([asset(projectedId, other)])).rejects.toThrow(
+ mismatchedRemote,
+ );
+ await expect(
+ check([anchor, asset("wiz-row", other)], source),
+ ).rejects.toThrow(/does not match/);
+ await check([asset(projectedId, source)], source);
+ await check([asset("sdk-row", other)], other);
+ for (const id of ["wiz-row", "checkmarx-one:" + "b".repeat(64)]) {
+ await expect(check([anchor, retained(id, other)], source)).rejects.toThrow(
+ /does not match/,
+ );
+ await check([anchor, retained(id, source)], source);
+ }
+ await check([sdk("sdk-row"), retained("wiz-row", other)], source);
+});
+
+test("a projected Checkmarx report must match a hosted Semgrep project even with both Git remotes", async () => {
+ await using selection = await selectionFixture(source);
+ selection.git("remote", "add", "other", other);
+ const scan = normalizeSemgrepPlatformFindings({
+ format: "semgrep-platform-findings/v2",
+ deployment: "example",
+ project: { id: "1", name: "example/project", url: source },
+ ref: "refs/heads/main",
+ product: "sca",
+ repositoryAliases: [],
+ findingCount: 1,
+ findings: [JSON.stringify({ id: 9, rule_name: "example.rule" })],
+ });
+ const check = (sourceRepositoryUrl: string) =>
+ selection.check([...scan.findings, sdk(projectedId)], {
+ provider: "semgrep",
+ report: { sourceRepositoryUrl },
+ });
+ await expect(check(other)).rejects.toThrow(/Checkmarx report repository/);
+ await check(source);
+});
+
+test("selected native Checkmarx rows bind explicit SDK and reader claims without remotes", async () => {
+ await using selection = await selectionFixture();
+ const check = (
+ claim: Partial<ExternalFinding["evidence"]>,
+ reader?: string,
+ ) =>
+ selection.check([sdk("sdk-id", claim), ...xml("1").findings], { reader });
+ await check({}, source);
+ for (const claim of [
+ { source_scan_id: "2" },
+ { source_data: { projectId: "2" } },
+ {
+ details: { kind: "sast" as const, scanner_origin: "Checkmarx One SAST" },
+ },
+ { details: { kind: "sast" as const, repository: { url: other } } },
+ { source_data: { sourceRepositoryUrl: other } },
+ ]) {
+ await expect(check(claim)).rejects.toThrow(
+ /same product|retained Checkmarx report/i,
+ );
+ }
+ await expect(check({}, other)).rejects.toThrow(/retained Checkmarx report/i);
+ await check({ source_scan_id: "1", source_data: { projectId: "1" } });
+});
+
+function resultAttributes(finding: ExternalFinding) {
+ return finding.evidence.source_data!["result"] as Record<string, unknown>;
+}
+
+test("normalized CxSAST batches compare the known viewer instances, including linkless rows", async () => {
+ await using selection = await selectionFixture();
+ const first = xml("1", "1", "1");
+ const second = xml("1", "1", "2").findings[0]!;
+ const third = xml("1", "1", "3").findings[0]!;
+ resultAttributes(second)["DeepLink"] = viewer + "scanid=1";
+ resultAttributes(third)["DeepLink"] =
+ "https://two.example/CxWebClient/ViewerMain.aspx?scanid=1";
+ const batch = [...first.findings, second, third];
+ await expect(selection.check(batch)).rejects.toThrow(/same instance/i);
+ resultAttributes(third)["DeepLink"] = resultAttributes(second)["DeepLink"];
+ await selection.check(batch);
+ await expect(
+ selection.check(batch, {
+ report: { ...first.report, instance: "https://two.example" },
+ }),
+ ).rejects.toThrow(/same instance/i);
+
+ const projected = (query: string, pathId?: string) =>
+ sdk("projected", {
+ source_data: {
+ result: { DeepLink: viewer + query },
+ ...(pathId && { path: { PathId: pathId } }),
+ },
+ });
+ await expect(
+ selection.check([projected("scanid=2"), second]),
+ ).rejects.toThrow(conflictingScope);
+ await expect(
+ selection.check([second, projected("projectid=2")]),
+ ).rejects.toThrow(conflictingScope);
+ await expect(
+ selection.check([second, projected("pathid=2", "1")]),
+ ).rejects.toThrow(/DeepLink/);
+ await selection.check([second, projected("scanid=1&projectid=1")]);
+});
+
+test("recognized native rows retain their occurrence IDs and require the Checkmarx provider", async () => {
+ await using selection = await selectionFixture(source);
+ for (const input of [one("scan-a", "abc"), xml("1")]) {
+ const { findings, report } = input;
+ const row = findings[0]!;
+ const originalId = row.source_finding_id;
+ const originalScanner = row.evidence.details!.scanner_origin;
+ const data = row.evidence.source_data!;
+ const asWiz = (report?: Report) =>
+ selection.check(findings, { provider: "wiz", report });
+ await selection.check(findings, { report });
+ await expect(asWiz(report)).rejects.toThrow(/checkmarx provider/i);
+ delete data["format"];
+ await selection.check(findings, { report });
+ for (const format of [null, "other-format"]) {
+ data["format"] = format;
+ await expect(selection.check(findings, { report })).rejects.toThrow(
+ /retained report/i,
+ );
+ }
+ delete data["format"];
+ await expect(asWiz()).rejects.toThrow(/checkmarx provider/i);
+ row.source_finding_id = "sdk-key";
+ await expect(asWiz()).rejects.toThrow(/checkmarx provider/i);
+ await expect(selection.check(findings)).rejects.toThrow(
+ /source finding ID/i,
+ );
+ await expect(selection.check(findings, { report })).rejects.toThrow(
+ /source finding ID/i,
+ );
+ delete data["sourceRepositoryUrl"];
+ await expect(asWiz()).rejects.toThrow(/checkmarx provider/i);
+ await expect(selection.check(findings)).rejects.toThrow(
+ /source finding ID/i,
+ );
+ delete row.evidence.details!.scanner_origin;
+ await expect(selection.check(findings)).rejects.toThrow(
+ /source finding ID/i,
+ );
+ await asWiz();
+
+ // A projection without the native payload still has to honor explicit URLs.
+ row.source_finding_id = originalId;
+ row.evidence.source_data = { sourceRepositoryUrl: other };
+ await expect(asWiz()).rejects.toThrow(/retained scanner repository/i);
+ row.source_finding_id = "sdk-projection";
+ row.evidence.details!.scanner_origin = originalScanner;
+ delete row.evidence.details!.repository;
+ await expect(asWiz()).rejects.toThrow(mismatchedRemote);
+ row.evidence.source_data = { sourceRepositoryUrl: source };
+ await asWiz();
+ delete row.evidence.source_data;
+ await asWiz();
+ }
+});
+
+test("Checkmarx rows must match the report scan, format, project and repository", async () => {
+ await using selection = await selectionFixture(source);
+ for (const input of [one("scan-a", "abc"), xml("1")]) {
+ const { findings, report } = input;
+ await expect(
+ selection.check(findings, { report: { sourceRepositoryUrl: other } }),
+ ).rejects.toThrow(/retained Checkmarx report/i);
+ for (const change of [
+ { scanId: "another-scan" },
+ { sourceRepositoryUrl: other },
+ {
+ format:
+ report!["format"] === "cxsast-xml"
+ ? "checkmarx-one-json"
+ : "cxsast-xml",
+ projectId: "1",
+ },
+ ]) {
+ await expect(
+ selection.check(findings, { report: { ...report, ...change } }),
+ ).rejects.toThrow(
+ /retained Checkmarx report|does not match the retained report/i,
+ );
+ }
+ findings[0]!.evidence.details!.repository!.url = other;
+ await expect(selection.check(findings, { report })).rejects.toThrow(
+ /retained scanner repository/i,
+ );
+ }
+ const typed = [sdk("sdk-id")];
+ await selection.check(typed);
+ const oneReport = one("scan-a", "abc").report;
+ await expect(selection.check(typed, { report: oneReport })).rejects.toThrow(
+ /retained report/i,
+ );
+ await expect(
+ selection.check([], {
+ report: { ...oneReport, totalCount: 0, sourceRepositoryUrl: other },
+ }),
+ ).rejects.toThrow(mismatchedRemote);
+
+ const native = xml("1");
+ await expect(
+ selection.check(native.findings, {
+ report: { ...native.report, projectId: "2" },
+ }),
+ ).rejects.toThrow(/retained report/i);
+ resultAttributes(native.findings[0]!)["DeepLink"] =
+ viewer + "scanid=2&projectid=1";
+ await expect(selection.check(native.findings)).rejects.toThrow(/scan/i);
+ const viewerOnly = sdk("sdk-viewer", {
+ source_data: {
+ sourceRepositoryUrl: other,
+ result: { DeepLink: viewer + "scanid=1&projectid=1" },
+ },
+ });
+ await expect(
+ selection.check([viewerOnly], { provider: "wiz" }),
+ ).rejects.toThrow(mismatchedRemote);
+});
+
+test("Checkmarx One scan UUIDs compare by value and retain their original spellings", async () => {
+ await using selection = await selectionFixture(source);
+ const id = "e074e307-135b-4185-9b4d-d249dcf70559";
+ const upper = id.toUpperCase();
+ const first = one(id, "7");
+ const second = one(upper, "8");
+ const row = (scan: string) => sdk(scan, { source_scan_id: scan });
+ const preview = await selection.check(
+ [...first.findings, ...second.findings],
+ {
+ report: second.report,
+ },
+ );
+ expect(preview.report!["scanId"]).toBe(upper);
+ expect(
+ preview.findings.map(({ evidence }) => evidence.source_scan_id),
+ ).toEqual([id, upper]);
+ await selection.check([row(upper), ...first.findings]);
+ await selection.check([row(id), row(upper)]);
+ await expect(
+ selection.check([row("scan-key"), row("SCAN-KEY")]),
+ ).rejects.toThrow(conflictingScope);
+ await expect(
+ selection.check([row(upper), ...xml("1", id).findings]),
+ ).rejects.toThrow(conflictingScope);
+});
+
+test("linkless CxSAST selections compare named project and team claims", async () => {
+ await using selection = await selectionFixture(source);
+ const first = xml(
+ "3",
+ "10",
+ "1",
+ 'ProjectName="Project" TeamFullPathOnReportDate="/CxServer\\BuildÉ/"',
+ );
+ const second = (project: string, team: string) =>
+ xml(
+ "3",
+ "10",
+ "2",
+ `ProjectName="${project}" TeamFullPathOnReportDate="${team}"`,
+ ).findings;
+ for (const report of [undefined, first.report]) {
+ for (const rows of [
+ second("project", "cxserver/buildÉ"),
+ second("Project", "cxserver/buildé"),
+ ]) {
+ await expect(
+ selection.check([...first.findings, ...rows], { report }),
+ ).rejects.toThrow(/same product|retained report/i);
+ }
+ const team = "CXSERVER/BUILDÉ\\";
+ const preview = await selection.check(
+ [...first.findings, ...second("Project", team)],
+ { report },
+ );
+ expect(
+ preview.findings[1]!.evidence.source_data?.["teamFullPathOnReportDate"],
+ ).toBe(team);
+ await selection.check(
+ [...first.findings, ...xml("3", "10", "2").findings],
+ {
+ report,
+ },
+ );
+ }
+});
diff --git a/sdk/typescript/tests-ts/checkmarx-xml.test.ts b/sdk/typescript/tests-ts/checkmarx-xml.test.ts
new file mode 100644
index 000000000..8f7666a16
--- /dev/null
+++ b/sdk/typescript/tests-ts/checkmarx-xml.test.ts
@@ -0,0 +1,253 @@
+import { expect, test } from "bun:test";
+import {
+ checkmarxXmlId,
+ checkmarxXmlScope,
+ normalizeCheckmarxXml,
+} from "../src/checkmarx-xml.js";
+
+const repository = "https://github.com/example/sample";
+const normalize = (xml: string) =>
+ normalizeCheckmarxXml(xml, repository, "local");
+const linkAttribute = (url?: string) =>
+ url ? ` DeepLink="${url.replaceAll("&", "&amp;")}"` : "";
+const node = (file: string, line: number, name: string) =>
+ `<PathNode><FileName>${file}</FileName><Line>${line}</Line><Column>2</Column>
+ <Name>${name}</Name><Type>Reference</Type><NodeId>1</NodeId>
+ <Snippet><Line><Number>${line}</Number><Code><![CDATA[work(a < b);]]></Code></Line></Snippet>
+ </PathNode>`;
+const result = (middleLine: number, url?: string) =>
+ `<Result${linkAttribute(url)} FileName="src/input.ts" Line="5" Column="2" Severity="Medium" Status="Recurrent" FalsePositive="True" state="1" NodeId="1001">
+ <Path ResultId="100" PathId="1" SimilarityId="-17">
+ ${node("src/input.ts", 5, "input")}
+ ${node("src/query.ts", middleLine, "build")}
+ ${node("src/db.ts", 22, "execute")}
+ </Path>
+ </Result>`;
+const report = (results: string, url?: string) =>
+ `<CxXMLResults${linkAttribute(url)} ScanId="100" ProjectId="8" Owner="report owner">
+ <Query id="12" name="SQL_Injection" cweId="89" Severity="High">${results}</Query>
+ </CxXMLResults>`;
+
+test("retains native triage and ordered flow with snippets for each CxSAST result", () => {
+ const output = normalize(report(result(13)));
+ expect(output.read).toBe(1);
+ expect(output.excluded).toEqual([]);
+ const { evidence } = output.findings[0]!;
+ expect(evidence).toMatchObject({
+ title: "SQL_Injection",
+ source_scan_id: "100",
+ severity: "medium",
+ locations: [],
+ details: {
+ repository: { url: repository },
+ source_status: "Recurrent",
+ scanner_verdict: "False positive",
+ weakness_ids: ["CWE-89"],
+ },
+ source_data: {
+ projectId: "8",
+ query: { id: "12" },
+ result: { NodeId: "1001", FalsePositive: "True", state: "1" },
+ path: { SimilarityId: "-17" },
+ nodes: [
+ { FileName: "src/input.ts", Line: "5" },
+ {
+ FileName: "src/query.ts",
+ Line: "13",
+ Snippet: [{ Number: "13", Code: "work(a < b);" }],
+ },
+ { FileName: "src/db.ts", Line: "22" },
+ ],
+ },
+ });
+ expect(JSON.stringify(evidence)).not.toContain("report owner");
+});
+
+test("retains optional CxSAST project and team names without changing occurrence IDs", () => {
+ const xml = report(result(13));
+ const original = normalize(xml);
+ const row = original.findings[0]!;
+ const names = {
+ projectName: "Source & API",
+ teamFullPathOnReportDate: "CxServer\\SP\\Café",
+ };
+ for (const field of Object.keys(names)) {
+ expect(original.report).not.toHaveProperty(field);
+ expect(row.evidence.source_data).not.toHaveProperty(field);
+ }
+ const scoped = normalize(
+ xml.replace(
+ "<CxXMLResults ",
+ '<CxXMLResults ProjectName="Source &amp; API" TeamFullPathOnReportDate="CxServer\\SP\\Café" ',
+ ),
+ );
+ expect(scoped.report).toEqual({ ...original.report, ...names });
+ expect(scoped.findings[0]!.evidence.source_data).toEqual({
+ ...row.evidence.source_data,
+ ...names,
+ });
+ expect(scoped.findings[0]!.source_finding_id).toBe(row.source_finding_id);
+});
+
+test("checks explicit scan, project and path IDs in native viewer links", () => {
+ const viewer = "https://sast.example/CxWebClient/ViewerMain.aspx";
+ const scanLink = viewer + "?projectid=8&scanid=100";
+ const matching = scanLink + "&pathid=1";
+ const rows = [
+ matching,
+ viewer + "?scanid=101",
+ viewer + "?projectid=9",
+ viewer + "?pathid=2",
+ ].map((link) => result(13, link));
+ const output = normalize(report(rows.join(""), scanLink));
+ expect(output.findings).toHaveLength(1);
+ expect(output.findings[0]!.evidence.source_data).toMatchObject({
+ result: { DeepLink: matching },
+ });
+ expect(output.excluded).toMatchObject([
+ { position: 2, reason: expect.stringContaining("DeepLink") },
+ { position: 3, reason: expect.stringContaining("DeepLink") },
+ { position: 4, reason: expect.stringContaining("DeepLink") },
+ ]);
+ const noPathId = result(13, matching).replace('PathId="1"', "");
+ expect(normalize(report(noPathId)).excluded).toEqual([]);
+ expect(checkmarxXmlScope({ result: { DeepLink: matching } })).toEqual({
+ instance: "https://sast.example",
+ scanId: "100",
+ projectId: "8",
+ });
+ for (const field of ["scanid", "projectid", "pathid"]) {
+ const DeepLink = viewer + `?${field}=1&${field.toUpperCase()}=2`;
+ expect(() => checkmarxXmlScope({ result: { DeepLink } })).toThrow(
+ /DeepLink/u,
+ );
+ }
+ const unrelated = "https://sast.example/issue?scanid=101";
+ expect(normalize(report(result(13, unrelated))).excluded).toEqual([]);
+ expect(() => normalize(report("", viewer + "?scanid=101"))).toThrow(
+ /DeepLink/u,
+ );
+});
+
+test("requires all known CxSAST viewer instances to agree", () => {
+ const instance = "https://sast.example/tenant";
+ const viewer = instance + "/CxWebClient/ViewerMain.aspx";
+ const linked = result(13, viewer + "?pathid=1");
+ const unlinked = result(15);
+ for (const xml of [
+ report(unlinked, viewer),
+ report(linked + unlinked),
+ report(unlinked + linked),
+ ]) {
+ const parsed = normalize(xml);
+ expect(parsed.excluded).toEqual([]);
+ expect(parsed.report?.["instance"]).toBe(instance);
+ for (const { evidence } of parsed.findings)
+ expect(evidence.source_data?.["instance"]).toBe(instance);
+ }
+ for (const other of [
+ viewer.replace("sast.example", "other.example"),
+ viewer.replace("/tenant/", "/other/"),
+ ]) {
+ expect(() => normalize(report(linked, other))).toThrow(/same instance/u);
+ expect(() =>
+ normalize(report(linked + unlinked + result(19, other))),
+ ).toThrow(/same instance/u);
+ }
+});
+
+test("compares retained CxSAST instance URLs without rewriting the evidence", () => {
+ const viewer = "https://sast.example/Team/CxWebClient/ViewerMain.aspx";
+ const row = normalize(report(result(13, viewer))).findings[0]!;
+ const instance = "https://SAST.EXAMPLE:443/Team";
+ const retained = { ...row.evidence.source_data, instance };
+ expect(checkmarxXmlScope(retained).instance).toBe(instance);
+ expect(checkmarxXmlId(retained)).toBe(row.source_finding_id);
+ for (const different of [
+ "https://sast.example/team",
+ "https://sast.example/Team/other",
+ "https://sast.example:8443/Team",
+ ]) {
+ expect(() =>
+ checkmarxXmlScope({ ...retained, instance: different }),
+ ).toThrow(/same instance/u);
+ }
+});
+
+test("excluded results cannot select the instance of a linkless report", () => {
+ const unlinked = result(15);
+ const viewer = "https://other.example/CxWebClient/ViewerMain.aspx";
+ const wrongScan = result(17, viewer + "?scanid=999");
+ const duplicate = result(19, viewer + "?scanid=100");
+ const parsed = normalize(
+ report(wrongScan + duplicate + unlinked + duplicate),
+ );
+ expect(parsed.excluded.map((item) => item.position)).toEqual([1, 2, 4]);
+ expect(parsed.findings).toHaveLength(1);
+ expect(parsed.report).not.toHaveProperty("instance");
+ expect(parsed.findings[0]!.evidence.source_data).not.toHaveProperty(
+ "instance",
+ );
+});
+
+test("retains distinct intermediate paths and replays their identity across scans", () => {
+ const first = result(13);
+ const other = result(19);
+ const original = normalize(report(first + other));
+ expect(original.excluded).toEqual([]);
+ const ids = original.findings.map((finding) => finding.source_finding_id);
+ expect(new Set(ids).size).toBe(2);
+ const changed = report(other + first)
+ .replaceAll('="100"', '="200"')
+ .replaceAll('PathId="1"', 'PathId="42"')
+ .replaceAll('NodeId="1001"', 'NodeId="2001"')
+ .replaceAll('Severity="Medium"', 'Severity="Low"');
+ expect(
+ normalize(changed).findings.map((finding) => finding.source_finding_id),
+ ).toEqual(ids.toReversed());
+ const overlap = normalize(report(first + other + first + "<Result/>"));
+ expect(overlap.read).toBe(4);
+ expect(overlap.findings.map((finding) => finding.source_finding_id)).toEqual([
+ ids[1]!,
+ ]);
+ expect(overlap.excluded).toMatchObject([
+ { position: 1, source_finding_id: ids[0] },
+ { position: 3, source_finding_id: ids[0] },
+ { position: 4, source_finding_id: null },
+ ]);
+});
+
+test("retains project-wide results and paths without nodes", () => {
+ const projectWide =
+ '<Result FileName="" Line="1"><Path SimilarityId="17"><PathNode><FileName/><Line>1</Line><Column>0</Column></PathNode></Path></Result>';
+ const emptyPath =
+ '<Result FileName="src/app.ts" Line="7"><Path SimilarityId="-3"/></Result>';
+ const output = normalize(report(projectWide + emptyPath));
+ expect(output.excluded).toEqual([]);
+ expect(output.findings.map(({ evidence }) => evidence.locations)).toEqual([
+ [],
+ [],
+ ]);
+ expect(output.findings[1]?.evidence.source_data).toMatchObject({
+ result: { FileName: "src/app.ts", Line: "7" },
+ nodes: [],
+ });
+});
+
+test("handles empty reports and rejects other XML and truncated reports", () => {
+ expect(normalize('<CxXMLResults ScanId="100" ProjectId="8"/>')).toMatchObject(
+ {
+ read: 0,
+ findings: [],
+ excluded: [],
+ report: { scanId: "100", projectId: "8" },
+ },
+ );
+ for (const input of [
+ "<Other/>",
+ "<CxXMLResults/>",
+ report(`<Results>${result(13)}</Results>`),
+ report(result(13)).slice(0, -1),
+ ])
+ expect(() => normalize(input)).toThrow();
+});
diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.ts
index 38f179b68..b073b691b 100644
--- a/sdk/typescript/tests-ts/external-findings-publish.test.ts
+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts
@@ -4035,6 +4035,63 @@ async function inspectorPublicationFixture(name = inspectorRepositoryUrl) {
return { f, input, project, map, prepare, loseResponse };
}
+test("Checkmarx publishes a native SAST finding only to its declared Cloud repository", async () => {
+ const row = {
+ type: "sast",
+ similarityId: "17",
+ severity: "MEDIUM",
+ data: { resultHash: "c97c", queryName: "Example_Query" },
+ };
+ const f = await fixture({ scanID: "scan-a", totalCount: 1, results: [row] });
+ const selected = {
+ ...options,
+ provider: "checkmarx" as const,
+ sourceRepositoryUrl: f.state.repositoryUrl,
+ };
+ const prepare = () => prepareExternalPublication(f.file, selected, f.deps);
+ const first = await prepare();
+ expect(first.preview.requests[0]).toMatchObject({
+ source: { provider: "checkmarx", source_key: selected.sourceKey },
+ items: [{ evidence: { source_scan_id: "scan-a", source_data: { row } } }],
+ });
+ const sibling = sdkRow("sdk-id");
+ sibling.evidence.source_scan_id = "scan-b";
+ await expect(
+ prepareNormalizedExternalPublication(
+ sdkSelection([...first.preview.findings, sibling]),
+ selected,
+ f.deps,
+ ),
+ ).rejects.toThrow(/same product, project and scan/i);
+ const replayWithReport = (change: Record<string, unknown>) =>
+ prepareNormalizedExternalPublication(
+ { ...first.preview, report: { ...first.preview.report, ...change } },
+ selected,
+ f.deps,
+ );
+ await expect(
+ replayWithReport({
+ sourceRepositoryUrl: "https://github.com/example/other",
+ }),
+ ).rejects.toThrow(/does not match the selected Cloud repository/i);
+ f.state.repositoryUrl = "https://github.com/example/other";
+ await expect(prepare()).rejects.toThrow(/does not match/i);
+ expect(f.posts).toHaveLength(0);
+ f.state.repositoryUrl = selected.sourceRepositoryUrl;
+ await f.loseResponse(first);
+ await expect(replayWithReport({ scanId: "different-scan" })).rejects.toThrow(
+ /does not match the retained report/i,
+ );
+ f.state.repositoryUrl = "https://github.com/example/other";
+ await expect(prepare()).rejects.toThrow(/does not match/i);
+ expect(f.posts).toHaveLength(1);
+ f.state.repositoryUrl = selected.sourceRepositoryUrl;
+ const replay = await prepare();
+ expect(replay.preview.resumed).toBe(true);
+ expect((await replay.publish()).verified).toBe(1);
+ expect(f.posts[1]).toBe(f.posts[0]!);
+});
+
test("Continuum Cloud publication checks repository and provider and replays an interrupted request", async () => {
const detail = continuumDetail();
const f = await fixture(detail, continuumRepository);
@@ -4277,7 +4334,60 @@ const savedDependabotData = {
sourceRepositoryUrl: "https://github.com/example/different",
};
+const checkmarxFormat = { format: "cxsast-xml" };
+const exampleRepository = "https://github.com/example/project";
+const otherRepository = "https://github.com/example/other";
+const savedEndorData = (repositoryUri: string) => ({
+ ...checkmarxFormat,
+ runContext: { versionControlProvenance: ["opaque", { repositoryUri }] },
+});
+const endorCheckpoint = {
+ requiredProvider: "checkmarx",
+ selected: { ...options, provider: "endor" as const },
+};
+
+const wizBranchAsset = {
+ nativeType: "github#repositoryBranch",
+ cloudProviderURL: exampleRepository + "/tree/main",
+};
+
test.each([
+ {
+ data: { ...checkmarxFormat, vulnerableAsset: wizBranchAsset },
+ selected: options,
+ requiredProvider: "checkmarx",
+ filename:
+ "44c97129ef37ba88ccf7d6a1c43c3ef4c051080c0e746145b1f37dc6216f0181.pending.json",
+ digest: "7c90e7bf4a7d9c64c7cbbc15fdcdf6a3ff0e14f50cda77c9b523d834cf337dd7",
+ },
+ {
+ ...endorCheckpoint,
+ data: savedEndorData(exampleRepository),
+ filename:
+ "4d59df5533b5d0acbbcc2e28884e597a52d8b55e354eb15539d6cfba37c79011.pending.json",
+ digest: "d19b090ff4cd18329b37e74e674394deb2670c1d0dfc7bc088c02edcbb088cad",
+ },
+ {
+ ...endorCheckpoint,
+ data: {
+ ...savedEndorData(exampleRepository),
+ sourceRepositoryUrl: exampleRepository,
+ },
+ filename:
+ "624c404a8fcf0e8241c30d9b1a434d78aaa2c1e87d211465e0698821ab1c509f.pending.json",
+ digest: "f77bce9f03733812b5fda88ae988193b54462baf78be95ba6b4de49658b103d9",
+ },
+ {
+ ...endorCheckpoint,
+ data: {
+ ...savedEndorData(otherRepository),
+ sourceRepositoryUrl: exampleRepository,
+ },
+ conflictingUrl: otherRepository,
+ filename:
+ "70e7f4be8d0d9eb0306f18ea1a2b256641bee797b3626a8dfc2920d0a15abcd2.pending.json",
+ digest: "8fedf62999d4c5f510706db4647ad3d847e8e5f6f5f3d75eb365da193c16ea1a",
+ },
{
data: { format: "snyk-rest-issues/v2", issueJson: "{}" },
requiredProvider: "snyk",
@@ -4328,7 +4438,8 @@ test.each([
},
])(
"checks a saved $selected.provider request from before $requiredProvider checks",
- async ({ selected, data, requiredProvider, filename, digest }) => {
+ async (saved) => {
+ const { selected, data, requiredProvider, filename, digest } = saved;
const f = await fixture();
const environment: NodeJS.ProcessEnv = { ...f.environment };
// These persisted keys came from the default deployment.
@@ -4391,6 +4502,13 @@ test.each([
{ mode: 0o600 },
);
+ if ("conflictingUrl" in saved && saved.conflictingUrl) {
+ await expect(prepare()).rejects.toThrow(
+ `belongs to "${saved.conflictingUrl}"`,
+ );
+ expect(f.posts).toHaveLength(0);
+ return;
+ }
if (alert) {
// The original publisher selected the alert's repository. Changing the
// catalog to match the projection must not permit replay to another repo.
@@ -4402,6 +4520,13 @@ test.each([
expect(f.posts).toHaveLength(0);
return;
}
+ if (requiredProvider === "checkmarx") {
+ const original = f.state.repositoryUrl;
+ f.state.repositoryUrl += "-other";
+ await expect(prepare()).rejects.toThrow(`belongs to "${original}"`);
+ expect(f.posts).toHaveLength(0);
+ f.state.repositoryUrl = original;
+ }
if (selected.provider === "snyk") {
const other = "https://github.com/example/other";
await expect(prepare(other)).rejects.toThrow(/does not match/);
@@ -4454,6 +4579,94 @@ test.each(["wiz", "inspector"] as const)(
},
);
+const projectedId = "checkmarx-one:" + "a".repeat(64);
+
+function sdkRow(id: string, source_data?: Record<string, unknown>) {
+ const row = normalized(id);
+ return {
+ ...row,
+ evidence: validateExternalEvidence({ ...row.evidence, source_data }),
+ };
+}
+
+function sdkSelection(
+ findings: ExternalFindings["findings"],
+ report?: ExternalFindings["report"],
+): ExternalFindings {
+ return { read: findings.length, excluded: [], findings, report };
+}
+
+test.each(["row", "report", "Snyk SARIF"] as const)(
+ "keeps the projected Checkmarx repository from the %s across retries",
+ async (scope) => {
+ const f = await fixture();
+ const sourceRepositoryUrl = f.state.repositoryUrl;
+ const snyk = scope === "Snyk SARIF";
+ const selected = snyk ? { ...options, provider: "snyk" as const } : options;
+ const report = scope === "report" ? { sourceRepositoryUrl } : undefined;
+ const input = snyk
+ ? (await snykRepositoryEvidence("SARIF", sourceRepositoryUrl)).normalized
+ : sdkSelection(
+ [
+ sdkRow(
+ projectedId,
+ scope === "row" ? { sourceRepositoryUrl } : undefined,
+ ),
+ ],
+ report,
+ );
+ input.findings[0]!.source_finding_id = projectedId;
+ const prepare = (selection: ExternalFindings = input) =>
+ prepareNormalizedExternalPublication(selection, selected, f.deps);
+ f.state.repositoryUrl = otherRepository;
+ if (report)
+ expect(
+ (await prepare(sdkSelection([sdkRow("opaque-sdk-id")], report))).preview
+ .requests,
+ ).toHaveLength(1);
+ await expect(prepare()).rejects.toThrow(/belongs to|does not match/);
+ f.state.repositoryUrl = sourceRepositoryUrl;
+ await f.loseResponse(await prepare());
+ f.state.repositoryUrl = otherRepository;
+ await expect(prepare()).rejects.toThrow(/belongs to|does not match/);
+ expect(f.posts).toHaveLength(1);
+ f.state.repositoryUrl = sourceRepositoryUrl;
+ const retry = await prepare();
+ expect(retry.preview.resumed).toBe(true);
+ expect((await retry.publish()).verified).toBe(1);
+ expect(f.posts[1]).toBe(f.posts[0]);
+ },
+);
+
+test("Checkmarx projections under Wiz bind retained row URLs and native repository branch assets", async () => {
+ const f = await fixture();
+ const sourceRepositoryUrl = f.state.repositoryUrl;
+ f.state.repositoryUrl = otherRepository;
+ const report = { sourceRepositoryUrl: otherRepository };
+ const prepare = (
+ findings: ExternalFindings["findings"],
+ metadata?: typeof report,
+ ) =>
+ prepareNormalizedExternalPublication(
+ sdkSelection(findings, metadata),
+ options,
+ f.deps,
+ );
+ const branch = { vulnerableAsset: wizBranchAsset };
+ const mismatch = `belongs to "${sourceRepositoryUrl}"`;
+ const projected = sdkRow(projectedId, branch);
+ await expect(prepare([projected], report)).rejects.toThrow(mismatch);
+ await expect(prepare([projected])).rejects.toThrow(mismatch);
+ for (const data of [branch, { sourceRepositoryUrl }]) {
+ const sibling = sdkRow("wiz-finding", data);
+ expect((await prepare([sibling], report)).preview.requests).toHaveLength(1);
+ await expect(
+ prepare([sdkRow(projectedId), sibling], report),
+ ).rejects.toThrow(mismatch);
+ }
+ expect(f.posts).toHaveLength(0);
+});
+
test("Black Duck Cloud replay preserves package occurrence and rejects a different destination", async () => {
const row = {
...blackDuckBomRow(),
@@ -10484,6 +10697,142 @@ test.each([
},
);
+function privateInboxContext(context_version = "generation-a") {
+ return Response.json({
+ object: "security.finding_import_context",
+ context_version,
+ can_read: true,
+ can_upload: true,
+ can_create_import_jobs: true,
+ formats: ["security.findings.v1"],
+ limits: { max_direct_file_bytes: 32768, max_record_bytes: 8192 },
+ });
+}
+
+test.each([
+ {
+ data: checkmarxFormat,
+ report: { sourceRepositoryUrl: exampleRepository, scanId: "123" },
+ key: "0b6db48e67edf53d39403c9fd1897c34a179edf5b6cce9bffabc9f52f8757f33",
+ sha256: "8b0e177506af75c363184d3627fed74325acfcada7e3ee8e9d81041c5db5b2d1",
+ },
+ {
+ data: { vulnerableAsset: wizBranchAsset },
+ report: checkmarxFormat,
+ key: "7400c077334e75f2b1ca49f05eb5cc4f431b62a9f2063734f42a03d60500ea5e",
+ sha256: "bf944f1fec0d2f97675f35dc8db1bee753807879fa6077e2bd8c5169889ce7ae",
+ },
+ {
+ data: { sourceRepositoryUrl: exampleRepository },
+ report: checkmarxFormat,
+ key: "0c9c5eef708bb27f19dcaebb67832cc6dcd43bfbf9dee0f0d4c4d2da9145ffa8",
+ sha256: "2ae1422cd86875a7be2d73f2dc8f6833e494668f6e4be9982c403d336557ef9f",
+ },
+])(
+ "only a verified private Wiz checkpoint replays pre-Checkmarx evidence ($data)",
+ async ({ data, report, key, sha256 }) => {
+ const f = await fixture();
+ const selection = sdkSelection(
+ [sdkRow(normalized().source_finding_id, data)],
+ report,
+ );
+ const source = {
+ provider: options.provider,
+ source_key: options.sourceKey,
+ };
+ const repository = { id: options.repository, repo_connector_id: "github" };
+ const checkpoint = {
+ format: "security.findings.v1",
+ apiBaseUrl: "https://chatgpt.com/backend-api/aardvark",
+ accountId: "synthetic-account",
+ contextVersion: "generation-a",
+ source,
+ repository,
+ sha256,
+ uploadRequestId: "ff52f1ac-ee15-4126-a3f4-bc9984fa0c51",
+ jobRequestId: "a942a3d4-ad70-4b4d-aaca-4e1e2b70cb20",
+ fileId: "aifile_" + "a".repeat(32),
+ };
+ const directory = join(f.root, "state", "external-finding-publications");
+ const path = join(directory, key + ".private-import.json");
+ await mkdir(directory, { recursive: true, mode: 0o700 });
+ await writeFile(path, JSON.stringify(checkpoint), { mode: 0o600 });
+ let contextVersion = checkpoint.contextVersion;
+ const requests: unknown[] = [];
+ const prepare = () =>
+ prepareNormalizedExternalPublication(selection, options, {
+ environment: {
+ ...f.environment,
+ CODEX_SECURITY_CLOUD_BASE_URL: undefined,
+ CODEX_SECURITY_CLOUD_WEB_URL: undefined,
+ },
+ fetch: async (url, init) => {
+ const pathname = new URL(url).pathname;
+ if (pathname.endsWith("/repositories"))
+ return f.deps.fetch(url, init);
+ if (pathname.endsWith("/finding-imports/context"))
+ return privateInboxContext(contextVersion);
+ expect(pathname).toEndWith("/finding-imports/jobs");
+ expect(init.method).toBe("POST");
+ const job = JSON.parse(String(init.body));
+ requests.push(job);
+ return Response.json({
+ ...job,
+ object: "security.finding_import_job",
+ id: "import_" + "b".repeat(32),
+ status: "completed",
+ counts: {
+ total: 1,
+ discovered: 1,
+ created: 1,
+ updated: 0,
+ unchanged: 0,
+ error: 0,
+ unprocessed: 0,
+ },
+ poll_after_seconds: null,
+ error: null,
+ });
+ },
+ });
+ contextVersion = "different-inbox";
+ await expect(prepare()).rejects.toThrow("requires the checkmarx provider");
+ contextVersion = checkpoint.contextVersion;
+ f.state.repositoryUrl = otherRepository;
+ await expect(prepare()).rejects.toThrow(/belongs to|does not match/);
+ f.state.repositoryUrl = exampleRepository;
+ const resumed = await prepare();
+ expect(resumed.preview.resumed).toBe(true);
+ expect(resumed.preview.privateImport?.sha256).toBe(checkpoint.sha256);
+ expect((await resumed.publish()).counts.created).toBe(1);
+ expect(requests).toEqual([
+ {
+ request_id: checkpoint.jobRequestId,
+ context_version: checkpoint.contextVersion,
+ source,
+ input: {
+ type: "file",
+ file_id: checkpoint.fileId,
+ format: checkpoint.format,
+ },
+ default_targets: [
+ {
+ type: "repository",
+ repo_id: repository.id,
+ repo_connector_id: repository.repo_connector_id,
+ },
+ ],
+ },
+ ]);
+ await rm(path);
+ await expect(resumed.publish()).rejects.toThrow(
+ "requires the checkmarx provider",
+ );
+ await expect(prepare()).rejects.toThrow("requires the checkmarx provider");
+ expect(requests).toHaveLength(1);
+ },
+);
+
test("a private preview recognizes a later repository checkpoint under its historical filename", async () => {
const f = await fixture();
const privatePreview = await prepareNormalizedExternalPublication(
@@ -10500,15 +10849,7 @@ test("a private preview recognizes a later repository checkpoint under its histo
});
}
expect(new URL(url).pathname).toEndWith("/finding-imports/context");
- return Response.json({
- object: "security.finding_import_context",
- context_version: "generation-a",
- can_read: true,
- can_upload: true,
- can_create_import_jobs: true,
- formats: ["security.findings.v1"],
- limits: { max_direct_file_bytes: 32768, max_record_bytes: 8192 },
- });
+ return privateInboxContext();
},
},
);