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): include AWS-generated patches in Continuum findings (#2615)

Michael D'Angelo7b5335becab8
diff --git a/docs/scanner-imports/README.md b/docs/scanner-imports/README.md
index 6ff1c871f..bdebb4bf5 100644
--- a/docs/scanner-imports/README.md
+++ b/docs/scanner-imports/README.md
@@ -26,7 +26,7 @@ The guides cover local and Cloud imports unless a row limits its scope.
| ----------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------- |
| [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` | Summaries or selected code finding details for one verified repository |
+| [AWS Continuum](continuum.md) | `continuum` | Code finding details and available patches, or summaries for one repository |
| [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 |
diff --git a/docs/scanner-imports/continuum.md b/docs/scanner-imports/continuum.md
index ff092fb79..499283880 100644
--- a/docs/scanner-imports/continuum.md
+++ b/docs/scanner-imports/continuum.md
@@ -1,18 +1,20 @@
# Import AWS Continuum code findings
-Use `GetCodeFinding` JSON to import selected findings with their locations
-and mitigation. When AWS has run validation, the export also includes the
-validation result. Use `ListCodeFindings` JSON for summaries from an
-environment dedicated to one repository.
+Collect a selected finding with its locations, mitigation, validation result
+(when available), and any AWS-generated patches for its repository. The import
+saves patches as evidence for review without applying them to your checkout.
## Quick start
-Open the matching checkout. Set `ENVIRONMENT_ID` to the Continuum environment ID. Verify which
+Identify the matching local checkout. Set `ENVIRONMENT_ID` to the Continuum environment ID. Verify which
repository supplied the scanned code, including the archive for an S3 source.
For a finding from another scanner, you can also check its repository in that
scanner. [AWS Continuum code sources](https://docs.aws.amazon.com/continuum/latest/userguide/cv-getting-started.html)
-**Saved report.** Set `report` to a native detail response, an array of detail responses, or a complete list response with its `items` array. Then [preview the report](#preview-and-import).
+**Saved report.** The importer can read a collector capture, a native
+`GetCodeFinding` response, an array of either, or a complete `ListCodeFindings`
+response from a single-repository environment. With a saved report, the importer
+reads the file offline. Set its path and [preview the report](#preview-and-import).
```sh
report=/private/path/continuum.json
@@ -24,20 +26,44 @@ To create a report, sign in to the environment's AWS account and Region with
AWS CLI v2.38.5 or later, the first release with `aws continuum`. Choose one
export.
-**One finding.** Set `FINDING_ID` to the Continuum ID of the finding you
-verified. In an environment with several repositories, use this command to
-export one verified finding at a time. [AWS CLI get-code-finding](https://docs.aws.amazon.com/cli/latest/reference/continuum/get-code-finding.html)
+**One finding with available patches.** Set `FINDING_ID` to the verified
+finding ID. The bundled Python 3.10+ collector uses your signed-in AWS CLI to read
+the finding, follow its created or duplicate issue ID, and retrieve its
+`PATCH` artifacts. Its IAM permissions are `continuum:GetCodeFinding`,
+`continuum:ListCodeIssueArtifacts`, and `continuum:GetCodeIssueArtifact`.
+[AWS issue artifacts](https://docs.aws.amazon.com/continuum/latest/APIReference/API_ListCodeIssueArtifacts.html)
+
+Run the collector from a trusted shell outside the checkout. Set `source_root`
+to the absolute path of the local checkout that owns the finding. Keep your AWS
+config, shared credentials, CLI aliases, and custom service models outside that checkout. The AWS CLI
+and its helpers receive your AWS settings (including profile and Region), proxy
+and OS account settings, and a `PATH` that excludes the checkout. If a custom
+helper needs other shell variables, use a profile that works with these settings
+or import a saved report.
+
+The example uses a global npm installation and a verified single-repository
+environment. For a multi-repository environment, replace `--single-repository` with
+`--repository-name "$AWS_SOURCE_NAME"`. Use the exact source name AWS assigns
+to that repository. One issue can have patches for several sources. In this
+mode the collector skips patches without a repository name and prints their
+artifact IDs to stderr for review. [AWS patch fields](https://docs.aws.amazon.com/continuum/latest/APIReference/API_PatchBody.html)
```sh
report=
+source_root=/absolute/path/to/checkout
+plugin="$(npm root --global)/@openai/codex-security/_bundled_plugin"
out=$(mktemp -d "${TMPDIR:-/tmp}/continuum.XXXXXX") &&
- aws continuum get-code-finding --environment-id "$ENVIRONMENT_ID" \
- --finding-id "$FINDING_ID" --output json > "$out/continuum.tmp" &&
+ python3 -I "$plugin/skills/publish-findings/scripts/collect_continuum.py" \
+ --environment-id "$ENVIRONMENT_ID" --finding-id "$FINDING_ID" \
+ --source-root "$source_root" --single-repository > "$out/continuum.tmp" &&
mv "$out/continuum.tmp" "$out/continuum.json" &&
report="$out/continuum.json"
```
-**Selected findings.** Fetch one detail response per finding ID. Verify each
+If the finding has no linked issue or no matching patches, the collector saves
+the native finding detail. If an AWS read fails, retry the export before import.
+
+**Selected findings.** Run the collector once per finding ID. Verify each
belongs to the same environment and Git repository. To publish them together,
combine the saved objects into a JSON array with `jq`.
@@ -63,8 +89,8 @@ out=$(mktemp -d "${TMPDIR:-/tmp}/continuum.XXXXXX") &&
### Preview and import
-Preview the report with the verified Git URL and a source key for this
-environment and repository.
+From the matching checkout, preview the saved report with the verified Git
+URL and a source key for this environment and repository.
```sh
codex-security publish findings "$report" --to local --repository . \
@@ -75,15 +101,71 @@ codex-security publish findings "$report" --to local --repository . \
Check the repository, finding ARNs, paths, and exclusions. In a
multi-repository environment, a customer-supplied path can begin with a
-repository name. The reader keeps that prefix. For local repeat imports, a summary replaces richer evidence already saved for the same ARN and source key. Use the detail export to keep locations, mitigation and validation evidence. To save locally, remove `--dry-run` and confirm.
+repository name. The reader keeps that prefix. For local repeat imports, a summary replaces richer evidence already saved for the same ARN and source key. Use the collector capture to keep locations, mitigation, validation evidence, and available patches. To save locally, remove `--dry-run` and confirm.
+
+Run `codex-security findings imported . --format json` and match the finding ARN.
+The original AWS record is in `evidence.source_data.finding`. When AWS supplied
+patches, `evidence.source_data.patches` contains one entry per matching
+artifact with its ID (`artifactId`), exact patch text (`patch`), SHA-256
+(`patchSha256`), byte count (`sizeBytes`), and AWS format and repository name
+when supplied.
+
+### Patch and verify one finding
+
+From the checkout you want to fix, set `finding` to the path of a
+single-finding collector capture. To use a local workbench record instead,
+select its evidence by the finding ARN and the source key used at import.
+
+```sh
+out=$(mktemp -d "${TMPDIR:-/tmp}/continuum.XXXXXX") &&
+ codex-security findings imported . --format json > "$out/imported.json" &&
+ jq -e --arg arn "$FINDING_ARN" --arg key "$SOURCE_KEY" \
+ '.findings[] | select(.provider == "continuum" and .sourceKey == $key and .sourceFindingId == $arn) | .evidence' \
+ "$out/imported.json" > "$out/finding.json" &&
+ finding="$out/finding.json"
+```
+
+```mermaid
+flowchart LR
+ A[Continuum finding] --> C[Collector capture]
+ B[Linked issue PATCH artifacts] --> C
+ C --> F[One finding file]
+ C --> I[Import to local workbench]
+ I -->|Select stored evidence| F
+ F --> B0[validate on original checkout]
+ F --> P[patch in writable checkout]
+ P -->|Resulting diff| V[verify-fix on edited checkout]
+ F --> V
+```
+
+`validate` assesses the original checkout. When an AWS patch is available,
+`patch` starts from that diff and adapts it to the current code as needed.
+
+```sh
+codex-security validate "$finding"
+codex-security patch "$finding"
+```
+
+Review the resulting diff and run the relevant regression tests. Use the same
+finding file for an independent read-only check of the edited checkout.
+`verify-fix` reports `fixed`, `still_vulnerable`, or `inconclusive` with evidence.
+
+```sh
+git diff
+codex-security verify-fix "$finding"
+```
<a id="publish-to-your-cloud-inbox"></a>
### Publish to Cloud
-If you need locations, mitigation, or validation evidence, publish the detailed
-`get-code-finding` export first. For private inbox imports, a later upload
-with changed evidence for the same ARN can return `source_order_unknown`.
+Publish the collector capture first to include available patches. Cloud uses
+the same `evidence.source_data.patches` field. When patch text would exceed
+the Cloud finding evidence limit, the patch entry retains its descriptors and
+records `contentOmitted: "cloud_evidence_limit"`. If the finding and patch
+metadata alone exceed the limit, the Cloud preview reports an exclusion. The
+local capture retains the complete text. For private inbox imports, a later
+upload with changed evidence for the same ARN can return `source_order_unknown`.
Preview the file and source key using your connected repository URL.
```sh
diff --git a/docs/scanner-imports/workbench.md b/docs/scanner-imports/workbench.md
index 24e75468a..ef80727f6 100644
--- a/docs/scanner-imports/workbench.md
+++ b/docs/scanner-imports/workbench.md
@@ -62,7 +62,7 @@ For a saved export, say which checkout and report to use. For an upstream read,
| “Scan package.json for Snyk dependency issues.” | Runs the signed-in `snyk test --file=package.json` with JSON file output and imports the native dependency report. | A findings exit code of 1 still produces findings with the reported dependency paths. [Snyk CLI](snyk.md#native-cli-json) |
| “Import Wiz package occurrences A and B for this repo.” | Fetches those occurrences through the connected Wiz tool or reads a detailed package vulnerability export. | Compare the stored Wiz occurrence IDs with A and B, including when both share a CVE. [Wiz](wiz.md) |
| “Get Inspector findings for this Code Security repository in us-east-1.” | Runs `aws inspector2 list-findings` for the account and exact `CODE_REPOSITORY` resource. | A fixture containing EC2 findings imports only the eligible repository findings, identified by finding ARN. [Inspector](inspector.md) |
-| “Import Continuum finding F from environment E.” | Runs `aws continuum get-code-finding` for E and F after verifying the owning repository. | Import the summary, then the detail under the same source key. The same ARN gains the reported location. [Continuum](continuum.md) |
+| “Import Continuum finding F from environment E.” | Collects the detailed finding and linked PATCH artifacts for the verified repository. | Match the stored ARN and any `source_data.patches` to the AWS finding and issue artifacts. [Continuum](continuum.md) |
| “Import this Black Duck project version’s vulnerable components.” | Reads the complete BOM-6 collection for that version and verifies the Git repository. | The stored `source_data.projectVersionUrl` identifies the selected version. [Black Duck](blackduck.md) |
| “Import completed Checkmarx scan S for payments.” | Exports Checkmarx One JSON with `cx results show`, or reads the self-managed CxSAST scan’s XML. | The retained scan ID is S and the result’s ordered path nodes match the export. [Checkmarx](checkmarx.md) |
| “Get Endor Findings A and B from this project and namespace.” | Filters `endorctl api list --resource Finding` to the project, scan context and requested UUIDs. | The preview contains both requested finding UUIDs once. [Endor Labs](endor.md) |
diff --git a/plugins/codex-security/plugin-files.json b/plugins/codex-security/plugin-files.json
index d4db360be..ff8e6761b 100644
--- a/plugins/codex-security/plugin-files.json
+++ b/plugins/codex-security/plugin-files.json
@@ -147,6 +147,8 @@
"skills/publish-findings/references/checkmarx-import.md",
"skills/publish-findings/references/wiz-import.md",
"skills/publish-findings/scripts/collect_checkmarx.py",
+ "skills/publish-findings/scripts/collect_continuum.py",
+ "skills/publish-findings/scripts/collector_paths.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/fix-finding/SKILL.md b/plugins/codex-security/skills/fix-finding/SKILL.md
index 839dbc6f7..e5d1f26ea 100644
--- a/plugins/codex-security/skills/fix-finding/SKILL.md
+++ b/plugins/codex-security/skills/fix-finding/SKILL.md
@@ -35,6 +35,7 @@ Treat the finding as a data-flow and boundary problem, not merely the named inpu
1. Trace the reported path and inspect only the context needed to identify the real shared boundary. Return `no_change` when repository evidence shows that the reported path is already safe; do not make a speculative change.
2. In standard mode, when feasible, run the smallest high-signal reproduction through that boundary and one legitimate control through the same path.
3. Implement the smallest repository-native fix at the shared boundary. Prefer nearby helpers and established APIs. Do not broaden into unrelated redesign, cleanup, or sibling findings.
+ - If the finding includes a proposed patch for this repository, use it as the starting candidate. For AWS Continuum, read `patches[].patch` from a collector capture or `source_data.patches[].patch` from the stored finding's `evidence`. Compare the hunks with the current checkout. Keep those that enforce the security invariant and adapt or replace those that leave a bypass or break legitimate behavior. If only artifact metadata is available, develop the fix from source.
4. Before verification, challenge the patch rather than defending it: inspect every direct caller of each changed helper and both outcomes of each changed condition. Look for one sibling path, representation, or copy that still reaches the vulnerable sink and one ordinary or default input that the patch newly rejects or reinterprets; revise the implementation if either exists.
5. In standard mode, verify the resulting change:
- inspect the final diff and run the narrowest syntax, import, build, or type check relevant to it
diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.md
index c5e70d9c5..7e6762aaa 100644
--- a/plugins/codex-security/skills/publish-findings/SKILL.md
+++ b/plugins/codex-security/skills/publish-findings/SKILL.md
@@ -24,7 +24,8 @@ For a fresh scan, look for the relevant executable in the environment where it w
| Snyk | For a monitored Open Source project use `codex-security import snyk PROJECT_ID --org ORG_ID --source-repository-url URL --format json`. Add `--snyk-product code` for a monitored Code project. For a fresh dependency scan use native `snyk test` JSON or the signed-in Snyk plugin's SCA export from the requested root. Keep acquisition formats in distinct namespaces. |
| 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) |
-| 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. Continuum uses GetCodeFinding details or repository-specific summaries. 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) |
+| AWS Continuum | From a trusted directory outside the checkout, run the [bundled collector](scripts/collect_continuum.py) with the signed-in AWS CLI and selected profile and Region. Pass `--source-root` with the absolute path of the selected local checkout, `--environment-id`, `--finding-id`, and either `--single-repository` for a verified single-repository environment or `--repository-name` with the exact AWS source name. Import the resulting JSON to retain generated patches as evidence. A saved native detail or complete single-repository list also works offline. [Continuum guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/continuum.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 issues
diff --git a/plugins/codex-security/skills/publish-findings/scripts/collect_checkmarx.py b/plugins/codex-security/skills/publish-findings/scripts/collect_checkmarx.py
index e86e49fb1..daa6e34ad 100644
--- a/plugins/codex-security/skills/publish-findings/scripts/collect_checkmarx.py
+++ b/plugins/codex-security/skills/publish-findings/scripts/collect_checkmarx.py
@@ -6,7 +6,6 @@ import os
import re
import shutil
import signal
-import stat
import subprocess
import sys
import tempfile
@@ -16,63 +15,9 @@ 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
+# Isolated Python does not put the installed script directory on sys.path.
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from collector_paths import in_source, source_root # noqa: E402
def installed_file(value: str, source: Path | None) -> Path:
diff --git a/plugins/codex-security/skills/publish-findings/scripts/collect_continuum.py b/plugins/codex-security/skills/publish-findings/scripts/collect_continuum.py
new file mode 100644
index 000000000..49663e5f8
--- /dev/null
+++ b/plugins/codex-security/skills/publish-findings/scripts/collect_continuum.py
@@ -0,0 +1,224 @@
+"""Export one AWS Continuum finding and its selected repository's generated patches."""
+
+import argparse
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+# Isolated Python does not put the installed script directory on sys.path.
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from collector_paths import in_source, source_root # noqa: E402
+
+# Credential helpers may use any interpreter. Forward AWS and host settings
+# explicitly so a helper cannot inherit language-specific startup hooks.
+ACCOUNT_DIRECTORIES = {"HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "XDG_CONFIG_HOME"}
+HOST_SETTINGS = ACCOUNT_DIRECTORIES | {
+ "ALL_PROXY",
+ "CURL_CA_BUNDLE",
+ "HOMEDRIVE",
+ "HOMEPATH",
+ "HTTP_PROXY",
+ "HTTPS_PROXY",
+ "LANG",
+ "LANGUAGE",
+ "LOGNAME",
+ "NO_PROXY",
+ "REQUESTS_CA_BUNDLE",
+ "SSH_AUTH_SOCK",
+ "SSL_CERT_DIR",
+ "SSL_CERT_FILE",
+ "SYSTEMROOT",
+ "TEMP",
+ "TMP",
+ "TMPDIR",
+ "TZ",
+ "USER",
+ "USERNAME",
+ "WINDIR",
+}
+
+
+def checked_model_path(path: Path, source: Path | None, levels: int) -> None:
+ if in_source(path, source) or (source is not None and source.is_relative_to(path.resolve())):
+ raise ValueError(f"Use an AWS model path separate from the selected checkout: {path}")
+ if levels and path.is_dir():
+ # AWS reads global models and service/<version>/*.json[.gz]. Version
+ # names come from the filesystem; even a new version can override AWS.
+ for child in path.iterdir():
+ if child.name.lower().endswith((".json", ".json.gz")) or (
+ levels > 1 and child.is_dir()
+ ):
+ checked_model_path(child, source, levels - 1)
+
+
+def pinned_setting(name: str, path: Path) -> str:
+ # Preserve paths expanded from parent-only variables; the CLI expands the
+ # forwarded value again and splits its model path on the platform separator.
+ value = str(path)
+ if os.path.expandvars(value) != value or (name == "AWS_DATA_PATH" and os.pathsep in value):
+ raise ValueError(f"Use a fully expanded file path for {name}.")
+ return value
+
+
+def aws_environment(source: Path | None, cwd: Path, directories: list[str]) -> dict[str, str]:
+ env = {
+ name: value
+ for name, value in os.environ.items()
+ if name.startswith(("AWS_", "LC_")) or name.upper() in HOST_SETTINGS
+ }
+ env["PATH"] = os.pathsep.join(directories)
+ for name in ACCOUNT_DIRECTORIES:
+ if env.get(name) and in_source(cwd / env[name], source):
+ raise ValueError(f"Use an account {name} directory outside the selected checkout.")
+
+ # AWS can run credential_process from either profile file and shell commands
+ # from its per-account alias file. Check the paths AWS will actually read.
+ for name, default in (
+ ("AWS_CONFIG_FILE", "~/.aws/config"),
+ ("AWS_SHARED_CREDENTIALS_FILE", "~/.aws/credentials"),
+ ):
+ filename = os.path.expanduser(os.path.expandvars(env.get(name, default)))
+ path = cwd / filename
+ if in_source(path, source):
+ raise ValueError(f"Use an {name} file outside the selected checkout.")
+ if name in env:
+ env[name] = pinned_setting(name, path)
+ if in_source(cwd / os.path.expanduser("~/.aws/cli/alias"), source):
+ raise ValueError("Use an AWS CLI alias file outside the selected checkout.")
+ checked_model_path(cwd / os.path.expanduser("~/.aws/models"), source, 3)
+ if "AWS_DATA_PATH" in env:
+ paths = []
+ for entry in env["AWS_DATA_PATH"].split(os.pathsep):
+ directory = os.path.expanduser(os.path.expandvars(entry))
+ if directory:
+ path = cwd / directory
+ checked_model_path(path, source, 3)
+ paths.append(pinned_setting("AWS_DATA_PATH", path))
+ env["AWS_DATA_PATH"] = os.pathsep.join(paths)
+ return env
+
+
+def installed_aws(target: Path) -> tuple[Path, dict[str, str], Path]:
+ source = source_root(target)
+ name = "aws.exe" if os.name == "nt" else "aws"
+ executable = None
+ directories = []
+ for entry in os.get_exec_path():
+ if os.name == "nt" and entry.startswith('"') and entry.endswith('"'):
+ entry = entry[1:-1]
+ directory = Path(entry)
+ if not directory.is_absolute():
+ continue
+ try:
+ # Also exclude a host directory whose aws links through the checkout.
+ if in_source(directory / name, source):
+ continue
+ directory = directory.resolve(strict=True)
+ if not directory.is_dir():
+ continue
+ candidate = directory / name
+ if executable is None and candidate.is_file() and os.access(candidate, os.X_OK):
+ resolved = candidate.resolve(strict=True)
+ if os.name == "nt" and resolved.suffix.lower() != ".exe":
+ continue
+ executable = resolved
+ directories.append(str(directory))
+ except OSError:
+ continue
+ if executable is None:
+ raise ValueError("Could not find an installed AWS CLI outside the selected checkout.")
+
+ # Credential helpers inherit the same lookup boundary, including on Windows
+ # where executable searches can also use the current directory.
+ cwd = executable.parent if in_source(Path.cwd(), source) else Path.cwd()
+ return executable, aws_environment(source, cwd, directories), cwd
+
+
+def collect(
+ environment_id: str, finding_id: str, repository_name: str | None, target: Path
+) -> dict:
+ executable, child_env, cwd = installed_aws(target)
+
+ def aws(operation: str, *arguments: str) -> dict:
+ return json.loads(
+ subprocess.check_output(
+ [
+ str(executable),
+ "continuum",
+ operation,
+ *arguments,
+ "--output",
+ "json",
+ "--no-cli-pager",
+ ],
+ env=child_env,
+ cwd=cwd,
+ )
+ )
+
+ environment = ["--environment-id", environment_id]
+ finding = aws("get-code-finding", *environment, "--finding-id", finding_id)
+ issue_id = finding.get("createdIssueId") or finding.get("duplicateOfIssueId")
+ if not issue_id:
+ return finding
+
+ issue = [*environment, "--issue-id", issue_id]
+ # With JSON output the AWS CLI combines all pages into one items array.
+ artifacts = aws("list-code-issue-artifacts", *issue, "--artifact-type", "PATCH")
+ patches = []
+ for artifact_id in sorted(item["artifactId"] for item in artifacts["items"]):
+ artifact = aws("get-code-issue-artifact", *issue, "--artifact-id", artifact_id)
+ body = artifact["body"].get("patch")
+ if body is None:
+ raise ValueError(f"Continuum artifact {artifact_id} has no projected patch body.")
+ if repository_name is not None and body.get("repositoryName") != repository_name:
+ if not body.get("repositoryName"):
+ print(
+ f"Skipped Continuum patch {artifact_id}: AWS did not identify its repository.",
+ file=sys.stderr,
+ )
+ continue
+ patch = {key: body[key] for key in ("patch", "patchSha256", "sizeBytes")}
+ for key in ("format", "repositoryName"):
+ if key in body:
+ patch[key] = body[key]
+ patches.append({"artifactId": artifact_id, **patch})
+
+ return {"finding": finding, "patches": patches} if patches else finding
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "--source-root",
+ type=Path,
+ required=True,
+ help="Absolute path to the selected local checkout to exclude from executable lookup.",
+ )
+ parser.add_argument("--environment-id", required=True)
+ parser.add_argument("--finding-id", required=True)
+ scope = parser.add_mutually_exclusive_group(required=True)
+ scope.add_argument(
+ "--single-repository",
+ action="store_true",
+ help="The selected environment has been verified to contain only this repository.",
+ )
+ scope.add_argument("--repository-name", help="Exact Continuum build repository name.")
+ args = parser.parse_args()
+ try:
+ report = collect(
+ args.environment_id, args.finding_id, args.repository_name, args.source_root
+ )
+ except subprocess.CalledProcessError as error:
+ # The AWS CLI already wrote the diagnostic to stderr.
+ return error.returncode
+ except (KeyError, OSError, ValueError) as error:
+ sys.exit(f"Could not export Continuum finding: {error}")
+ print(json.dumps(report))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/plugins/codex-security/skills/publish-findings/scripts/collector_paths.py b/plugins/codex-security/skills/publish-findings/scripts/collector_paths.py
new file mode 100644
index 000000000..b519e4a06
--- /dev/null
+++ b/plugins/codex-security/skills/publish-findings/scripts/collector_paths.py
@@ -0,0 +1,63 @@
+"""Identify the selected source checkout and paths it controls."""
+
+import os
+import stat
+from pathlib import Path
+
+
+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
diff --git a/plugins/codex-security/tests/test_collect_continuum.py b/plugins/codex-security/tests/test_collect_continuum.py
new file mode 100644
index 000000000..81ab0f6f3
--- /dev/null
+++ b/plugins/codex-security/tests/test_collect_continuum.py
@@ -0,0 +1,343 @@
+"""Cover source selection and failures at the AWS CLI boundary."""
+
+import json
+import os
+import runpy
+import shlex
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+SCRIPT = (
+ Path(__file__).resolve().parents[1] / "skills/publish-findings/scripts/collect_continuum.py"
+)
+main = runpy.run_path(str(SCRIPT))["main"]
+AWS_NAME = "aws.exe" if os.name == "nt" else "aws"
+
+
+def arguments(checkout, *scope):
+ identity = ["--environment-id", "env", "--finding-id", "f"]
+ return [str(SCRIPT), "--source-root", str(checkout), *identity, *scope]
+
+
+def collect_one(checkout, directories, **environment):
+ return subprocess.run(
+ [sys.executable, "-I", *arguments(checkout, "--single-repository")],
+ cwd=checkout.parent,
+ env={**os.environ, "PATH": os.pathsep.join(map(str, directories)), **environment},
+ capture_output=True,
+ text=True,
+ )
+
+
+def write_service_model(root):
+ model = root / "continuum/2099-10-23/service-2.json"
+ model.parent.mkdir(parents=True)
+ model.write_text("{}")
+
+
+def checkout(tmp_path):
+ checkout = tmp_path / "source"
+ checkout.mkdir()
+ return checkout
+
+
+def invoke(monkeypatch, tmp_path, checkout):
+ for directory in (checkout, tmp_path):
+ executable = directory / AWS_NAME
+ executable.touch()
+ executable.chmod(0o755)
+ monkeypatch.setenv("PATH", os.pathsep.join(map(str, (checkout, tmp_path))))
+ monkeypatch.setenv("NODE_OPTIONS", f"--require={checkout / 'startup.cjs'}")
+
+ def run(scope, *responses):
+ replies = iter(responses)
+ calls = []
+
+ def aws(command, **kwargs):
+ assert Path(command[0]) == (tmp_path / AWS_NAME).resolve()
+ assert "NODE_OPTIONS" not in kwargs["env"]
+ calls.append(command)
+ reply = next(replies)
+ if isinstance(reply, Exception):
+ raise reply
+ return json.dumps(reply).encode()
+
+ monkeypatch.setattr(subprocess, "check_output", aws)
+ monkeypatch.setattr(sys, "argv", arguments(checkout, *scope))
+ return main(), calls
+
+ return run
+
+
+def patch(source=None):
+ return {
+ "body": {
+ "patch": {
+ "patch": "example\n",
+ "sizeBytes": 8,
+ "patchSha256": "13550350a8681c84c861aac2e5b440161c2b33a3e4f302ac680ca5b686de48de",
+ **({"repositoryName": source} if source else {}),
+ }
+ }
+ }
+
+
+def test_collects_only_selected_repository_on_duplicate_issue(invoke, capsys):
+ finding = {"duplicateOfIssueId": "original"}
+ status, calls = invoke(
+ ["--repository-name", "api"],
+ finding,
+ {"items": [{"artifactId": "two"}, {"artifactId": "one"}]},
+ patch("api"),
+ patch("web"),
+ )
+ assert status == 0
+ assert [call[2] for call in calls] == [
+ "get-code-finding",
+ "list-code-issue-artifacts",
+ "get-code-issue-artifact",
+ "get-code-issue-artifact",
+ ]
+ for call in calls:
+ assert call[3:5] == ["--environment-id", "env"]
+ assert calls[0][5:7] == ["--finding-id", "f"]
+ assert calls[1][5:9] == ["--issue-id", "original", "--artifact-type", "PATCH"]
+ assert [call[5:9] for call in calls[2:]] == [
+ ["--issue-id", "original", "--artifact-id", "one"],
+ ["--issue-id", "original", "--artifact-id", "two"],
+ ]
+ assert json.loads(capsys.readouterr().out) == {
+ "finding": finding,
+ "patches": [{"artifactId": "one", **patch("api")["body"]["patch"]}],
+ }
+
+
+def test_unnamed_patch_does_not_block_matching_patches(invoke, capsys):
+ finding = {"createdIssueId": "issue"}
+ status, _ = invoke(
+ ["--repository-name", "api"],
+ finding,
+ {"items": [{"artifactId": "one"}, {"artifactId": "two"}]},
+ patch(),
+ patch("api"),
+ )
+ output = capsys.readouterr()
+ assert status == 0
+ assert "Skipped Continuum patch one" in output.err
+ assert json.loads(output.out) == {
+ "finding": finding,
+ "patches": [{"artifactId": "two", **patch("api")["body"]["patch"]}],
+ }
+
+
+ ("finding", "replies"),
+ [
+ ({"findingId": "f"}, []),
+ ({"createdIssueId": "issue"}, [{"items": [{"artifactId": "one"}]}, patch("web")]),
+ ],
+)
+def test_no_eligible_patch_preserves_native_finding(invoke, capsys, finding, replies):
+ status, _ = invoke(["--repository-name", "api"], finding, *replies)
+ assert status == 0
+ assert json.loads(capsys.readouterr().out) == finding
+
+
+def test_failure_after_first_patch_emits_no_partial_report(invoke, capsys):
+ status, _ = invoke(
+ ["--single-repository"],
+ {"createdIssueId": "issue"},
+ {"items": [{"artifactId": "one"}, {"artifactId": "two"}]},
+ patch(),
+ subprocess.CalledProcessError(254, ["aws"]),
+ )
+ assert status == 254
+ assert not capsys.readouterr().out
+
+
+def test_no_installed_aws_never_launches_checkout_executable(checkout, monkeypatch):
+ executable = checkout / AWS_NAME
+ executable.touch()
+ executable.chmod(0o755)
+ monkeypatch.setenv("PATH", str(checkout))
+ monkeypatch.setattr(sys, "argv", arguments(checkout, "--single-repository"))
+
+ def unexpected(command, **kwargs):
+ pytest.fail(f"Collector invoked {command[0]} with no installed AWS CLI on PATH")
+
+ monkeypatch.setattr(subprocess, "check_output", unexpected)
+ with pytest.raises(SystemExit, match="(?i)aws"):
+ main()
+
+
[email protected]("setting", ["AWS_CONFIG_FILE", "AWS_SHARED_CREDENTIALS_FILE"])
+def test_checkout_credential_process_file_is_rejected(checkout, invoke, monkeypatch, setting):
+ config = checkout / "profile"
+ config.write_text("[default]\ncredential_process = checkout-command\n")
+ monkeypatch.setenv(setting, str(config))
+ with pytest.raises(SystemExit, match="checkout"):
+ invoke(["--single-repository"], {})
+
+
[email protected](os.name == "nt", reason="Fixture links a settings file into the checkout")
+ ("name", "contents"),
+ [
+ ("config", "[default]\ncredential_process = checkout-command\n"),
+ ("cli/alias", "[toplevel]\ncontinuum = !checkout-command\n"),
+ ],
+)
+def test_default_settings_linked_into_checkout_are_rejected(
+ tmp_path, checkout, invoke, monkeypatch, name, contents
+):
+ config = checkout / "settings"
+ config.write_text(contents)
+ home = tmp_path / "home"
+ default_file = home / ".aws" / name
+ default_file.parent.mkdir(parents=True)
+ default_file.symlink_to(config)
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.delenv("AWS_CONFIG_FILE", raising=False)
+ with pytest.raises(SystemExit, match="checkout"):
+ invoke(["--single-repository"], {})
+
+
[email protected]("trusted_first", [False, True])
+def test_model_search_path_rejects_checkout_entries(checkout, invoke, monkeypatch, trusted_first):
+ write_service_model(checkout)
+ trusted = checkout.parent / "installed-models"
+ trusted.mkdir()
+ paths = (trusted, checkout) if trusted_first else (checkout,)
+ monkeypatch.setenv("AWS_DATA_PATH", os.pathsep.join(map(str, paths)))
+ with pytest.raises(SystemExit, match="checkout"):
+ invoke(["--single-repository"], {})
+
+
[email protected](os.name == "nt", reason="Fixture links service models into the checkout")
+ ("use_default", "linked_entry"),
+ [
+ (False, "."),
+ (True, "continuum"),
+ (False, "continuum/2099-10-23"),
+ (True, "continuum/2099-10-23/service-2.json"),
+ ],
+)
+def test_aws_model_links_into_checkout_are_rejected(
+ tmp_path, checkout, invoke, monkeypatch, use_default, linked_entry
+):
+ write_service_model(checkout)
+ if use_default:
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.delenv("AWS_DATA_PATH", raising=False)
+ models = tmp_path / ".aws/models"
+ else:
+ models = tmp_path / "installed-models"
+ monkeypatch.setenv("AWS_DATA_PATH", str(models))
+ link = models / linked_entry
+ link.parent.mkdir(parents=True, exist_ok=True)
+ target = checkout / linked_entry
+ link.symlink_to(target, target_is_directory=target.is_dir())
+ with pytest.raises(SystemExit, match="checkout"):
+ invoke(["--single-repository"], {})
+
+
[email protected](os.name == "nt", reason="Fixture uses Bash scripts and POSIX symlinks")
+def test_aws_and_its_credential_helper_skip_checkout_launchers_and_startup_hooks(tmp_path):
+ checkout = tmp_path / "source"
+ repo_bin = checkout / "bin"
+ repo_bin.mkdir(parents=True)
+ trusted_bin = tmp_path / "installed"
+ helper_bin = tmp_path / "auth-tools"
+ linked_bin = tmp_path / "linked"
+ for directory in (trusted_bin, helper_bin, linked_bin):
+ directory.mkdir()
+
+ def script(path, body):
+ path.write_text("#!/bin/bash\n" + body)
+ path.chmod(0o755)
+
+ marker = tmp_path / "ran-source-tool"
+ for name in ("aws", "fixture-credentials"):
+ script(repo_bin / name, f": > {shlex.quote(str(marker))}\nexit 9\n")
+ alias = tmp_path / "alias"
+ alias.symlink_to(repo_bin, target_is_directory=True)
+ (linked_bin / "aws").symlink_to(repo_bin / "aws")
+ script(trusted_bin / "aws", "exec fixture-credentials\n")
+ credentials = "import json, os\nprint(json.dumps({'profile': os.environ['AWS_PROFILE']}))"
+ script(
+ helper_bin / "fixture-credentials",
+ f"exec {shlex.quote(sys.executable)} -c {shlex.quote(credentials)}\n",
+ )
+ hook_marker = tmp_path / "ran-startup-hook"
+ hook = checkout / "bash-env"
+ hook.write_text(f": > {shlex.quote(str(hook_marker))}\n")
+ python_marker = tmp_path / "ran-sitecustomize"
+ (checkout / "sitecustomize.py").write_text(
+ f"from pathlib import Path\nPath({str(python_marker)!r}).touch()\n"
+ )
+ result = collect_one(
+ checkout,
+ (repo_bin, alias, linked_bin, trusted_bin, helper_bin),
+ AWS_PROFILE="synthetic",
+ BASH_ENV=str(hook),
+ PYTHONPATH=str(checkout),
+ )
+ assert not marker.exists()
+ assert not hook_marker.exists()
+ assert not python_marker.exists()
+ assert result.returncode == 0, result.stderr
+ assert json.loads(result.stdout) == {"profile": "synthetic"}
+
+
[email protected](os.name == "nt", reason="Fixture uses POSIX executable scripts")
+def test_node_credential_helper_ignores_checkout_preload(tmp_path, checkout):
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("Node credential helper requires an installed Node runtime")
+ preload = checkout / "preload.cjs"
+ marker = tmp_path / "ran-node-preload"
+ preload.write_text(f"require('node:fs').writeFileSync({json.dumps(str(marker))}, 'ran');\n")
+
+ aws = tmp_path / "aws"
+ aws.write_text("#!/bin/sh\nexec fixture-node-credentials\n")
+ aws.chmod(0o755)
+ helper = tmp_path / "fixture-node-credentials"
+ helper.write_text(
+ "#!/usr/bin/env node\n"
+ "const keys = ['AWS_PROFILE', 'AWS_REGION', 'AWS_CONFIG_FILE', 'HTTPS_PROXY', "
+ "'AWS_DATA_PATH'];\n"
+ "console.log(JSON.stringify(Object.fromEntries(keys.map(key => [key, process.env[key]]))));\n"
+ )
+ helper.chmod(0o755)
+ config = tmp_path / "profile"
+ config.write_text("[profile synthetic]\ncredential_process = fixture-node-credentials\n")
+ models = tmp_path / "installed-models"
+ write_service_model(models)
+ settings = {
+ "AWS_PROFILE": "synthetic",
+ "AWS_REGION": "us-east-1",
+ "AWS_CONFIG_FILE": str(config),
+ "AWS_DATA_PATH": str(models),
+ "HTTPS_PROXY": "http://proxy.example.invalid:8080",
+ }
+ result = collect_one(
+ checkout,
+ (tmp_path, Path(node).parent),
+ NODE_OPTIONS=f"--require={json.dumps(str(preload))}",
+ **settings,
+ )
+ assert not marker.exists()
+ assert result.returncode == 0, result.stderr
+ assert json.loads(result.stdout) == settings
diff --git a/sdk/typescript/docs/sdk.md b/sdk/typescript/docs/sdk.md
index 2e3cc46da..d8dc776c0 100644
--- a/sdk/typescript/docs/sdk.md
+++ b/sdk/typescript/docs/sdk.md
@@ -767,9 +767,14 @@ Omit `issueKeys` to collect the project's open security issues. An empty list is
If you know the source repository, pass its Git URL in `options.sourceRepositoryUrl`
to check the Sonar binding before fetching issues.
-For AWS Continuum code findings, use `readContinuumFindings(path, sourceRepositoryUrl)`
-with a saved list or detail response, or `normalizeContinuumFindings(input, sourceRepositoryUrl)`
-with parsed JSON. Verify the repository for the selected findings before passing its Git URL.
+For AWS Continuum, pass a collector capture, native detail, array of selected
+details or captures, or complete list response to `readContinuumFindings` (file
+path) or `normalizeContinuumFindings` (parsed JSON). The second argument is
+the verified Git repository URL. Pass `"local"` as the third argument to retain
+full patch contents locally. The default Cloud projection records
+`contentOmitted: "cloud_evidence_limit"` on patches whose contents exceed the
+finding evidence budget. Read the native finding at `evidence.source_data.finding`
+and its available patches at `evidence.source_data.patches`.
[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
diff --git a/sdk/typescript/src/continuum-findings.ts b/sdk/typescript/src/continuum-findings.ts
index 1d5ec8330..914ab3204 100644
--- a/sdk/typescript/src/continuum-findings.ts
+++ b/sdk/typescript/src/continuum-findings.ts
@@ -1,9 +1,12 @@
+import { hash } from "node:crypto";
import { CodexSecurityError } from "./errors.js";
import type { ExternalFinding, ExternalFindings } from "./external-findings.js";
import {
+ CLOUD_EVIDENCE_BYTES,
DEFAULT_CLOUD_STRING_BYTES,
type ExternalImportTarget,
validateEnrichedExternalEvidence,
+ validateExternalEvidenceJson,
} from "./external-import-contract.js";
import type { ImportedPackage, Provider } from "./external-import-models.js";
import { isRecord } from "./record.js";
@@ -159,9 +162,13 @@ function reportRows(input: unknown) {
throw new Error(
"Continuum export has a continuation token; supply the complete paginated CLI output.",
);
- if (!("items" in document || "findingArn" in document))
+ if (!(
+ "items" in document ||
+ "findingArn" in document ||
+ "finding" in document
+ ))
throw new Error(
- "Expected a Continuum ListCodeFindings or GetCodeFinding response.",
+ "Expected a Continuum ListCodeFindings, GetCodeFinding, or finding with patch artifacts.",
);
const summary = "items" in document;
return {
@@ -170,6 +177,76 @@ function reportRows(input: unknown) {
};
}
+function isPatchCapture(value: unknown): value is Record<string, unknown> {
+ return isRecord(value) && !("findingArn" in value) && "finding" in value;
+}
+
+function readPatch(value: unknown) {
+ const artifact = record(value, "Continuum patch artifact");
+ const patch = requiredText(artifact["patch"], "Continuum patch content");
+ const sizeBytes = Buffer.byteLength(patch);
+ const patchSha256 = hash("sha256", patch);
+ if (
+ artifact["sizeBytes"] !== sizeBytes ||
+ artifact["patchSha256"] !== patchSha256
+ )
+ throw new Error(
+ "Continuum patch content does not match its sizeBytes or patchSha256.",
+ );
+ return {
+ artifactId: requiredText(
+ artifact["artifactId"],
+ "Continuum patch artifact ID",
+ ),
+ patch,
+ patchSha256,
+ sizeBytes,
+ ...(artifact["format"] !== undefined && {
+ format: requiredText(artifact["format"], "Continuum patch format"),
+ }),
+ ...(artifact["repositoryName"] !== undefined && {
+ repositoryName: requiredText(
+ artifact["repositoryName"],
+ "Continuum patch repository",
+ ),
+ }),
+ };
+}
+
+function projectPatches(
+ patches: ReturnType<typeof readPatch>[],
+ target: ExternalImportTarget,
+ project: (artifacts: object[]) => ExternalFinding["evidence"],
+) {
+ if (!patches.length || target === "local") return project(patches);
+ try {
+ return project(patches);
+ } catch {
+ // Complete patches can exceed the Cloud evidence budget.
+ }
+
+ // Reserve each artifact's lookup information, then include whole patches that fit.
+ const marker = { contentOmitted: "cloud_evidence_limit" };
+ const markerBytes = Buffer.byteLength(JSON.stringify(marker));
+ const sizes = patches.map(
+ ({ patch }) => Buffer.byteLength(JSON.stringify({ patch })) - markerBytes,
+ );
+ const projected = patches.map(({ patch, ...descriptor }, index) =>
+ sizes[index]! > 0 ? { ...descriptor, ...marker } : patches[index]!,
+ );
+ const result = project(projected);
+ let remaining =
+ CLOUD_EVIDENCE_BYTES - validateExternalEvidenceJson(result, target);
+ for (const [index, bytes] of sizes.entries()) {
+ if (bytes > 0 && bytes <= remaining) {
+ projected[index] = patches[index]!;
+ remaining -= bytes;
+ }
+ }
+ result.source_data!["patches"] = projected;
+ return result;
+}
+
function subcategoryCwe(row: Record<string, unknown>) {
return /^(CWE-[1-9]\d*):/u.exec(text(row["subCategory"]) ?? "")?.[1];
}
@@ -237,7 +314,21 @@ export function normalizeContinuumFindings(
const output = normalizeRecords(
rows,
(value) => {
- const row = record(value, "Continuum finding");
+ const capture = !summary && isPatchCapture(value) ? value : undefined;
+ const row = record(
+ capture ? capture["finding"] : value,
+ "Continuum finding",
+ );
+ const patches = capture
+ ? array(capture["patches"], "Continuum patches").map(readPatch)
+ : [];
+ if (
+ patches.length &&
+ !(text(row["createdIssueId"]) || text(row["duplicateOfIssueId"]))
+ )
+ throw new Error(
+ "Continuum patches require a finding linked to an issue.",
+ );
if (
row["type"] !== "CONTINUUM_CODE_VULN" &&
row["type"] !== "CUSTOMER_CODE_VULN"
@@ -321,19 +412,28 @@ export function normalizeContinuumFindings(
? { details: { ...evidence.details, weakness_ids: [namedCwe] } }
: undefined;
// Keep previously admissible evidence if an optional projection exceeds the Cloud budget.
- return validateEnrichedExternalEvidence(
- evidence,
- target,
- inferred ? { ...enrichment, ...inferred } : undefined,
- enrichment,
- packages.length && updatedAt !== null
- ? { source_updated_at: updatedAt }
- : undefined,
- inferred,
+ return projectPatches(patches, target, (artifacts) =>
+ validateEnrichedExternalEvidence(
+ artifacts.length
+ ? {
+ ...evidence,
+ source_data: { ...evidence.source_data, patches: artifacts },
+ }
+ : evidence,
+ target,
+ inferred ? { ...enrichment, ...inferred } : undefined,
+ enrichment,
+ packages.length && updatedAt !== null
+ ? { source_updated_at: updatedAt }
+ : undefined,
+ inferred,
+ ),
);
},
(value) => {
- const { arn, scope } = identity(value);
+ const { arn, scope } = identity(
+ !summary && isPatchCapture(value) ? value["finding"] : value,
+ );
scopes.add(scope);
return arn;
},
diff --git a/sdk/typescript/src/external-import-contract.ts b/sdk/typescript/src/external-import-contract.ts
index 902c37f08..85d799d51 100644
--- a/sdk/typescript/src/external-import-contract.ts
+++ b/sdk/typescript/src/external-import-contract.ts
@@ -503,7 +503,7 @@ function validateRawEvidence(
}
}
-const CLOUD_EVIDENCE_BYTES = 256 * 1024;
+export const CLOUD_EVIDENCE_BYTES = 256 * 1024;
function checkEvidenceSize(bytes: number): number {
if (bytes > CLOUD_EVIDENCE_BYTES)
throw new Error("Evidence exceeds the Cloud limit of 256 KiB.");
diff --git a/sdk/typescript/src/stored-finding-projection.ts b/sdk/typescript/src/stored-finding-projection.ts
index 0f1161ff1..dfac999e2 100644
--- a/sdk/typescript/src/stored-finding-projection.ts
+++ b/sdk/typescript/src/stored-finding-projection.ts
@@ -65,7 +65,10 @@ function* nativeReaders(
);
if (row.provider === "continuum" && isRecord(data["finding"])) {
// The list and detail APIs can return the same raw record with different SAST projections.
- yield (target) => normalizeContinuumFindings(data["finding"], url, target);
+ const detail = data["patches"]
+ ? { finding: data["finding"], patches: data["patches"] }
+ : data["finding"];
+ yield (target) => normalizeContinuumFindings(detail, url, target);
yield (target) =>
normalizeContinuumFindings({ items: [data["finding"]] }, url, target);
}
diff --git a/sdk/typescript/tests-ts/continuum-findings.test.ts b/sdk/typescript/tests-ts/continuum-findings.test.ts
index 791054e64..b830b245f 100644
--- a/sdk/typescript/tests-ts/continuum-findings.test.ts
+++ b/sdk/typescript/tests-ts/continuum-findings.test.ts
@@ -1,8 +1,10 @@
import { expect, test } from "bun:test";
+import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { gzipSync } from "node:zlib";
import { prepareNormalizedLocalImport } from "../src/external-findings-local.js";
import { normalizeContinuumFindings } from "../src/continuum-findings.js";
+import { projectStoredFinding } from "../src/stored-finding-projection.js";
import {
createAndReplayFinding,
localReportFixture,
@@ -85,6 +87,88 @@ test("a selected array retains the same evidence as separate GetCodeFinding resp
expect(normalize([first, first]).excluded).toHaveLength(2);
});
+function patchArtifact(artifactId: string, patch: string) {
+ return {
+ artifactId,
+ format: "GIT_DIFF",
+ repositoryName: "project",
+ patchSha256: createHash("sha256").update(patch).digest("hex"),
+ sizeBytes: Buffer.byteLength(patch),
+ patch,
+ };
+}
+
+test("patch captures retain the native finding, exact patch bytes and AWS descriptors", () => {
+ const finding = { ...continuumDetail(), createdIssueId: "oneissue" };
+ const patch = patchArtifact(
+ "firstpatch",
+ "--- a/src/example.ts\n+++ b/src/example.ts\n@@ -1 +1 @@\n-// example\n+// café\n",
+ );
+ const plain = continuumSummary("two");
+ const prior = normalize(finding).findings[0]!;
+ const captured = normalize([{ finding, patches: [patch] }, plain]);
+ expect(captured.excluded).toEqual([]);
+ expect(captured.findings).toEqual([
+ {
+ ...prior,
+ evidence: {
+ ...prior.evidence,
+ source_data: { ...prior.evidence.source_data, patches: [patch] },
+ },
+ },
+ ...normalize(plain).findings,
+ ]);
+ expect(normalize({ finding, patches: [] })).toEqual(normalize(finding));
+});
+
+test("a broken patch capture excludes only its own finding", () => {
+ const detail = continuumDetail();
+ const linked = { ...detail, duplicateOfIssueId: "otherissue" };
+ const patch = patchArtifact("firstpatch", "+ok\n");
+ const plain = continuumSummary("two");
+ for (const broken of [
+ { finding: detail, patches: [patch] },
+ {
+ finding: linked,
+ patches: [{ ...patch, sizeBytes: patch.sizeBytes + 1 }],
+ },
+ { finding: linked, patches: [{ ...patch, patch: "+no\n" }] },
+ ]) {
+ const result = normalize([broken, plain]);
+ expect(result.excluded).toMatchObject([{ position: 1 }]);
+ expect(result.findings).toEqual(normalize(plain).findings);
+ }
+});
+
+test("Cloud publication of a stored capture keeps fitting patches and identifies oversized patch bodies", () => {
+ const finding = { ...continuumDetail(), duplicateOfIssueId: "otherissue" };
+ const big = patchArtifact("bigpatch", "+example\n".repeat(32 * 1024));
+ const small = patchArtifact("smallpatch", "+ok\n");
+ const input = { finding, patches: [big, small] };
+ const local = normalizeContinuumFindings(input, continuumRepository, "local");
+ expect(local.excluded).toEqual([]);
+ const stored = local.findings[0]!;
+ expect(stored.evidence.source_data?.["patches"]).toEqual([big, small]);
+
+ const cloud = normalize(input);
+ expect(cloud.excluded).toEqual([]);
+ const { patch: _, ...descriptor } = big;
+ expect(cloud.findings[0]!.evidence.source_data?.["patches"]).toEqual([
+ { ...descriptor, contentOmitted: "cloud_evidence_limit" },
+ small,
+ ]);
+ expect(
+ projectStoredFinding(
+ {
+ provider: "continuum",
+ sourceFindingId: stored.source_finding_id,
+ evidence: stored.evidence,
+ },
+ [],
+ ).findings,
+ ).toEqual(cloud.findings);
+});
+
test("preserves dependency and posture evidence without classifying it as a code flaw", () => {
const summary = continuumSummary();
const pkg = {
@@ -238,33 +322,42 @@ test("Cloud projects packages within its limits and retains all AWS package evid
expect(local.findings[0]!.evidence.packages).toHaveLength(102);
});
-test("a Cloud finding that fits with native packages alone still imports", () => {
- const finding = {
- ...continuumSummary(),
- affectedPackages: [
- { name: "example", version: "1.0.0", packageManager: "npm" },
- ],
- padding: "",
- };
- const base = normalize(finding).findings[0]!.evidence;
- base.packages = [];
- base.source_updated_at = null;
- const bytes = Buffer.byteLength(JSON.stringify(base));
- finding.padding = "x".repeat(256 * 1024 - bytes);
- const result = normalize(finding);
- expect(result.excluded).toEqual([]);
- expect(result.findings[0]!.evidence.packages).toEqual([]);
- expect(result.findings[0]!.evidence.source_data?.["finding"]).toEqual(
- finding,
- );
- finding.padding = finding.padding.slice(10);
- const withTimestamp = normalize(finding);
- expect(withTimestamp.findings[0]!.evidence).toMatchObject({
- packages: [],
- source_updated_at: Date.parse(finding.statusUpdatedAt) / 1000,
- source_data: { finding },
- });
-});
+test.each(["plain finding", "patch capture"])(
+ "Cloud imports a %s that fits only without the derived package list",
+ (format) => {
+ const finding = {
+ ...continuumSummary(),
+ createdIssueId: "oneissue",
+ affectedPackages: [
+ { name: "example", version: "1.0.0", packageManager: "npm" },
+ ],
+ padding: "",
+ };
+ const patches = [patchArtifact("firstpatch", "+checkedExample(input)\n")];
+ const report = format === "patch capture" ? { finding, patches } : finding;
+ const base = normalize(report).findings[0]!.evidence;
+ base.packages = [];
+ base.source_updated_at = null;
+ const bytes = Buffer.byteLength(JSON.stringify(base));
+ finding.padding = "x".repeat(256 * 1024 - bytes);
+ const result = normalize(report);
+ expect(result.excluded).toEqual([]);
+ expect(result.findings[0]!.evidence.packages).toEqual([]);
+ expect(result.findings[0]!.evidence.source_data?.["finding"]).toEqual(
+ finding,
+ );
+ expect(result.findings[0]!.evidence.source_data?.["patches"]).toEqual(
+ format === "patch capture" ? patches : undefined,
+ );
+ finding.padding = finding.padding.slice(10);
+ const withTimestamp = normalize(report);
+ expect(withTimestamp.findings[0]!.evidence).toMatchObject({
+ packages: [],
+ source_updated_at: Date.parse(finding.statusUpdatedAt) / 1000,
+ source_data: { finding },
+ });
+ },
+);
test("unsafe paths stay in native evidence without becoming checkout locations", () => {
const detail = {
@@ -314,7 +407,12 @@ test("local replay enriches one unassessed occurrence when the detailed record a
try {
await fixture.writeJson({ items: [continuumSummary()] });
const previous = await createAndReplayFinding(fixture);
- await writeFile(fixture.file, gzipSync(JSON.stringify(continuumDetail())));
+ const finding = { ...continuumDetail(), createdIssueId: "oneissue" };
+ const patches = [patchArtifact("firstpatch", "+checkedExample(input)\n")];
+ await writeFile(
+ fixture.file,
+ gzipSync(JSON.stringify({ finding, patches })),
+ );
const updated = await updateStoredFinding(fixture, previous);
const normalized = normalize(continuumDetail());
normalized.findings[0]!.evidence.details!.repository!.url =
@@ -328,6 +426,7 @@ test("local replay enriches one unassessed occurrence when the detailed record a
).rejects.toThrow(/repository|remote/i);
expect(updated.provider).toBe("continuum");
expect(updated.evidence.details?.scanner_verdict).toBe("TRUE_POSITIVE");
+ expect(updated.evidence.source_data?.["patches"]).toEqual(patches);
await expect(
fixture.prepare({
sourceRepositoryUrl: "https://github.com/example/other",