OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
feat(imports): import CrowdStrike FCS IaC findings locally (#2589)
Carlos Matos4822a9cbc4c4
diff --git a/docs/scanner-imports/README.md b/docs/scanner-imports/README.mdindex 84b8c9f86..9a0e5c883 100644--- a/docs/scanner-imports/README.md+++ b/docs/scanner-imports/README.md@@ -22,25 +22,26 @@ The `--provider` value selects the reader for a saved report. To see whichreaders your installed CLI supports, run `codex-security publish findings --help`.The guides cover local and Cloud imports unless a row limits its scope.-| Guide | `--provider` | Supported input |-| ----------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------- |-| [Amazon Inspector](inspector.md) | `inspector` | Inspector2 `ListFindings` JSON for one Code Security repository |-| [ArmorCode](armorcode.md) | `armorcode` | Findings API JSON for one repository (local verified, Cloud unverified) |-| [AWS Continuum](continuum.md) | `continuum` | Code issues with linked evidence, or saved findings and patches |-| [Black Duck SCA](blackduck.md) | `blackduck` | BOM-6 vulnerable components for one project version |-| [Checkmarx SAST](checkmarx.md) | `checkmarx` | Checkmarx One CLI JSON or self-managed CxSAST XML for one scan |-| [Endor Labs](endor.md) | `endor` | Native Finding JSON, or self-contained `endorctl` SARIF with finding UUIDs |-| [GitHub code scanning](github-code-scanning.md) | `github` | Alerts selected for one repository and Git ref |-| [GitHub Dependabot](github-dependabot.md) | `github` | Dependency alerts exported from one repository |-| [GitHub Security Advisories](github-security-advisories.md) | `github` | Selected repository or global advisories |-| [OpenGrep](opengrep.md) | `opengrep` | Native scan JSON, optionally gzip-compressed |-| [Semgrep](semgrep.md) | `semgrep` | CLI/CI JSON, SARIF, selected Guardian findings, or Platform Web API reports |-| [Snyk](snyk.md) | `snyk` | CLI JSON, plugin exports, SARIF, or monitored Code and Open Source issues |-| [SonarQube Cloud](sonar.md) | `sonar` | Issues selected with the signed-in Sonar CLI, or saved issue-search pages |-| [Tenable One](tenable.md) | `tenable` | Selected Code Repository inventory findings (local only) |-| [Trivy](trivy.md) | `trivy` | Native schema-v2 repository or filesystem JSON, optionally gzip-compressed |-| [Veracode Static Analysis](veracode.md) | `veracode` | Findings API pages for one application's policy flaws |-| [Wiz](wiz.md) | `wiz` | Native JSON, normalized JSONL, or detailed repository package vulnerability CSV |+| Guide | `--provider` | Supported input |+| ----------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------- |+| [Amazon Inspector](inspector.md) | `inspector` | Inspector2 `ListFindings` JSON for one Code Security repository |+| [ArmorCode](armorcode.md) | `armorcode` | Findings API JSON for one repository (local verified, Cloud unverified) |+| [AWS Continuum](continuum.md) | `continuum` | Code issues with linked evidence, or saved findings and patches |+| [Black Duck SCA](blackduck.md) | `blackduck` | BOM-6 vulnerable components for one project version |+| [Checkmarx SAST](checkmarx.md) | `checkmarx` | Checkmarx One CLI JSON or self-managed CxSAST XML for one scan |+| [CrowdStrike](crowdstrike.md) | `crowdstrike` | FCS CLI 4.x IaC scan JSON (local only) |+| [Endor Labs](endor.md) | `endor` | Native Finding JSON, or self-contained `endorctl` SARIF with finding UUIDs |+| [GitHub code scanning](github-code-scanning.md) | `github` | Alerts selected for one repository and Git ref |+| [GitHub Dependabot](github-dependabot.md) | `github` | Dependency alerts exported from one repository |+| [GitHub Security Advisories](github-security-advisories.md) | `github` | Selected repository or global advisories |+| [OpenGrep](opengrep.md) | `opengrep` | Native scan JSON, optionally gzip-compressed |+| [Semgrep](semgrep.md) | `semgrep` | CLI/CI JSON, SARIF, selected Guardian findings, or Platform Web API reports |+| [Snyk](snyk.md) | `snyk` | CLI JSON, plugin exports, SARIF, or monitored Code and Open Source issues |+| [SonarQube Cloud](sonar.md) | `sonar` | Issues selected with the signed-in Sonar CLI, or saved issue-search pages |+| [Tenable One](tenable.md) | `tenable` | Selected Code Repository inventory findings (local only) |+| [Trivy](trivy.md) | `trivy` | Native schema-v2 repository or filesystem JSON, optionally gzip-compressed |+| [Veracode Static Analysis](veracode.md) | `veracode` | Findings API pages for one application's policy flaws |+| [Wiz](wiz.md) | `wiz` | Native JSON, normalized JSONL, or detailed repository package vulnerability CSV |## Preview a report@@ -76,7 +77,7 @@ from the preview for your destination](sonar.md#import-and-verify).**Save locally.** Remove `--dry-run` and confirm. In automation, use `--yes`after reviewing the preview.-**Send to Cloud.** Tenable One reports support local import only. For a Cloud-supported report, keep the file, provider,+**Send to Cloud.** Tenable One and CrowdStrike reports support local import only. For a Cloud-supported report, keep the file, provider,source key, and scanner options from your local preview. Change the destinationto `--to cloud`, and pass the connected repository URL or Cloud ID to`--repository`. Preview again with `--dry-run --format json`. [Cloud setup](../../sdk/typescript/docs/cli.md#preview-and-publish)diff --git a/docs/scanner-imports/crowdstrike.md b/docs/scanner-imports/crowdstrike.mdnew file mode 100644index 000000000..c2d2379f3--- /dev/null+++ b/docs/scanner-imports/crowdstrike.md@@ -0,0 +1,94 @@+# Import CrowdStrike findings locally++Use a saved JSON report from `fcs scan iac` in the CrowdStrike Falcon Cloud Security (FCS) CLI 4.x. The reader imports each detection in `rule_detections` as one misconfiguration or secret finding. It works offline and does not run the FCS CLI. Reports in the older `violations` format and image scan reports are not supported. CrowdStrike reports support local import only.++## Create the report++FCS writes each detection's `file` relative to the directory where the CLI runs, not relative to `--path`. Run the scan from the root of the directory you will import into, and write the report outside it. The output directory must exist, and its name must not contain a dot.++```sh+cd /path/to/project+reports=$(mktemp -d "${TMPDIR:-/tmp}/fcs-report-XXXXXX")+fcs scan iac --path . --report-formats json --output-path "$reports"+report=$(find "$reports" -name '*-scan-results.json')+```++FCS exits with a nonzero code when detections match `--fail-on`, which by default is any detection. The report is saved if the output shows `Results saved to file`. A scan of a subdirectory, such as `--path infra`, also gives correct paths when it runs from the root.++The [FCS GitHub Action](https://github.com/CrowdStrike/fcs-action) runs the CLI from the workspace root. When `path` is a directory in a checkout at the workspace root, its JSON report matches a checkout of the same commit. Set `report_formats: json` and an `output_path`, upload that directory as a workflow artifact, and download it outside your checkout.++### Scan a remote repository++A `git::` scan clones the default branch, and the report does not record the commit. FCS has no branch or commit option, but the URL accepts `?ref=` with a branch, tag or commit. Pin the scan to a commit and check out the same commit.++```sh+repository_url=https://github.com/example/project+checkout=/path/to/project+reports=$(mktemp -d "${TMPDIR:-/tmp}/fcs-report-XXXXXX")+commit=$(git ls-remote "$repository_url.git" HEAD | cut -f1)+fcs scan iac --path "git::$repository_url.git?ref=$commit" \+ --report-formats json --output-path "$reports"+report=$(find "$reports" -name '*-scan-results.json')+git clone --quiet "$repository_url.git" "$checkout"+git -C "$checkout" checkout --quiet --detach "$commit"+```++To scan another branch, replace `HEAD` with `refs/heads/BRANCH`. Paths start at the repository root. If the URL ends with a subdirectory, such as `.git//infra?ref=...`, paths start at that subdirectory. Use `"$checkout/infra"` as `--repository`. If the checkout is at a different commit, the import stops at the first file that changed.++A report of a `git::https://` URL names its repository. The import records that URL, without the subdirectory or `?ref=`, as the findings' repository. If you also pass `--source-repository-url`, both must name the same repository, or the import stops. If the scanned URL has a user name and token, FCS keeps them in the report's `flags.path`. The import does not store that field, but keep the report private.++## Preview, save and read back++The project does not need to be a Git checkout.++```sh+codex-security publish findings "$report" --provider crowdstrike --to local \+ --repository /path/to/project --source-key example/project/main \+ --dry-run --format json+```++Every detection's file must exist in `--repository` with the content that FCS scanned, which the report records as `file_sha256`. If a file is missing or changed, the import stops and names it, because the reported lines might no longer be correct. Select the directory and commit that FCS scanned, or scan again from its root. Different line endings also count as a change, for example in a Windows checkout of a report from a Linux CI runner.++Add `--source-repository-url https://github.com/example/project` to record the repository of a local scan. With a repository URL, findings get typed `iac` or `secret` details. If you pass the URL and `--repository` is a Git checkout, the URL must match one of its fetch remotes. Without a URL, each finding has a title, severity, description and location, and `evidence.source_data` keeps the native FCS rule and detection.++Remove `--dry-run` and confirm to save. Run `codex-security findings imported /path/to/project --format json` to read back the findings and their initial `not_assessed` Codex assessment. To check a finding against the code, see [Work with imported findings](README.md#work-with-imported-findings).++## Read the evidence++This shortened report has one detection. The reader keeps its file and line as the finding location.++```json+{+ "fcs_version": "4.3.0",+ "path": ".",+ "scan_uuid": "00000000-0000-4000-8000-000000000001",+ "rule_detections": [+ {+ "rule_name": "Sensitive Port Is Exposed To Entire Network",+ "rule_uuid": "00000000-0000-4000-8000-000000000002",+ "rule_category": "Networking and Firewall",+ "severity": "High",+ "platform": "Terraform",+ "detections": [+ {+ "file": "infra/main.tf",+ "line": 4,+ "resource_type": "aws_security_group",+ "resource_name": "example",+ "reason": "aws_security_group[example] 'SSH' (Port:22) is public",+ "recommendation": "aws_security_group[example] 'SSH' (Port:22) should not be public"+ }+ ]+ }+ ]+}+```++- With a repository URL, `details.kind` is `secret` for the Secret Management rule category and `iac` for all others. `details.configuration.actual` is the FCS `reason`, and `details.configuration.expected` is its `recommendation`. FCS names the attribute that holds a secret, not its value.+- A detection in a local Terraform module points to the module file. FCS also reports a copy at the module call, and both are imported.+- A detection in a registry or Git module names the calling file. Its location is the call line from `module_remediation`, or no line if FCS does not state one.+- `evidence.source_data` keeps the FCS version, the native rule without its detection list, and the one detection. For a `git::` scan, it also keeps the scanned URL without `?ref=`. A saved preview imports only if each finding's location matches its retained detection.++## Repeat an import++FCS has no stable detection ID. The reader identifies a detection by rule UUID, file, line, resource type and name, reason and module path. Keep the same source key for one project and branch. When a later scan reports a detection on a different line, it is imported as a new finding, and the earlier finding stays stored.diff --git a/docs/scanner-imports/schema-guide.md b/docs/scanner-imports/schema-guide.mdindex 27ac58574..058f156e2 100644--- a/docs/scanner-imports/schema-guide.md+++ b/docs/scanner-imports/schema-guide.md@@ -28,6 +28,7 @@ which changes can give an occurrence a different ID.| [AWS Continuum](continuum.md) | Issue ARN for issue exports. For finding exports, a list summary and a detailed response share the finding ARN. || [Tenable One](tenable.md) | Exact Tenable `finding_id` within the local checkout and a stable tenant/asset source key. Use the Code Repository asset UUID in the key. || [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. |+| [CrowdStrike](crowdstrike.md) | FCS IaC rule UUID, file, line, resource type and name, reason and module path. A detection on a new line gets a new ID. || [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/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.mdindex 191bfad04..b8e01d13d 100644--- a/plugins/codex-security/skills/publish-findings/SKILL.md+++ b/plugins/codex-security/skills/publish-findings/SKILL.md@@ -26,6 +26,7 @@ For a fresh scan, look for the relevant executable in the environment where it w| Checkmarx | Export a completed Checkmarx One scan as CLI JSON or self-managed CxSAST as XML. Follow the [collector instructions](references/checkmarx-import.md) for the selected product, scan, and verified owning project. || Wiz | Use the connected Wiz tools or API to retrieve the selected repository findings by occurrence ID, or use a detailed report. JSON covers multiple finding families. Detailed CSV covers repository package vulnerabilities. [Wiz input profiles](references/wiz-import.md) || AWS Continuum patches | Run `codex-security import continuum ENVIRONMENT_ID --finding-id FINDING_ID --source-root CHECKOUT --repository-name AWS_SOURCE_NAME --format json` for one finding. Use an absolute checkout path and the exact AWS source name. Omit `--repository-name` when the environment has exactly one Git repository and no S3 sources. The CLI verifies that with `GetEnvironment` before collecting the finding. Publish the JSON with `--provider continuum` and the verified `--source-repository-url`. [Continuum guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/continuum.md#collect-a-finding-with-patches) |+| CrowdStrike FCS | Use a saved FCS CLI 4.x `fcs scan iac` JSON report, such as a CI artifact from the [FCS GitHub Action](https://github.com/CrowdStrike/fcs-action). For a fresh scan, run the installed `fcs` CLI from the directory to import into: `fcs scan iac --path . --report-formats json --output-path DIR`, where `DIR` is an existing private directory outside it whose name has no dot. For a remote `git::` URL, add `?ref=COMMIT` and import into a checkout of that commit, or into its subdirectory for a `//subdir` suffix. A nonzero exit can mean that detections matched `--fail-on` or that the scan failed; import only the `*-scan-results.json` file named in `Results saved to file`. If `fcs` is not on `PATH`, do not install it or pass Falcon credentials in arguments; ask for a saved report. Import with `--to local` only. The directory does not need to be a Git checkout, but each detection's file must have the content that FCS scanned. Add `--source-repository-url` only for a verified URL. A `git::https://` report already names its repository, and a different URL stops the import. [CrowdStrike guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/crowdstrike.md) || Other built-in readers | OpenGrep accepts native scan JSON including scanner errors. Endor uses `endorctl` Finding JSON with complete records. Inspector uses Inspector2 ListFindings for one Code Security repository. Black Duck uses BOM-6 vulnerable components for one project version. Veracode uses paginated STATIC policy findings for one application. Tenable uses a selected Code Repository inventory capture and verified HTTPS clone URL. [Provider guides and identity rules](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md#choose-your-scanner) |### SonarQube Cloud issuesdiff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex 1ef1a2915..b8d9e1eed 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -1584,6 +1584,8 @@ on stderr to verify that every finding belongs to the repository you specify.For Tenable One Code Repository findings, use `--provider tenable --to local` and set `--source-repository-url` to the checkout’s verified HTTPS remote. [Tenable export and import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/tenable.md)+For CrowdStrike FCS CLI 4.x IaC reports, use `--provider crowdstrike --to local` and select the directory where FCS ran with `--repository`. It does not need to be a Git checkout, but each scanned file must be unchanged since the scan. Add `--source-repository-url` to record the repository; it must match a fetch remote when the directory is a Git checkout. A `git::https://` report names its repository, and a different `--source-repository-url` stops the import. [CrowdStrike import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/crowdstrike.md)+Local readback uses `findings imported [PATH]`. The path defaults to the currentdirectory. Each imported record starts as `not_assessed`. Unknown revisions andlocations stay unknown. Repository-scoped sources are checked against comparablediff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjsindex 3a1f0da7e..e38a31b9d 100644--- a/sdk/typescript/scripts/package-dist-files.mjs+++ b/sdk/typescript/scripts/package-dist-files.mjs@@ -75,6 +75,7 @@ const distModules = ["wiz-csv","veracode-findings","tenable-findings",+ "crowdstrike-findings","wiz-findings","codex-prompt","codex-sdk-environment",diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex a3c76d108..a565ea75c 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -4146,7 +4146,7 @@ export async function main(provider: z.enum(EXTERNAL_FINDINGS_READERS).describe(- "Select the file reader for this report. OpenGrep findings use the semgrep storage provider. Tenable requires --to local and --source-repository-url.",+ "Select the file reader for this report. OpenGrep findings use the semgrep storage provider. Tenable requires --to local and --source-repository-url. CrowdStrike requires --to local.",),sourceRepositoryUrl: optionValue("--source-repository-url").optional()diff --git a/sdk/typescript/src/crowdstrike-findings.ts b/sdk/typescript/src/crowdstrike-findings.tsnew file mode 100644index 000000000..cc27e541c--- /dev/null+++ b/sdk/typescript/src/crowdstrike-findings.ts@@ -0,0 +1,308 @@+import { createHash } from "node:crypto";+import { readFile, stat } from "node:fs/promises";+import { join } from "node:path";+import { CodexSecurityError } from "./errors.js";+import type {+ ExternalFindings,+ ExternalSourceRepository,+} from "./external-findings.js";+import {+ repositoryUrlKey,+ validateExternalEvidence,+} from "./external-import-contract.js";+import { isGitHubCloudHost } from "./git-remote.js";+import {+ array,+ normalizeRecords,+ readScannerJson,+ record,+ repositoryFilePath,+ requiredText,+ scannerSeverity,+ stableId,+ text,+} from "./scanner-import.js";+import {+ declaredScannerRepositoryUrl,+ validScannerRepositoryUrl,+} from "./scanner-repository-url.js";++export const crowdstrikeReportFormat = "crowdstrike-fcs-iac/v1";++type NativeRecord = Record<string, unknown>;++interface Entry {+ rule: NativeRecord;+ detection: NativeRecord;+}++function joined(...values: (string | null)[]): string | null {+ return values.filter((value) => value !== null).join("\n\n") || null;+}++function positive(value: unknown): number | null {+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0+ ? value+ : null;+}++// A git:: scan path without its ?ref= query. When the scanned URL has a user+// name, FCS writes each detection path after this prefix.+function gitScan(path: unknown): string | undefined {+ const value = text(path);+ return value?.startsWith("git::") ? value.split("?", 1)[0] : undefined;+}++// The repository of an HTTPS git:: scan, without its //subdirectory. Checkouts+// fetch over HTTPS or SSH, which do not match an http:// URL.+function gitScanRepository(scan: string): string | undefined {+ const source = scan.slice("git::".length);+ const scheme = /^https:\/\//iu.exec(source)?.[0];+ if (!scheme) return undefined;+ const subdirectory = source.indexOf("//", scheme.length);+ const url = subdirectory === -1 ? source : source.slice(0, subdirectory);+ return validScannerRepositoryUrl(url, "local") ? url : undefined;+}++// FCS writes paths relative to its working directory. A git:: scan writes them+// from the scan root, after a slash or after the scan path.+function detectionPath(detection: NativeRecord, scan: string | undefined) {+ const raw = text(detection["file"]);+ const relative =+ scan === undefined || !raw+ ? raw+ : raw.startsWith(`${scan}/`)+ ? raw.slice(scan.length + 1)+ : raw.replace(/^\//u, "");+ const path = repositoryFilePath(relative);+ if (!path)+ throw new CodexSecurityError(+ "CrowdStrike detection file must be checkout-relative. Run the FCS CLI from the checkout root.",+ );+ return path;+}++// A detection in a registry or Git module names the calling file, but its line+// is inside the module. FCS states the call line only in module_remediation.+// FCS writes the file, module source and calling file in one form, so compare them as written.+function detectionLine(detection: NativeRecord): number | null {+ const line = positive(detection["line"]);+ const file = text(detection["file"]);+ const source = text(detection["module_source"]);+ if (+ detection["is_from_module"] !== true ||+ !file ||+ !source ||+ file.startsWith(`${source}/`)+ )+ return line;+ // Search for this file's exact phrase; the remediation text comes from the report.+ const remediation = text(detection["module_remediation"]) ?? "";+ const marker = `called by ${file} at line `;+ const start = remediation.indexOf(marker);+ const call =+ start === -1+ ? null+ : /^\d+\b/u.exec(remediation.slice(start + marker.length));+ return call ? positive(Number(call[0])) : null;+}++/** Check repository claims, and that each finding's file is the scanned version in the selected checkout. */+export async function crowdstrikeCheckout(+ input: ExternalFindings,+ declared: string | undefined,+ references: readonly ExternalSourceRepository[],+ repository: string,+): Promise<ExternalSourceRepository | undefined> {+ if (input.report?.["format"] !== crowdstrikeReportFormat)+ throw new CodexSecurityError(+ "CrowdStrike imports require a report from the crowdstrike reader.",+ );+ // Only a declared URL binds the checkout to its fetch remotes. A git:: report's+ // own repository is recorded and must agree with it.+ const declarations: unknown[] = [+ declared,+ input.report["repositoryUrl"],+ ...references.map(({ url }) => url),+ ];+ const reportScan = gitScan(input.report["git_scan"]);+ const claims = [...declarations, reportScan && gitScanRepository(reportScan)];+ const files = new Map<string, Set<unknown>>();+ for (const { evidence } of input.findings) {+ validateExternalEvidence(evidence, "local");+ const data = evidence.source_data;+ if (data?.["format"] !== crowdstrikeReportFormat)+ throw new CodexSecurityError(+ "CrowdStrike findings must retain their native detection.",+ );+ const scan = gitScan(data["git_scan"]);+ claims.push(+ data["repository_url"],+ evidence.details?.repository?.url,+ scan && gitScanRepository(scan),+ );+ // Check the retained detection's file, and that the shown location is the same.+ const detection = record(data["detection"], "CrowdStrike detection");+ const file = detectionPath(detection, scan);+ const [location, ...others] = evidence.locations ?? [];+ if (+ !location ||+ others.length > 0 ||+ location.path !== file ||+ (location.line ?? null) !== detectionLine(detection)+ )+ throw new CodexSecurityError(+ "CrowdStrike finding locations must match the native detection file and line.",+ );+ files.set(+ file,+ (files.get(file) ?? new Set()).add(detection["file_sha256"]),+ );+ }+ const urls = claims+ .filter((claim) => claim != null)+ .map((claim) =>+ declaredScannerRepositoryUrl(claim, "CrowdStrike", "local"),+ );+ if (new Set(urls.map((url) => repositoryUrlKey(url))).size > 1)+ throw new CodexSecurityError(+ "CrowdStrike findings name a different repository than --source-repository-url.",+ );+ // Paths are relative to where FCS ran, so a missing file means a different root or checkout.+ // FCS follows file symlinks and records each file's SHA-256; another version gives stale lines.+ for (const [file, hashes] of files) {+ const path = join(repository, ...file.split("/"));+ if (!(await stat(path).catch(() => null))?.isFile())+ throw new CodexSecurityError(+ `${JSON.stringify(file)} is not in ${JSON.stringify(repository)}. Select the checkout that FCS scanned, and run the FCS CLI from its root.`,+ );+ const hash = createHash("sha256")+ .update(await readFile(path))+ .digest("hex");+ if ([...hashes].some((expected) => expected !== hash))+ throw new CodexSecurityError(+ `${JSON.stringify(file)} changed after the FCS scan. Select a checkout of the scanned commit, or scan again.`,+ );+ }+ const url = urls[0];+ if (url === undefined || declarations.every((claim) => claim == null))+ return undefined;+ const { hostname } = new URL(url);+ return {+ url,+ platform: isGitHubCloudHost(hostname)+ ? "github"+ : hostname === "gitlab.com"+ ? "gitlab"+ : undefined,+ };+}++/** Read a saved FCS CLI 4.x IaC JSON report. */+export async function readCrowdStrikeFindings(+ path: string,+ sourceRepositoryUrl?: string,+): Promise<ExternalFindings> {+ const document = record(await readScannerJson(path), "CrowdStrike report");+ if (!Array.isArray(document["rule_detections"]))+ throw new CodexSecurityError(+ "Expected an FCS CLI 4.x IaC JSON report with rule_detections.",+ );+ const version = text(document["fcs_version"]);+ const scan = gitScan(document["path"]);+ const declared =+ sourceRepositoryUrl === undefined+ ? undefined+ : declaredScannerRepositoryUrl(+ sourceRepositoryUrl,+ "CrowdStrike",+ "local",+ );+ // A git:: report names the repository that FCS cloned.+ const repositoryUrl = declared ?? (scan && gitScanRepository(scan));+ const entries: Entry[] = array(+ document["rule_detections"],+ "CrowdStrike rule_detections",+ ).flatMap((value) => {+ const { detections, ...rule } = record(value, "CrowdStrike rule");+ return array(detections ?? [], "CrowdStrike detections").map(+ (detection) => ({+ rule,+ detection: record(detection, "CrowdStrike detection"),+ }),+ );+ });+ return normalizeRecords(+ entries,+ ({ rule, detection }) => {+ const kind =+ rule["rule_category"] === "Secret Management" ? "secret" : "iac";+ const reason = text(detection["reason"]);+ const recommendation = text(detection["recommendation"]);+ const file = detectionPath(detection, scan);+ return validateExternalEvidence(+ {+ title: requiredText(rule["rule_name"], "CrowdStrike rule_name"),+ severity: scannerSeverity(text(rule["severity"])?.toLowerCase()),+ description: joined(text(rule["description"]), reason),+ locations: [{ path: file, line: detectionLine(detection) }],+ source_scan_id: text(document["scan_uuid"]),+ // Typed IaC and secret details must name their source repository.+ details: repositoryUrl && {+ kind,+ repository: { url: repositoryUrl },+ rule: {+ id: text(rule["rule_uuid"]),+ name: text(rule["rule_name"]),+ },+ configuration:+ kind === "iac"+ ? {+ platform: text(rule["platform"]),+ cloud_platform: text(rule["cloud_provider"]),+ expected: recommendation,+ actual: reason,+ }+ : null,+ remediation_instructions: joined(+ recommendation,+ text(detection["module_remediation"]),+ ),+ scanner_origin: version+ ? `CrowdStrike FCS CLI ${version}`+ : "CrowdStrike FCS CLI",+ },+ source_data: structuredClone({+ format: crowdstrikeReportFormat,+ fcs_version: version,+ ...(repositoryUrl && { repository_url: repositoryUrl }),+ ...(scan !== undefined && { git_scan: scan }),+ rule,+ detection,+ }),+ },+ "local",+ );+ },+ ({ rule, detection }) =>+ stableId("crowdstrike", [+ requiredText(rule["rule_uuid"], "CrowdStrike rule_uuid"),+ detectionPath(detection, scan),+ positive(detection["line"]),+ detection["resource_type"] ?? null,+ detection["resource_name"] ?? null,+ detection["reason"] ?? null,+ detection["module_path"] ?? null,+ ]),+ "local",+ {+ report: {+ format: crowdstrikeReportFormat,+ ...(declared && { repositoryUrl: declared }),+ ...(scan !== undefined && { git_scan: scan }),+ fcs_version: version,+ scan_uuid: text(document["scan_uuid"]),+ },+ },+ );+}diff --git a/sdk/typescript/src/external-findings-local.ts b/sdk/typescript/src/external-findings-local.tsindex 429be2886..a6acb51aa 100644--- a/sdk/typescript/src/external-findings-local.ts+++ b/sdk/typescript/src/external-findings-local.ts@@ -51,11 +51,16 @@ import {EXTERNAL_FINDINGS_READERS,localFindingRepositories,semgrepSarifRepositories,+ LOCAL_ONLY_PROVIDERS,} from "./external-findings-read.js";import {tenableReportFormat,tenableSourceRepository,} from "./tenable-findings.js";+import {+ crowdstrikeCheckout,+ crowdstrikeReportFormat,+} from "./crowdstrike-findings.js";import {guardianFindingRepository,guardianSelectionFormat,@@ -955,7 +960,11 @@ export function distinctSourceRepositories(export async function prepareLocalImport(input: ExternalFindings & Partial<SnykIssuesFindings>,options: NormalizedLocalImportOptions &- ({ provider: "tenable" } | { provider: Provider }),+ (+ | { provider: "tenable" }+ | { provider: "crowdstrike" }+ | { provider: Provider }+ ),dependencies: LocalExternalImportDependencies,readerSources = distinctSourceRepositories(snapshotSourceRepositories(dependencies.sourceRepositories),@@ -981,16 +990,20 @@ export async function prepareLocalImport("local",options.provider,);- if (- options.provider !== "tenable" &&- (current.report?.["format"] === tenableReportFormat ||- current.findings.some(- (row) => row.evidence?.source_data?.["format"] === tenableReportFormat,- ))- )- throw new CodexSecurityError(- "Retained Tenable evidence requires the tenable provider.",- );+ for (const [provider, format] of [+ ["tenable", tenableReportFormat],+ ["crowdstrike", crowdstrikeReportFormat],+ ] as const)+ if (+ options.provider !== provider &&+ (current.report?.["format"] === format ||+ current.findings.some(+ (row) => row.evidence?.source_data?.["format"] === format,+ ))+ )+ throw new CodexSecurityError(+ `Retained ${LOCAL_ONLY_PROVIDERS[provider]} evidence requires the ${provider} provider.`,+ );checkTrivyReportProvider(options.provider, current.report);let dependabotSource: string | undefined;validateFindingIds(current);@@ -1014,12 +1027,11 @@ export async function prepareLocalImport(dependabotSource = native;}const context = await localContext(options.repository, dependencies);- if (options.provider === "tenable") {- const source = tenableSourceRepository(- current,- options.sourceRepositoryUrl,- [...readerSources, ...parsedSources],- );+ // Neither report records the checkout, so check the operator's URL against its remotes.+ const requireFetchRemote = async (+ source: ExternalSourceRepository,+ provider: keyof typeof LOCAL_ONLY_PROVIDERS,+ ) => {const remotes = await hostedCheckoutRemotes(context.repository,context.options.protectedRoot,@@ -1028,12 +1040,41 @@ export async function prepareLocalImport();if (!remotes?.some((remote) => hostedRepositoryMatches(source, remote)))throw new CodexSecurityError(- "Tenable's source repository must match a configured Git fetch remote of the selected checkout.",+ `${LOCAL_ONLY_PROVIDERS[provider]}'s source repository must match a configured Git fetch remote of the selected checkout.`,);+ };+ if (options.provider === "tenable") {+ const source = tenableSourceRepository(+ current,+ options.sourceRepositoryUrl,+ [...readerSources, ...parsedSources],+ );+ await requireFetchRemote(source, "tenable");return preparedLocalStorage(current, options, context, dependencies, true, {sourceRepositories: [source],});}+ if (options.provider === "crowdstrike") {+ const source = await crowdstrikeCheckout(+ current,+ options.sourceRepositoryUrl,+ [...readerSources, ...parsedSources],+ context.repository,+ );+ // FCS scans plain directories; only a Git checkout has remotes to compare.+ const bound =+ source !== undefined &&+ (await hasGitMetadata(context.repository, dependencies.signal));+ if (bound) await requireFetchRemote(source, "crowdstrike");+ return preparedLocalStorage(+ current,+ options,+ context,+ dependencies,+ bound,+ source ? { sourceRepositories: [source] } : {},+ );+ }const { repository, options: workbenchOptions } = context;const sources = new Map<string, ExternalSourceRepository>();const references = [...readerSources, ...parsedSources];diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.tsindex 3dc9a619c..5ae91b602 100644--- a/sdk/typescript/src/external-findings-publish.ts+++ b/sdk/typescript/src/external-findings-publish.ts@@ -22,6 +22,7 @@ import type { LocalExternalImportOptions } from "./external-findings-import.js";import { armorCodeRepositoryUrl } from "./armorcode-findings.js";import { declaredScannerRepositoryUrl } from "./scanner-repository-url.js";import { tenableReportFormat } from "./tenable-findings.js";+import { crowdstrikeReportFormat } from "./crowdstrike-findings.js";import {guardianFindingId,guardianFindingRepository,@@ -593,6 +594,8 @@ function checkFindingProvider(function checkFormat(format: unknown) {if (format === tenableReportFormat)requireCloudReader({ provider: "tenable" });+ if (format === crowdstrikeReportFormat)+ requireCloudReader({ provider: "crowdstrike" });if (format === guardianSelectionFormat && provider !== "semgrep")throw new CodexSecurityError("Use the semgrep provider for Guardian findings.",diff --git a/sdk/typescript/src/external-findings-read.ts b/sdk/typescript/src/external-findings-read.tsindex 351a85810..a76c91301 100644--- a/sdk/typescript/src/external-findings-read.ts+++ b/sdk/typescript/src/external-findings-read.ts@@ -7,6 +7,7 @@ import { readScannerJson, sarifRunRepositories } from "./scanner-import.js";import type { Provider } from "./external-import-models.js";import { CodexSecurityError } from "./errors.js";import { readTenableFindings } from "./tenable-findings.js";+import { readCrowdStrikeFindings } from "./crowdstrike-findings.js";import type { ExternalImportTarget } from "./external-import-contract.js";import { dependabotRepository } from "./github-dependabot-findings.js";import {@@ -37,7 +38,14 @@ import { isRecord } from "./record.js";import { readWizSelection, wizFindingRepository } from "./wiz-findings.js";import { normalizeArmorCodeFindings } from "./armorcode-findings.js";-export type LocalFindingProvider = Provider | "tenable";+/** Readers whose findings Cloud does not accept, with their display names. */+export const LOCAL_ONLY_PROVIDERS = {+ tenable: "Tenable",+ crowdstrike: "CrowdStrike",+} as const;+type LocalOnlyProvider = keyof typeof LOCAL_ONLY_PROVIDERS;++export type LocalFindingProvider = Provider | LocalOnlyProvider;/** File reader names mapped to the provider stored with each finding. */export const EXTERNAL_FINDINGS_PROVIDERS = {@@ -57,19 +65,23 @@ export const EXTERNAL_FINDINGS_PROVIDERS = {continuum: "continuum",checkmarx: "checkmarx",tenable: "tenable",+ crowdstrike: "crowdstrike",} as const satisfies Record<string, LocalFindingProvider>;export type ExternalFindingsReader = keyof typeof EXTERNAL_FINDINGS_PROVIDERS;-export type CloudFindingsReader = Exclude<ExternalFindingsReader, "tenable">;+export type CloudFindingsReader = Exclude<+ ExternalFindingsReader,+ LocalOnlyProvider+>;export function requireCloudReader(options: ExternalFindingsReaderOptions,): asserts options is ExternalFindingsReaderOptions & {provider: CloudFindingsReader;} {- if (options.provider === "tenable")+ if (Object.hasOwn(LOCAL_ONLY_PROVIDERS, options.provider))throw new CodexSecurityError(- "Tenable findings require a local import (--to local).",+ `${LOCAL_ONLY_PROVIDERS[options.provider as LocalOnlyProvider]} findings require a local import (--to local).`,);}@@ -187,6 +199,15 @@ export async function readExternalFindings(if (target === "cloud") requireCloudReader(options);return { findings: await readTenableFindings(path, url) };}+ if (provider === "crowdstrike") {+ if (target === "cloud") requireCloudReader(options);+ return {+ findings: await readCrowdStrikeFindings(+ path,+ options.sourceRepositoryUrl,+ ),+ };+ }if (provider === "sonar") {const findings = await readSonarFindings(path, url, target);const binding = findings.report?.["repositoryUrl"];diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsindex 7ac3143b9..589dcb678 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -365,6 +365,7 @@ export {type StoredFindingsPublicationGroup,} from "./stored-findings-publication.js";export { readTenableFindings } from "./tenable-findings.js";+export { readCrowdStrikeFindings } from "./crowdstrike-findings.js";export {normalizeOpenGrepFindings,readOpenGrepFindings,diff --git a/sdk/typescript/tests-ts/crowdstrike-import.test.ts b/sdk/typescript/tests-ts/crowdstrike-import.test.tsnew file mode 100644index 000000000..cca80b9b9--- /dev/null+++ b/sdk/typescript/tests-ts/crowdstrike-import.test.ts@@ -0,0 +1,562 @@+import { expect, mock, test } from "bun:test";+import { main } from "../src/cli.js";+import { readCrowdStrikeFindings } from "../src/crowdstrike-findings.js";+import {+ type NormalizedExternalPublicationOptions,+ prepareExternalPublication,+ prepareNormalizedExternalPublication,+} from "../src/external-findings-publish.js";+import { prepareNormalizedLocalImport } from "../src/external-findings-local.js";+import { dependencies as cliDependencies } from "./cli-fixtures.js";+import {+ createAndReplayFinding,+ localReportFixture,+ updateStoredFinding,+} from "./external-findings-local-helpers.js";+import { createCliTest } from "./support/cli-run.js";+import { createHash } from "node:crypto";+import { mkdir, rm, symlink, writeFile } from "node:fs/promises";+import { join } from "node:path";++const repositoryUrl = "https://github.com/example/repo";+// The checkout fixture writes empty files, as FCS scanned them.+const emptyFile = createHash("sha256").update("").digest("hex");+const detection = {+ file: "infra/net/main.tf",+ file_sha256: emptyFile,+ line: 7,+ resource_type: "aws_security_group",+ resource_name: "example",+ issue_type: "IncorrectValue",+ reason: "aws_security_group[example] 'SSH' (Port:22) is public",+ recommendation:+ "aws_security_group[example] 'SSH' (Port:22) should not be public",+};+const misconfiguration = {+ rule_name: "Example Sensitive Port Is Exposed",+ rule_uuid: "10000000-0000-4000-8000-000000000001",+ rule_category: "Networking and Firewall",+ description: "Example rule description",+ severity: "High",+ platform: "Terraform",+ cloud_provider: "AWS",+ service: "EC2",+ rule_type: "Example",+ detections: [detection],+};+const secret = {+ rule_name: "Passwords And Secrets - Example Access Key",+ rule_uuid: "20000000-0000-4000-8000-000000000002",+ rule_category: "Secret Management",+ description: "Example secret description",+ severity: "Critical",+ platform: "Generic",+ cloud_provider: "common",+ service: "common",+ rule_type: "Example",+ detections: [+ {+ file: "infra/provider.tf",+ file_sha256: emptyFile,+ line: 3,+ resource_type: null,+ resource_name: null,+ issue_type: "RedundantAttribute",+ reason: "Hardcoded secret key appears in source",+ recommendation: "Hardcoded secret key should not appear in source",+ },+ ],+};+const report = {+ fcs_version: "4.2.3",+ path: ".",+ project_name: "",+ scan_type: "Local",+ scan_uuid: "30000000-0000-4000-8000-000000000003",+ scan_performed_at: "2026-11-10T12:00:00Z",+ rule_detections: [misconfiguration, secret],+ detection_summary: {},+ stats: {},+};+const source = {+ provider: "crowdstrike",+ sourceKey: "example/crowdstrike/repo",+ sourceRepositoryUrl: repositoryUrl,+} as const;++// The scanned files exist in the checkout, as they do after a scan from its root.+async function checkout() {+ const fixture = await localReportFixture("fcs-iac.json", source, {+ remote: repositoryUrl + ".git",+ });+ await mkdir(join(fixture.repository, "infra", "net"), { recursive: true });+ for (const file of ["infra/net/main.tf", "infra/provider.tf"])+ await writeFile(join(fixture.repository, ...file.split("/")), "");+ return fixture;+}++test("the reader maps misconfigurations and secrets to typed IaC evidence", async () => {+ await using fixture = await checkout();+ await fixture.writeJson(report);+ const { findings, excluded } = await readCrowdStrikeFindings(+ fixture.file,+ repositoryUrl,+ );+ expect(excluded).toEqual([]);+ expect(findings).toHaveLength(2);+ const { detections: _, ...rule } = misconfiguration;+ expect(findings[0]!.evidence).toMatchObject({+ title: misconfiguration.rule_name,+ severity: "high",+ description: `${misconfiguration.description}\n\n${detection.reason}`,+ locations: [{ path: "infra/net/main.tf", line: 7 }],+ source_scan_id: report.scan_uuid,+ details: {+ kind: "iac",+ repository: { url: repositoryUrl },+ rule: {+ id: misconfiguration.rule_uuid,+ name: misconfiguration.rule_name,+ },+ configuration: {+ platform: "Terraform",+ cloud_platform: "AWS",+ expected: detection.recommendation,+ actual: detection.reason,+ },+ remediation_instructions: detection.recommendation,+ scanner_origin: "CrowdStrike FCS CLI 4.2.3",+ },+ source_data: { repository_url: repositoryUrl, rule, detection },+ });+ expect(findings[1]!.evidence).toMatchObject({+ severity: "critical",+ locations: [{ path: "infra/provider.tf", line: 3 }],+ details: { kind: "secret", configuration: null },+ });+ expect(findings[0]!.source_finding_id).toMatch(/^crowdstrike:[a-f0-9]{64}$/u);+});++test("detections that differ only by line remain separate findings", async () => {+ await using fixture = await checkout();+ const [first] = secret.detections;+ await fixture.writeJson({+ ...report,+ rule_detections: [+ { ...secret, detections: [first, { ...first, line: 7 }] },+ ],+ });+ const { findings, excluded } = await readCrowdStrikeFindings(+ fixture.file,+ repositoryUrl,+ );+ expect(excluded).toEqual([]);+ expect(findings.map(({ evidence }) => evidence.locations)).toEqual([+ [{ path: "infra/provider.tf", line: 3 }],+ [{ path: "infra/provider.tf", line: 7 }],+ ]);+});++const revision = "0123456789abcdef0123456789abcdef01234567";+const scanned = "git::https://github.com/example/repo.git//infra";+// FCS writes git:: files, module sources and call sites from the scan root after+// a slash. For a URL with a user name, it writes them after the scanned path,+// and only `flags.path` keeps the user name and token.+test.each([+ ["a slash", `${scanned}?ref=${revision}`, ""],+ [+ "the scanned path",+ `git::https://example:[email protected]/example/repo.git//infra?ref=${revision}`,+ scanned,+ ],+])(+ "git:: reports after %s keep module lines and record the scanned repository",+ async (_, given, root) => {+ await using fixture = await checkout();+ const call = `called by ${root}/main.tf at line 8.`;+ await fixture.writeJson({+ ...report,+ path: `${scanned}?ref=${revision}`,+ flags: { path: given },+ rule_detections: [+ {+ ...misconfiguration,+ detections: [+ {+ ...detection,+ file: `${root}/modules/example/main.tf`,+ line: 12,+ module_path: "example",+ module_source: `${root}/modules/example`,+ is_from_module: true,+ module_remediation: `This finding originates in module "${root}/modules/example", ${call}`,+ },+ {+ ...detection,+ file: `${root}/main.tf`,+ line: 1,+ module_path: "registry",+ module_source: "example/sg/aws",+ is_from_module: true,+ module_remediation: `This finding originates in module "example/sg/aws", ${call}`,+ },+ ],+ },+ ],+ });+ const result = await readCrowdStrikeFindings(fixture.file);+ expect(result.excluded).toEqual([]);+ expect(result.findings.map(({ evidence }) => evidence.locations)).toEqual([+ [{ path: "modules/example/main.tf", line: 12 }],+ [{ path: "main.tf", line: 8 }],+ ]);+ const repository = "https://github.com/example/repo.git";+ expect(result.report).toMatchObject({ git_scan: scanned });+ expect(result.report).not.toHaveProperty("repositoryUrl");+ expect(result.findings[0]!.evidence).toMatchObject({+ details: { kind: "iac", repository: { url: repository } },+ source_data: { repository_url: repository, git_scan: scanned },+ });+ expect(JSON.stringify(result)).not.toContain("synthetic-token");+ },+);++test.each([+ "git::ssh://[email protected]/example/repo.git",+ "git::http://github.com/example/repo.git",+])("a %s report imports without a scanned repository", async (path) => {+ await using fixture = await checkout();+ await fixture.writeJson({+ ...report,+ path,+ rule_detections: [+ {+ ...misconfiguration,+ detections: [{ ...detection, file: "/infra/net/main.tf" }],+ },+ ],+ });+ const { findings, report: read } = await readCrowdStrikeFindings(+ fixture.file,+ );+ expect(findings[0]!.evidence.locations).toEqual([+ { path: "infra/net/main.tf", line: 7 },+ ]);+ expect(findings[0]!.evidence.details).toBeUndefined();+ expect(read).not.toHaveProperty("repositoryUrl");+});++test("a git:: report's repository must agree with a declared URL", async () => {+ await using fixture = await checkout();+ const scan = (repository: string) =>+ fixture.writeJson({+ ...report,+ path: `git::https://github.com/example/${repository}.git`,+ rule_detections: [+ {+ ...misconfiguration,+ detections: [{ ...detection, file: "/infra/net/main.tf" }],+ },+ ],+ });+ await scan("repo");+ await fixture.prepare();+ await scan("upstream");+ await expect(fixture.prepare()).rejects.toThrow(/different repository/u);+ await fixture.writeJson({+ ...report,+ path: "git::https://github.com/example/upstream.git",+ rule_detections: [],+ });+ await expect(fixture.prepare()).rejects.toThrow(/different repository/u);+ await scan("upstream");+ // Without a declared URL, the scanned repository is recorded but does not bind the checkout.+ const { preview } = await fixture.prepare({ sourceRepositoryUrl: undefined });+ expect(preview.excluded).toEqual([]);+ expect(preview.findings[0]!.evidence.details?.repository?.url).toBe(+ "https://github.com/example/upstream.git",+ );+ await expect(fixture.prepareNormalized(preview)).rejects.toThrow(+ /different repository/u,+ );+ const replay = (input: typeof preview) =>+ prepareNormalizedLocalImport(+ input,+ {+ provider: "crowdstrike",+ sourceKey: source.sourceKey,+ repository: fixture.repository,+ },+ { environment: fixture.environment },+ );+ await replay(preview);+ const relabeled = structuredClone(preview);+ relabeled.findings[0]!.evidence.source_data!["git_scan"] =+ "git::https://github.com/example/repo.git";+ await expect(replay(relabeled)).rejects.toThrow(/different repository/u);+ await writeFile(join(fixture.repository, "infra", "net", "main.tf"), "\n");+ await expect(replay(preview)).rejects.toThrow(/changed after the FCS scan/u);+});++test("registry module detections use the call line that FCS reports for the module", async () => {+ await using fixture = await checkout();+ const call = (line: number) =>+ `This finding originates in module "example/sg/aws" (version 1.0.0), called by main.tf at line ${line}. To remediate, update the module.`;+ const registry = {+ ...detection,+ file: "main.tf",+ line: 1,+ module_path: "first_sg",+ module_source: "example/sg/aws",+ module_version: "1.0.0",+ is_from_module: true,+ module_remediation: call(5),+ };+ await fixture.writeJson({+ ...report,+ rule_detections: [+ {+ ...misconfiguration,+ detections: [+ registry,+ {+ ...registry,+ module_path: "second_sg",+ module_remediation: call(9),+ },+ {+ ...registry,+ module_path: "third_sg",+ module_remediation: "Update it.",+ },+ {+ ...detection,+ file: "modules/sg/main.tf",+ module_path: "local_sg",+ module_source: "modules/sg",+ is_from_module: true,+ module_remediation: call(1),+ },+ ],+ },+ ],+ });+ const { findings, excluded } = await readCrowdStrikeFindings(+ fixture.file,+ repositoryUrl,+ );+ expect(excluded).toEqual([]);+ expect(findings.map(({ evidence }) => evidence.locations)).toEqual([+ [{ path: "main.tf", line: 5 }],+ [{ path: "main.tf", line: 9 }],+ [{ path: "main.tf", line: null }],+ [{ path: "modules/sg/main.tf", line: 7 }],+ ]);+ expect(findings[0]!.evidence.details?.remediation_instructions).toBe(+ `${detection.recommendation}\n\n${call(5)}`,+ );+});++test("the reader rejects legacy reports and excludes paths outside the checkout", async () => {+ await using fixture = await checkout();+ await fixture.writeJson({ fcs_version: "1.0.0", violations: [] });+ await expect(+ readCrowdStrikeFindings(fixture.file, repositoryUrl),+ ).rejects.toThrow(/FCS CLI 4\.x IaC JSON report/u);+ await fixture.writeJson({+ ...report,+ rule_detections: [+ {+ ...misconfiguration,+ detections: [+ { ...detection, file: "/tmp/checkout/main.tf" },+ { ...detection, file: "../other/main.tf" },+ { ...detection, file: "C:\\checkout\\main.tf" },+ ],+ },+ ],+ });+ const { findings, excluded } = await readCrowdStrikeFindings(+ fixture.file,+ repositoryUrl,+ );+ expect(findings).toEqual([]);+ expect(excluded.map(({ reason }) => reason)).toEqual(+ Array(3).fill(expect.stringContaining("checkout root")),+ );+});++const single = { ...report, rule_detections: [misconfiguration] };++test("the CLI preview can be saved, replayed and updated with its original identity", async () => {+ await using fixture = await checkout();+ await fixture.writeJson(single);+ const cli = createCliTest(main);+ const code = await cli.runCli(+ [+ "publish",+ "findings",+ fixture.file,+ "--provider=crowdstrike",+ "--to=local",+ `--repository=${fixture.repository}`,+ `--source-repository-url=${repositoryUrl}`,+ `--source-key=${source.sourceKey}`,+ "--dry-run",+ "--format=json",+ ],+ cliDependencies({ environment: fixture.environment }),+ );+ expect(code, cli.stderr.text() || cli.stdout.text()).toBe(0);+ const preview = JSON.parse(cli.stdout.text());+ expect(preview.source).toEqual({+ provider: "crowdstrike",+ source_key: source.sourceKey,+ });+ const saved = await createAndReplayFinding(fixture, preview);+ expect(saved.provider).toBe("crowdstrike");+ expect(saved.evidence.locations).toEqual([+ { path: "infra/net/main.tf", line: 7 },+ ]);+ await fixture.writeJson({+ ...single,+ rule_detections: [{ ...misconfiguration, severity: "Medium" }],+ });+ expect((await updateStoredFinding(fixture, saved)).evidence.severity).toBe(+ "medium",+ );+});++test("a plain directory imports without Git or a repository URL", async () => {+ await using fixture = await checkout();+ await fixture.writeJson(single);+ await rm(join(fixture.repository, ".git"), { recursive: true });+ const { preview } = await fixture.prepare({ sourceRepositoryUrl: undefined });+ expect(preview.excluded).toEqual([]);+ const { evidence } = preview.findings[0]!;+ expect(evidence.details).toBeUndefined();+ expect(evidence.locations).toEqual([{ path: "infra/net/main.tf", line: 7 }]);+ expect(evidence.source_data).toMatchObject({+ fcs_version: "4.2.3",+ detection,+ });+ expect(evidence.source_data).not.toHaveProperty("repository_url");+ // Without Git there are no remotes to compare, so the URL is retained as supplied.+ const bound = await fixture.prepare();+ expect(bound.preview.findings[0]!.evidence.details?.repository).toMatchObject(+ {+ url: repositoryUrl,+ },+ );+});++test("imports check the checkout files and repository claims, even for empty selections", async () => {+ await using fixture = await checkout();+ await fixture.writeJson(single);+ const { preview } = await fixture.prepare();+ await rm(join(fixture.repository, "infra", "net", "main.tf"));+ await expect(fixture.prepare()).rejects.toThrow(+ /"infra\/net\/main\.tf" is not in .*run the FCS CLI from its root/u,+ );+ await expect(fixture.prepareNormalized(preview)).rejects.toThrow(+ /is not in/u,+ );+ await writeFile(join(fixture.repository, "infra", "net", "main.tf"), "\n");+ await expect(fixture.prepare()).rejects.toThrow(+ /"infra\/net\/main\.tf" changed after the FCS scan/u,+ );+ await expect(fixture.prepareNormalized(preview)).rejects.toThrow(+ /changed after the FCS scan/u,+ );+ await writeFile(join(fixture.repository, "infra", "net", "main.tf"), "");+ // FCS follows a file symlink and records the hash of its target.+ const target = join(fixture.root, "shared.tf");+ await writeFile(target, "");+ await rm(join(fixture.repository, "infra", "net", "main.tf"));+ await symlink(target, join(fixture.repository, "infra", "net", "main.tf"));+ await fixture.prepare();+ const otherUrl = "https://github.com/example/other";+ const wrongReport = structuredClone(preview);+ wrongReport.report!["repositoryUrl"] = otherUrl;+ await expect(fixture.prepareNormalized(wrongReport)).rejects.toThrow(+ /different repository/u,+ );+ const wrongRow = structuredClone(preview);+ wrongRow.findings[0]!.evidence.source_data!["repository_url"] = otherUrl;+ await expect(fixture.prepareNormalized(wrongRow)).rejects.toThrow(+ /different repository/u,+ );+ await expect(+ prepareNormalizedLocalImport(+ preview,+ {+ provider: "wiz",+ sourceKey: source.sourceKey,+ repository: fixture.repository,+ },+ { environment: fixture.environment },+ ),+ ).rejects.toThrow(/crowdstrike provider/i);+ fixture.git("remote", "set-url", "origin", otherUrl);+ for (const rule_detections of [[misconfiguration], []]) {+ await fixture.writeJson({ ...report, rule_detections });+ await expect(fixture.prepare()).rejects.toThrow(/fetch remote/u);+ }+});++test("replayed findings keep the location of their native detection", async () => {+ await using fixture = await checkout();+ await fixture.writeJson(single);+ const { preview } = await fixture.prepare();+ const location = { path: "infra/net/main.tf", line: 7 };+ // infra/provider.tf has the same content, so only the location check stops it.+ for (const locations of [+ [],+ undefined,+ [{ ...location, path: "infra/provider.tf" }],+ [{ ...location, line: 8 }],+ [location, location],+ ]) {+ const replay = structuredClone(preview);+ replay.findings[0]!.evidence.locations = locations;+ await expect(fixture.prepareNormalized(replay)).rejects.toThrow(+ /locations must match the native detection/u,+ );+ }+ await rm(join(fixture.repository, "infra", "net", "main.tf"));+ const cleared = structuredClone(preview);+ cleared.findings[0]!.evidence.locations = [];+ await expect(fixture.prepareNormalized(cleared)).rejects.toThrow(+ /locations must match the native detection/u,+ );+});++test("Cloud rejects local CrowdStrike findings before file access or credential lookup", async () => {+ await using fixture = await checkout();+ const options = { ...source, repository: fixture.repository };+ const unexpected = mock(async () => {+ throw new Error("Unexpected Cloud call");+ });+ const deps = {+ environment: fixture.environment,+ fetch: unexpected,+ credentials: unexpected,+ };+ // JavaScript callers may supply a local provider despite the SDK's Cloud types.+ const cloudOptions =+ options as unknown as NormalizedExternalPublicationOptions;+ const empty = { read: 0, findings: [], excluded: [] };+ await expect(+ prepareExternalPublication(fixture.file, cloudOptions, deps),+ ).rejects.toThrow(/local/i);+ await expect(+ prepareNormalizedExternalPublication(empty, cloudOptions, deps),+ ).rejects.toThrow(/local/i);+ await fixture.writeJson(single);+ const { preview } = await fixture.prepare();+ const relabeled = { ...options, provider: "wiz" as const };+ await expect(+ prepareNormalizedExternalPublication(preview, relabeled, deps),+ ).rejects.toThrow(/local/i);+ expect(unexpected).not.toHaveBeenCalled();+});