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

fix(cli): simplify finding imports and protect export files (#2595)

Michael D'Angelo67ee64c0bce9
diff --git a/docs/scanner-imports/README.md b/docs/scanner-imports/README.md
index ac61b976f..ca4f926b6 100644
--- a/docs/scanner-imports/README.md
+++ b/docs/scanner-imports/README.md
@@ -5,11 +5,11 @@ workbench or send a supported report to Codex Security Cloud.
## Choose your input
-| Starting point | Command |
-| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Saved vendor report | `codex-security publish findings FILE --provider PROVIDER --source-key KEY --repository . --to local --dry-run` previews the evidence. Remove `--dry-run` to save it. |
-| Codex Security findings export | `codex-security scan import --csv FILE` or `--json FILE` saves a completed scan in local history. Use `--format json` to select JSON output. |
-| Live provider | `codex-security import --help` lists the GitHub, Semgrep, Snyk and Sonar collectors. The Sonar collector can also replay its saved capture. |
+| Starting point | Command |
+| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Saved vendor report | `codex-security publish findings FILE --provider PROVIDER --source-key KEY --repository . --to local --dry-run` previews the evidence. Remove `--dry-run` to save it. |
+| Codex Security findings export | `codex-security scan import FILE` saves findings from a .csv or .json file as a completed scan. Use `--input-format` for other filenames and `--json` for JSON output. |
+| Live provider | `codex-security import --help` lists the GitHub, Semgrep, Snyk and Sonar collectors. The Sonar collector can also replay its saved capture. |
## Choose your scanner
diff --git a/docs/scanner-imports/semgrep.md b/docs/scanner-imports/semgrep.md
index 939ff4bbe..c57eb066e 100644
--- a/docs/scanner-imports/semgrep.md
+++ b/docs/scanner-imports/semgrep.md
@@ -423,8 +423,8 @@ leaves earlier exports available for replay.
```sh
report=$(mktemp ./semgrep-backlog.XXXXXX) &&
- codex-security import semgrep example/project --semgrep-deployment example \
- --semgrep-ref refs/heads/topic --semgrep-product sast --format json > "$report" &&
+ codex-security import semgrep example/project --deployment example \
+ --ref refs/heads/topic --semgrep-product sast --format json > "$report" &&
codex-security publish findings "$report" --to local --repository /path/to/project \
--provider semgrep --source-key example/project/topic --dry-run --format json
```
diff --git a/docs/scanner-imports/snyk.md b/docs/scanner-imports/snyk.md
index 70092ec1d..cbf005107 100644
--- a/docs/scanner-imports/snyk.md
+++ b/docs/scanner-imports/snyk.md
@@ -121,7 +121,7 @@ example saves a fresh report there and imports it into the checkout at `./projec
```sh
report=$(mktemp ./snyk-issues.XXXXXX) &&
- codex-security import snyk PROJECT_ID --snyk-org ORG_ID \
+ codex-security import snyk PROJECT_ID --org ORG_ID \
--source-repository-url https://github.com/example/project \
--format json > "$report" &&
codex-security publish findings "$report" --to local --provider snyk \
diff --git a/docs/scanner-imports/sonar.md b/docs/scanner-imports/sonar.md
index b41ccd45e..c31a0538f 100644
--- a/docs/scanner-imports/sonar.md
+++ b/docs/scanner-imports/sonar.md
@@ -1,7 +1,7 @@
# Import SonarQube Cloud findings
Use `import sonar` to collect security issues for one project and branch or
-pull request. A live `--dry-run` writes a private capture and returns its path.
+pull request. A `--dry-run` with either live issues or a saved capture writes a private evidence copy and returns its path. Pass that path to confirm the reviewed selection.
Replay it without signing in to Sonar. If you already have issue-search JSON,
[preview the native export](#use-a-native-json-export).
diff --git a/plugins/codex-security/scripts/finalize_scan_contract.py b/plugins/codex-security/scripts/finalize_scan_contract.py
index 9b55b1d47..00c9d4467 100644
--- a/plugins/codex-security/scripts/finalize_scan_contract.py
+++ b/plugins/codex-security/scripts/finalize_scan_contract.py
@@ -2977,7 +2977,14 @@ def _is_sealed_artifact(scan_dir: Path, relative_output: str, artifact_paths: li
return False
-def write_export_output(scan_dir: Path, output: Path, export_format: str, contents: bytes) -> None:
+def write_export_output(
+ scan_dir: Path,
+ output: Path,
+ export_format: str,
+ contents: bytes,
+ *,
+ replace_existing: bool = True,
+) -> None:
output_paths = {**EXPORT_PATHS, "md": THREAT_MODEL_EXPORT_PATH}
if export_format not in output_paths:
raise ContractError(f"unsupported export format: {export_format}")
@@ -3008,6 +3015,7 @@ def write_export_output(scan_dir: Path, output: Path, export_format: str, conten
output.name,
contents,
external_name=True,
+ replace_existing=replace_existing,
owner_read_write=export_format == "md",
)
return
@@ -3032,7 +3040,11 @@ def write_export_output(scan_dir: Path, output: Path, export_format: str, conten
f"{export_format.upper()} output path cannot overwrite a sealed scan artifact"
)
write_scan_local_bytes(
- scan_dir, relative_output, contents, owner_read_write=export_format == "md"
+ scan_dir,
+ relative_output,
+ contents,
+ owner_read_write=export_format == "md",
+ replace_existing=replace_existing,
)
@@ -3365,6 +3377,7 @@ def main() -> int:
parser.add_argument("--export-format", choices=[*sorted(EXPORT_PATHS), "md"])
parser.add_argument("--avit-template", type=Path)
parser.add_argument("--export-output", type=Path)
+ parser.add_argument("--no-clobber", action="store_true")
parser.add_argument("--export-metadata", action="store_true")
parser.add_argument("--describe-threat-model", action="store_true")
parser.add_argument("--write-threat-model", action="store_true")
@@ -3426,7 +3439,20 @@ def main() -> int:
if args.export_output is None:
sys.stdout.buffer.write(contents)
else:
- write_export_output(args.scan_dir, args.export_output, args.export_format, contents)
+ try:
+ write_export_output(
+ args.scan_dir,
+ args.export_output,
+ args.export_format,
+ contents,
+ replace_existing=not args.no_clobber,
+ )
+ except FileExistsError:
+ if not args.no_clobber:
+ raise
+ raise ContractError(
+ f"{args.export_output} already exists. Use --output FILE to choose or replace a file."
+ ) from None
if args.export_metadata:
sys.stdout.buffer.write(
_json_bytes({**description, "path": str(args.export_output.absolute())})
diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.md
index 6dd28884e..d521a5e3c 100644
--- a/plugins/codex-security/skills/publish-findings/SKILL.md
+++ b/plugins/codex-security/skills/publish-findings/SKILL.md
@@ -82,7 +82,7 @@ Use a stable Wiz tenant/finding namespace as `--source-key`; a project filter do
## Snyk findings
-For an existing monitored Open Source or Code project, follow the [Snyk Issues API import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/snyk.md#existing-issues-from-snyk). With a read-authorized `SNYK_TOKEN`, run `codex-security import snyk PROJECT_ID --snyk-org ORG_ID --source-repository-url URL --format json`. Add `--snyk-product code` for a Code project and `--snyk-api-origin` for a regional deployment. Save the complete successful JSON output, preview with `publish findings --provider snyk` and the requested `--to local` or `--to cloud` destination, then confirm the import.
+For an existing monitored Open Source or Code project, follow the [Snyk Issues API import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/snyk.md#existing-issues-from-snyk). With a read-authorized `SNYK_TOKEN`, run `codex-security import snyk PROJECT_ID --org ORG_ID --source-repository-url URL --format json`. Add `--snyk-product code` for a Code project and `--snyk-api-origin` for a regional deployment. Save the complete successful JSON output, preview with `publish findings --provider snyk` and the requested `--to local` or `--to cloud` destination, then confirm the import.
Prefer the [official Snyk Codex plugin](https://github.com/snyk/studio-recipes/tree/main/plugins/codex) when available. Ask its `snyk-findings-export` skill for **SCA only from the repository’s Git root** and save the `snyk-findings-export/v1` bundle. It scans the current workspace through local MCP; it cannot list existing platform projects or retrieve earlier findings. Do not substitute a fresh scan for a request to read a platform backlog. Authentication, relevant Snyk access and the project's package tooling are required.
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index a6c73480f..5c0738142 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -770,16 +770,18 @@ from the config directory; scope paths resolve from the repository.
### Import findings as a saved scan
```bash
-codex-security scan import --csv /path/to/findings.csv
-codex-security scan import --json /path/to/findings.json --format json
-codex-security scan import --csv /path/to/findings.csv --dry-run
+codex-security scan import /path/to/findings.csv
+codex-security scan import /path/to/findings.json --json
+codex-security scan import /path/to/report --input-format csv --dry-run
```
Supply exactly one input. CSV follows the
[findings template](https://github.com/openai/codex-security/blob/main/examples/findings.csv).
JSON accepts a complete `codex-security.findings` document or
-`{ "findings": [...] }` matching the findings schema. For this command, `--json`
-selects the input file; use `--format json` for JSON output. The input must be a
+`{ "findings": [...] }` matching the findings schema. The CLI infers the format from a `.csv` or `.json` suffix.
+Use `--input-format csv|json` to override it. Put `--json` after the filename
+to request JSON output. Existing scripts using `--csv FILE` or `--json FILE`
+can continue to select the input that way. The input must be a
regular file with no symlinks or directory junctions in its path.
Each import creates a completed scan in local history, retains the input under
@@ -1595,7 +1597,7 @@ SARIF compatibility, and the local preview.
## Import SonarQube Cloud issues
-`import sonar --dry-run` writes a private capture and returns its path. Preview
+`import sonar --dry-run` writes a private evidence copy for both live and saved inputs and returns its path. Preview
that capture for the intended destination before confirming. A Cloud confirmation
saves the issues locally and publishes them. Use `--full-output` with
`--format json` or `--format jsonl` for a structured result.
@@ -1807,8 +1809,8 @@ A dedicated login using automatic storage can publish if Codex Security
recorded the native file fallback. An unverified file can belong to another
account, so Cloud publication requires an explicit file store for an ambient login.
-Use a positional scan directory or repeated `--scan-dir PATH` for artifacts
-outside history. Each must contain one completed sealed scan, not a bulk-run
+Use `publish scan DIR --to cloud` for one directory outside history. For
+multiple directories, repeat `--scan-dir PATH`. Each must contain one completed sealed scan, not a bulk-run
directory or `results.jsonl`. Do not mix directories with `--scan`.
Cloud also accepts exported CSV:
@@ -1856,7 +1858,7 @@ codex-security publish check /path/to/completed-scan \
--linear-team TEAM_ID --json
```
-`publish check` defaults to `--to linear`. It verifies artifacts and recorded publications. With an API key,
+`publish check` verifies scan artifacts and recorded Linear publications. With an API key,
it also checks authentication and destination access. It does not test issue
creation; connected-app access is reported as `not-checked`.
@@ -2345,6 +2347,10 @@ must already exist.
SARIF is the default format, and `./results.sarif` is the default output path.
Use `--export-format json` or `--export-format csv` to choose another format.
+An existing default output file is preserved. Pass `--output FILE` to choose
+a filename or explicitly replace it. Use `--output -` to pipe the complete
+artifact. Response filters, token controls, and `--full-output` require a
+command that returns a formatted response.
To select a saved scan by its ID and export JSON, run:
```bash
diff --git a/sdk/typescript/src/artifact-export.ts b/sdk/typescript/src/artifact-export.ts
index 49d3311ee..24e8b761b 100644
--- a/sdk/typescript/src/artifact-export.ts
+++ b/sdk/typescript/src/artifact-export.ts
@@ -47,6 +47,7 @@ export interface ArtifactExportArguments {
pythonPath?: string;
signal?: AbortSignal;
includeMetadata?: boolean;
+ noClobber?: boolean;
}
export type ExportArtifactOptions = {
@@ -259,6 +260,7 @@ export async function runArtifactExport(
: ["--export-output", arguments_.output]),
...(source === undefined ? [] : ["--source-root", source.path]),
...(arguments_.includeMetadata ? ["--export-metadata"] : []),
+ ...(arguments_.noClobber ? ["--no-clobber"] : []),
],
{
pythonPath: arguments_.pythonPath,
diff --git a/sdk/typescript/src/cli-help.ts b/sdk/typescript/src/cli-help.ts
index d8f7cb790..f7e7482f8 100644
--- a/sdk/typescript/src/cli-help.ts
+++ b/sdk/typescript/src/cli-help.ts
@@ -226,7 +226,7 @@ function globalRows(rows: Row[], command: string): Row[] {
) {
formats.label = formats.label.replace("|md", "");
}
- if (formats && command !== "scan import") {
+ if (formats) {
visible.push({
label: "--json",
description: "Shorthand for --format json.",
@@ -329,7 +329,11 @@ export function formatCliHelp(text: string, columns = 80): string {
);
} else if (title === "Options:") {
const options = parseRows(lines)
- .filter((row) => command !== "publish scan" || rowName(row) !== "csv")
+ .filter(
+ (row) =>
+ !(command === "publish scan" && rowName(row) === "csv") &&
+ !(command === "publish check" && rowName(row) === "to"),
+ )
.map((row) => optionRow(row, command));
const rows = options.filter(
(row) => !row.description.startsWith("[deprecated]"),
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index c6553522a..fc11e3275 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -45,6 +45,7 @@ import { tmpdir } from "node:os";
import {
basename,
dirname,
+ extname,
isAbsolute,
join,
parse,
@@ -3444,9 +3445,9 @@ export async function main(
description: "Publish findings from a completed scan.",
examples: [
{
+ args: { scanDir: "../scan-results" },
options: {
to: "linear",
- scan: ["latest"],
linearTeam: "TEAM_ID",
dryRun: true,
},
@@ -3489,7 +3490,7 @@ export async function main(
.array(optionValue("--scan-dir"))
.default([])
.describe(
- "External completed scan directory; Linear and custom accept one scan.",
+ "Use the positional directory for one scan. Repeat this flag for destinations that accept multiple scans.",
),
// Cloud remains an internal destination, omitted from public discovery.
to: z
@@ -4470,7 +4471,7 @@ export async function main(
examples: [
{
args: { scanDir: "../scan-results" },
- options: { to: "linear", linearTeam: "TEAM_ID" },
+ options: { linearTeam: "TEAM_ID" },
},
],
hint: "Use publish scan --dry-run to preview a publication offline.",
@@ -4710,7 +4711,7 @@ export async function main(
usage: [
{
args: { project: true },
- options: { snykOrg: true, sourceRepositoryUrl: true },
+ options: { org: true, sourceRepositoryUrl: true },
suffix: "[options]",
},
],
@@ -4720,7 +4721,7 @@ export async function main(
{
args: { project: "PROJECT_ID" },
options: {
- snykOrg: "ORG_ID",
+ org: "ORG_ID",
sourceRepositoryUrl: "https://github.com/example/project",
},
},
@@ -4731,7 +4732,9 @@ export async function main(
project: z.string().min(1).describe("Snyk project ID."),
}),
options: z.object({
- snykOrg: optionValue("--snyk-org").describe("Snyk organization ID."),
+ org: optionValue("--org").describe(
+ "Snyk organization ID (alias: --snyk-org).",
+ ),
snykProduct: z
.enum(["open-source", "code"])
.default("open-source")
@@ -4771,7 +4774,7 @@ export async function main(
collectSnykIssues(
{
projectId: args.project,
- organizationId: options.snykOrg,
+ organizationId: options.org,
product: options.snykProduct,
apiOrigin: options.snykApiOrigin,
sourceRepositoryUrl: options.sourceRepositoryUrl,
@@ -4786,7 +4789,7 @@ export async function main(
usage: [
{
args: { project: true },
- options: { semgrepDeployment: true, semgrepRef: true },
+ options: { deployment: true, ref: true },
suffix: "[options]",
},
],
@@ -4796,8 +4799,8 @@ export async function main(
{
args: { project: "owner/project" },
options: {
- semgrepDeployment: "DEPLOYMENT",
- semgrepRef: "refs/heads/main",
+ deployment: "DEPLOYMENT",
+ ref: "refs/heads/main",
},
},
],
@@ -4810,11 +4813,11 @@ export async function main(
.describe("Exact Semgrep project name, typically owner/repository."),
}),
options: z.object({
- semgrepDeployment: optionValue("--semgrep-deployment").describe(
- "Semgrep deployment slug.",
+ deployment: optionValue("--deployment").describe(
+ "Semgrep deployment slug (alias: --semgrep-deployment).",
),
- semgrepRef: optionValue("--semgrep-ref").describe(
- "Exact source ref, for example refs/heads/main.",
+ ref: optionValue("--ref").describe(
+ "Exact source ref, for example refs/heads/main (alias: --semgrep-ref).",
),
semgrepProduct: z
.enum(SEMGREP_PLATFORM_PRODUCTS)
@@ -4852,8 +4855,8 @@ export async function main(
collectSemgrepPlatformFindings(
{
project: args.project,
- deployment: options.semgrepDeployment,
- ref: options.semgrepRef,
+ deployment: options.deployment,
+ ref: options.ref,
product: options.semgrepProduct,
sourceRepositoryUrl: options.sourceRepositoryUrl,
signal,
@@ -4874,7 +4877,7 @@ export async function main(
{ options: { sonarProject: "PROJECT_KEY", dryRun: true } },
{ args: { capture: "../reports/sonar.json" } },
],
- hint: "Uses the active sonar CLI login. --to cloud also publishes the locally imported selection to the connected Cloud repository. --dry-run saves a live capture for review without importing findings.",
+ hint: "Uses the active sonar CLI login. --to cloud also publishes the locally imported selection to the connected Cloud repository. --dry-run saves a private evidence copy for live and saved inputs and prints its path for confirmation.",
destructive: true,
args: z.object({
capture: z
@@ -4916,7 +4919,7 @@ export async function main(
.boolean()
.default(false)
.describe(
- "Preview destinations and evidence without storing or publishing findings.",
+ "Save a private evidence copy and preview the selected findings and destinations.",
),
yes: z
.boolean()
@@ -5612,20 +5615,22 @@ export async function main(
: finishScanCommand(outcome, format, incurError);
},
}).command("import", {
- usage: [{ suffix: "(--csv FILE | --json FILE) [options]" }],
+ usage: [{ suffix: "FILE [options]" }],
description:
"Save CSV or JSON findings as a completed scan without security analysis.",
destructive: true,
+ args: z.object({
+ file: z
+ .string({ error: "Provide a findings file to import." })
+ .min(1)
+ .describe("Findings file to import."),
+ }),
options: z
.object({
- csv: optionValue("--csv")
- .optional()
- .describe("Findings CSV in the codex-security export format."),
- json: optionValue("--json")
+ inputFormat: z
+ .enum(["csv", "json"])
.optional()
- .describe(
- "Findings JSON document or object with a findings array.",
- ),
+ .describe("Input format (default: inferred from .csv or .json)."),
outputDir: optionValue("--output-dir")
.optional()
.describe(
@@ -5640,30 +5645,35 @@ export async function main(
.default(false)
.describe("Validate the input without saving a scan."),
})
- .refine(
- (options) =>
- Number(options.csv !== undefined) +
- Number(options.json !== undefined) ===
- 1,
- { message: "Provide exactly one of --csv FILE or --json FILE." },
- )
.refine(
(options) =>
!options.archiveExisting || options.outputDir !== undefined,
{ message: "--archive-existing requires --output-dir." },
- )
- .meta({ oneOf: [{ required: ["csv"] }, { required: ["json"] }] }),
+ ),
examples: [
- { options: { csv: "findings.csv" } },
- { options: { json: "findings.json" } },
+ { args: { file: "findings.csv" } },
+ { args: { file: "report" }, options: { inputFormat: "json" } },
],
- hint: "Each input row is retained, including duplicates. --json selects the input file; use --format json for JSON output.",
+ hint: "Each input row is retained, including duplicates. Use FILE --json for JSON output. Legacy --csv FILE and --json FILE still select the input format.",
output: z.record(z.string(), z.unknown()).optional(),
- async run({ options, format, error: incurError }) {
+ async run({ args, options, format, error: incurError }) {
const directory = dependencies.currentDirectory();
+ const inputFormat =
+ options.inputFormat ?? extname(args.file).slice(1).toLowerCase();
+ if (inputFormat !== "csv" && inputFormat !== "json") {
+ exitCode = 2;
+ const message =
+ "Cannot infer input format. Use --input-format csv or --input-format json.";
+ errorOutput.write(`codex-security: ${message}\n`);
+ return incurError({
+ code: "INVALID_INPUT_FORMAT",
+ message,
+ exitCode,
+ });
+ }
const outcome = await runImport({
- sourcePath: resolveCliPath(directory, options.csv ?? options.json!),
- format: options.csv === undefined ? "json" : "csv",
+ sourcePath: resolveCliPath(directory, args.file),
+ format: inputFormat,
outputDir:
options.outputDir === undefined
? undefined
@@ -6824,6 +6834,7 @@ export async function main(
" codex-security export --export-format json --output -\n" +
" codex-security export ../scan-results --export-format csv\n" +
" codex-security export --artifact threat-model --output -\n\n" +
+ "Implicit filenames: results.sarif, findings.json, findings.csv, servicenow-avit.csv, or threatmodel.md.\n" +
"Use --export-format for artifact format. The global --format option controls\n" +
"framework output such as --schema; it does not change exported files.",
destructive: true,
@@ -6858,7 +6869,7 @@ export async function main(
output: optionValue("--output")
.optional()
.describe(
- "FILE or '-' for stdout (default: results.sarif, findings.json, findings.csv, servicenow-avit.csv, or threatmodel.md).",
+ "FILE to replace or '-' for raw stdout. Default filenames are created only if absent.",
),
sourceRoot: optionValue("--source-root")
.optional()
@@ -6883,6 +6894,34 @@ export async function main(
async run({ args, options }) {
rawExportOutput = options.output === "-";
try {
+ if (rawExportOutput) {
+ const responseFlag = frameworkFlags.filters.length
+ ? "--filter-output"
+ : frameworkFlags.fullOutput
+ ? "--full-output"
+ : frameworkFlags.tokenArguments[0];
+ if (responseFlag) {
+ throw new CodexSecurityError(
+ `${responseFlag} cannot be used with raw artifact stdout. Omit it to pipe the complete artifact.`,
+ );
+ }
+ const markdown =
+ options.artifact === "threat-model" ||
+ options.exportFormat === "md";
+ const csv =
+ options.exportFormat === "csv" ||
+ options.exportFormat === "servicenow-avit";
+ const expectedFormat = markdown ? "md" : csv ? undefined : "json";
+ const incompatible = frameworkFlags.formats.find(
+ (value) => value !== expectedFormat,
+ );
+ if (incompatible !== undefined) {
+ const label = markdown ? "Markdown" : csv ? "CSV" : "JSON";
+ throw new CodexSecurityError(
+ `${label} stdout cannot be combined with --format ${incompatible}. Omit the response format to pipe the complete artifact.`,
+ );
+ }
+ }
const currentDirectory = dependencies.currentDirectory();
if (args.scanDir !== undefined && options.scan !== undefined) {
throw new CodexSecurityError(
@@ -6937,6 +6976,7 @@ export async function main(
artifact: options.artifact,
format,
output: outputPath,
+ noClobber: options.output === undefined,
sourceRoot,
avitTemplate: options.avitTemplate,
pythonPath: options.python,
@@ -8078,6 +8118,13 @@ export async function main(
const verbIndex = firstNonGlobal(argv, commandIndex + 1);
let following = argv[verbIndex];
const scanImport = command === "scan" && following === "import";
+ const importArgs = normalizeImportArguments(
+ argv,
+ verbIndex,
+ command,
+ following,
+ );
+ argv = importArgs.args;
if (
command === "scan" &&
!scanImport &&
@@ -8127,6 +8174,7 @@ export async function main(
if (mixedAction) return `${actionFlags.join(" and ")} must be used alone.`;
if (command === undefined && literalArgs.length)
return "Select a command before --.";
+ if (importArgs.error) return importArgs.error;
if (frameworkFlags.argumentError) return frameworkFlags.argumentError;
if (command === undefined) return undefined;
if (!entry) {
@@ -8190,31 +8238,6 @@ export async function main(
) {
return `${command} does not support noninteractive JSON output; run it without --json, --format json, or --format jsonl.`;
}
- if (command === "export" && structuredOutput && !inspection) {
- const hasValue = (flag: string, value: string) =>
- argv.some(
- (arg, index) =>
- arg === `${flag}=${value}` ||
- (arg === flag && argv[index + 1] === value),
- );
- if (hasValue("--output", "-")) {
- if (
- ["csv", "servicenow-avit"].some(
- (format) =>
- hasValue("--export-format", format) ||
- hasValue("--exportFormat", format),
- )
- ) {
- return "CSV stdout cannot be combined with JSON output; write CSV to a file or omit --json.";
- }
- if (
- hasValue("--artifact", "threat-model") ||
- hasValue("--export-format", "md")
- ) {
- return "Markdown stdout cannot be combined with JSON output; write Markdown to a file or omit --json.";
- }
- }
- }
if (command === "scan" && !inspection) {
if (frameworkFlags.filters.length) {
return "--filter-output is not supported for scan results.";
@@ -8275,15 +8298,9 @@ export async function main(
return `Invalid boolean value for ${option}: ${diagnosticValue(value.slice(equals + 1))}. Use ${option}, ${option}=true, or ${option}=false.`;
}
}
- if (
- equals >= 0 ||
- (!valueOptions.has(canonicalOption) &&
- !(scanImport && option === "--json"))
- )
- continue;
+ if (equals >= 0 || !valueOptions.has(canonicalOption)) continue;
const next = argv[index + 1];
if (next === undefined || next.startsWith("--") || next === "-h") {
- if (scanImport && option === "--json" && inspection) continue;
return `Missing value for flag: ${option}`;
}
index += 1;
@@ -8320,10 +8337,7 @@ export async function main(
return `Unexpected positional argument for ${command}${subcommand === undefined ? "" : ` ${subcommand}`}.${hint}`;
}
}
- const frameworkFlags = parseFrameworkArguments(
- argv,
- scanImport ? verbIndex + 1 : argv.length,
- );
+ const frameworkFlags = parseFrameworkArguments(argv);
const frameworkArgv = frameworkFlags.args;
const { jsonFormat } = frameworkFlags;
const policyFullOutput =
@@ -8967,10 +8981,70 @@ function firstNonGlobal(argv: readonly string[], start: number): number {
return index;
}
-function parseFrameworkArguments(
+/** Translate historical input flags only within their original command. */
+function normalizeImportArguments(
argv: readonly string[],
- firstImportOption: number,
-) {
+ verbIndex: number,
+ command: string | undefined,
+ subcommand: string | undefined,
+): { args: readonly string[]; error?: string } {
+ const scanImport = command === "scan" && subcommand === "import";
+ const providerAliases: Record<string, string> =
+ command === "import" && subcommand === "semgrep"
+ ? { "--semgrep-deployment": "--deployment", "--semgrep-ref": "--ref" }
+ : command === "import" && subcommand === "snyk"
+ ? { "--snyk-org": "--org" }
+ : {};
+ if (!scanImport && Object.keys(providerAliases).length === 0)
+ return { args: argv };
+ const args = argv.slice(0, verbIndex + 1);
+ const seen = new Map<string, string>();
+ for (let index = args.length; index < argv.length; index++) {
+ const token = argv[index]!;
+ if (token === "--") {
+ args.push(...argv.slice(index));
+ break;
+ }
+ const equals = token.indexOf("=");
+ const name = equals < 0 ? token : token.slice(0, equals);
+ const flag = name.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase());
+ let value = equals < 0 ? argv[index + 1] : token.slice(equals + 1);
+ let canonical = providerAliases[flag] ?? flag;
+ if (scanImport && (flag === "--csv" || flag === "--json")) {
+ if (
+ equals < 0 &&
+ (value === undefined || value.startsWith("--") || value === "-h")
+ ) {
+ if (flag === "--csv")
+ return { args: argv, error: "Missing value for flag: --csv" };
+ args.push(token);
+ continue;
+ }
+ if (!value) return { args: argv, error: `${flag} must not be empty.` };
+ args.push(value.startsWith("-") ? "./" + value : value);
+ if (equals < 0) index++;
+ canonical = "--input-format";
+ value = flag.slice(2);
+ args.push(canonical + "=" + value);
+ } else if (Object.hasOwn(providerAliases, flag)) {
+ args.push(canonical + (equals < 0 ? "" : token.slice(equals)));
+ } else {
+ args.push(token);
+ }
+ if (
+ value !== undefined &&
+ (canonical === "--input-format" ||
+ Object.values(providerAliases).includes(canonical))
+ ) {
+ if (seen.has(canonical) && seen.get(canonical) !== value)
+ return { args: argv, error: `Conflicting values for ${canonical}.` };
+ seen.set(canonical, value);
+ }
+ }
+ return { args };
+}
+
+function parseFrameworkArguments(argv: readonly string[]) {
const args: string[] = [];
const formats: string[] = [];
const filters: (string | undefined)[] = [];
@@ -8980,18 +9054,6 @@ function parseFrameworkArguments(
for (let index = 0; index < argv.length; index++) {
const argument = argv[index]!;
const next = argv[index + 1];
- if (
- index >= firstImportOption &&
- argument === "--json" &&
- next !== undefined &&
- !next.startsWith("--") &&
- next !== "-h"
- ) {
- // Incur accepts the import's JSON input in the equals form.
- args.push(`--json=${next}`);
- index++;
- continue;
- }
const equals = argument.indexOf("=");
const flag = equals < 0 ? argument : argument.slice(0, equals);
if (!FRAMEWORK_VALUE_OPTIONS.has(flag)) {
@@ -9104,12 +9166,7 @@ function cliValueOptions(
for (const [name, schema] of Object.entries(
z.toJSONSchema(command.options, { io: "input" }).properties ?? {},
)) {
- // Bare --json is the framework output shortcut, except on scan import.
- if (
- name === "json" ||
- (typeof schema === "object" && schema.type === "boolean")
- )
- continue;
+ if (typeof schema === "object" && schema.type === "boolean") continue;
options.add(
`--${name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`,
);
diff --git a/sdk/typescript/tests-ts/cli-export.test.ts b/sdk/typescript/tests-ts/cli-export.test.ts
index 1c0489e7e..b3540ec2a 100644
--- a/sdk/typescript/tests-ts/cli-export.test.ts
+++ b/sdk/typescript/tests-ts/cli-export.test.ts
@@ -18,6 +18,7 @@ import { join } from "node:path";
import { Writable } from "node:stream";
import { pathToFileURL } from "node:url";
import { describe, expect, test, mock } from "bun:test";
+import { runArtifactExport } from "../src/artifact-export.js";
import { exportEnvironment, main } from "../src/cli.js";
import type { JsonObject } from "../src/config.js";
import {
@@ -103,30 +104,27 @@ describe("CLI", () => {
["sarif", '{"version":"2.1.0"}\n'],
["md", "# Synthetic threat model\n"],
] as const) {
- for (const metadata of [[], ["--full-output"], ["--token-count"]]) {
- const { stdout, stderr, runCli } = createCliTest(main);
+ const { stdout, stderr, runCli } = createCliTest(main);
- const deps = dependencies();
- deps.createSecurity = mustNotInitializeCodex;
- deps.exportFindings = async () => Buffer.from(expected);
- expect(
- await runCli(
- [
- "export",
- "scan",
- "--export-format",
- format,
- "--output",
- "-",
- ...(format === "md" ? ["--artifact", "threat-model"] : []),
- ...metadata,
- ],
- deps,
- ),
- ).toBe(0);
- expect(stdout.text()).toBe(expected);
- expect(stderr.text()).toBe("");
- }
+ const deps = dependencies();
+ deps.createSecurity = mustNotInitializeCodex;
+ deps.exportFindings = async () => Buffer.from(expected);
+ expect(
+ await runCli(
+ [
+ "export",
+ "scan",
+ "--export-format",
+ format,
+ "--output",
+ "-",
+ ...(format === "md" ? ["--artifact", "threat-model"] : []),
+ ],
+ deps,
+ ),
+ ).toBe(0);
+ expect(stdout.text()).toBe(expected);
+ expect(stderr.text()).toBe("");
}
const failure = dependencies();
failure.exportFindings = async () => {
@@ -172,6 +170,58 @@ describe("CLI", () => {
}
});
+ test.each(
+ [
+ ["--full-output"],
+ ["--filter-output", "findings"],
+ ["--token-count"],
+ ["--token-limit", "1"],
+ ["--token-offset", "1"],
+ ["--format", "jsonl"],
+ ].map((flags) => ({ flags })),
+ )(
+ "refuses $flags on raw artifact stdout before exporting",
+ async ({ flags }) => {
+ const cli = createCliTest(main);
+ const deps = dependencies();
+ deps.exportFindings = mock(async () => Buffer.from("unexpected"));
+ expect(
+ await cli.runCli(["export", "scan", "--output", "-", ...flags], deps),
+ ).toBe(2);
+ expect(cli.stdout.text()).toBe("");
+ expect(cli.stderr.text()).toContain(flags[0]!);
+ expect(deps.exportFindings).not.toHaveBeenCalled();
+ },
+ );
+
+ test("atomically preserves the default file and explicitly replaces a requested output", async () => {
+ const directory = await temporaryDirectory("export-no-clobber-");
+ const scan = await copyCompletedScan(directory);
+ const deps = {
+ ...dependencies({ currentDirectory: directory }),
+ exportFindings: runArtifactExport,
+ };
+ const args = ["export", scan, "--export-format", "json"];
+ const [first, second] = await Promise.all([
+ runCapturedCli(main, args, deps),
+ runCapturedCli(main, args, deps),
+ ]);
+ expect([first, second].sort()).toEqual([0, 2]);
+ const path = join(directory, "findings.json");
+ const artifact = await readFile(path, "utf8");
+ await writeFile(path, "my report");
+ const refused = createCliTest(main);
+ expect(await refused.runCli(args, deps)).toBe(2);
+ expect(refused.stderr.text()).toContain(
+ "already exists. Use --output FILE",
+ );
+ expect(await readFile(path, "utf8")).toBe("my report");
+ expect(await runCapturedCli(main, [...args, "--output", path], deps)).toBe(
+ 0,
+ );
+ expect(await readFile(path, "utf8")).toBe(artifact);
+ });
+
test("exports the latest completed scan when no directory is provided", async () => {
const scanDir = join(tmpdir(), "codex-security-latest-scan");
const deps = dependencies({
diff --git a/sdk/typescript/tests-ts/cli-help.test.ts b/sdk/typescript/tests-ts/cli-help.test.ts
index 0adde118c..9584866c2 100644
--- a/sdk/typescript/tests-ts/cli-help.test.ts
+++ b/sdk/typescript/tests-ts/cli-help.test.ts
@@ -236,8 +236,8 @@ describe("CLI help", () => {
test("distinguishes JSON file import from JSON output", async () => {
const text = await help(["scan", "import", "--help"]);
- expect(option(text, "--json")).toContain("<file>");
- expect(option(text, "--csv")).toContain("<file>");
+ expect(option(text, "--json")).toContain("--format json");
+ expect(option(text, "--input-format")).toContain("Input format");
expect(text.replace(/\s+/gu, " ")).toContain("--format json");
expect(option(text, "--format")).toContain("json");
});
@@ -532,7 +532,7 @@ describe("CLI help", () => {
}
});
- test("completes scan import and its file options from the command registry", async () => {
+ test("completes scan import and its input format option from the command registry", async () => {
const previousShell = process.env["COMPLETE"];
const previousIndex = process.env["_COMPLETE_INDEX"];
try {
@@ -540,9 +540,9 @@ describe("CLI help", () => {
process.env["_COMPLETE_INDEX"] = "2";
expect((await help(["--", "cs", "scan", "im"])).trim()).toBe("import");
process.env["_COMPLETE_INDEX"] = "3";
- expect((await help(["--", "cs", "scan", "import", "--cs"])).trim()).toBe(
- "--csv",
- );
+ expect(
+ (await help(["--", "cs", "scan", "import", "--input-f"])).trim(),
+ ).toBe("--input-format");
} finally {
if (previousShell === undefined) delete process.env["COMPLETE"];
else process.env["COMPLETE"] = previousShell;
diff --git a/sdk/typescript/tests-ts/cli-import-snyk.test.ts b/sdk/typescript/tests-ts/cli-import-snyk.test.ts
index d6903053c..7fd8e08ba 100644
--- a/sdk/typescript/tests-ts/cli-import-snyk.test.ts
+++ b/sdk/typescript/tests-ts/cli-import-snyk.test.ts
@@ -37,7 +37,10 @@ test.each(["open-source", "code"] as const)(
const productFlags = code
? ["--snyk-product", product, "--snyk-api-origin", apiOrigin]
: [];
- const status = await cli.runCli([...command, ...productFlags], {
+ const flags = code
+ ? command
+ : command.map((flag) => (flag === "--snyk-org" ? "--org" : flag));
+ const status = await cli.runCli([...flags, ...productFlags], {
...dependencies({ environment }),
hostedScannerFetch: async (url) => {
expect(url.origin).toBe(apiOrigin);
diff --git a/sdk/typescript/tests-ts/cli-scan-import.test.ts b/sdk/typescript/tests-ts/cli-scan-import.test.ts
index 1ddc2e659..c894a0f41 100644
--- a/sdk/typescript/tests-ts/cli-scan-import.test.ts
+++ b/sdk/typescript/tests-ts/cli-scan-import.test.ts
@@ -186,6 +186,45 @@ describe("scan import", () => {
},
);
+ test.each([
+ [["report.CSV"], "csv"],
+ [["report.JSON"], "json"],
+ [["report", "--input-format=json"], "json"],
+ [["report.json", "--input-format", "csv"], "csv"],
+ [["--json", "report"], "json"],
+ [["--csv=--report.csv"], "csv"],
+ ] as const)(
+ "selects the input format for %j and emits JSON",
+ async (args, format) => {
+ const { deps, calls } = importDependencies();
+ const { stdout, runCli } = createCliTest(main);
+ expect(
+ await runCli(["scan", "import", ...args, "--dry-run", "--json"], deps),
+ ).toBe(0);
+ expect(calls[0]?.format).toBe(format);
+ expect(JSON.parse(stdout.text())).toMatchObject({ dryRun: true, format });
+ },
+ );
+
+ test.each([
+ { input: ["--", "--findings.json"], file: "--findings.json" },
+ { input: ["--json", "findings"], file: "findings" },
+ ])(
+ "keeps JSON output before the import verb with $input",
+ async ({ input, file }) => {
+ const { deps, calls } = importDependencies();
+ const { stdout, runCli } = createCliTest(main);
+ expect(
+ await runCli(["scan", "--json", "import", "--dry-run", ...input], deps),
+ ).toBe(0);
+ expect(calls[0]).toMatchObject({
+ sourcePath: resolve("workspace", file),
+ format: "json",
+ });
+ expect(JSON.parse(stdout.text())).toMatchObject({ dryRun: true });
+ },
+ );
+
test("accepts equals input syntax and validates without saving", async () => {
const { deps, calls } = importDependencies();
const { stdout, stderr, runCli } = createCliTest(main);
@@ -224,10 +263,18 @@ describe("scan import", () => {
});
test.each([
- [[], "exactly one"],
- [["--csv", "findings.csv", "--json", "findings.json"], "exactly one"],
- [["--json"], "Missing value for flag: --json"],
- [["--json", "--dry-run"], "Missing value for flag: --json"],
+ [[], "file"],
+ [
+ ["--csv", "findings.csv", "--json", "findings.json"],
+ "Conflicting values for --input-format",
+ ],
+ [["--json"], "file"],
+ [["--json", "--dry-run"], "file"],
+ [["report"], "Use --input-format"],
+ [
+ ["--csv", "report", "--input-format", "json"],
+ "Conflicting values for --input-format",
+ ],
[["--csv"], "Missing value for flag: --csv"],
[["--json="], "--json must not be empty"],
[
@@ -246,22 +293,20 @@ describe("scan import", () => {
expect(stderr.text()).toContain(message);
});
- test("exposes both source flags in help and schemas", async () => {
+ test("exposes a positional file, an input format, and a separate JSON output option", async () => {
const { deps, calls } = importDependencies();
const help = captureCli(main, "stdout");
expect(await help.run(["scan", "import", "--help"], deps)).toBe(0);
- expect(help.text()).toContain("--csv <file>");
- expect(help.text()).toContain("--json <file>");
+ expect(help.text()).toContain("FILE [options]");
+ expect(help.text()).toContain("--input-format");
expect(help.text()).toContain("--format json");
const schema = captureCli(main, "stdout");
expect(
await schema.run(["scan", "import", "--schema", "--json"], deps),
).toBe(0);
expect(JSON.parse(schema.text())).toMatchObject({
- options: {
- properties: { csv: { type: "string" }, json: { type: "string" } },
- oneOf: [{ required: ["csv"] }, { required: ["json"] }],
- },
+ args: { required: ["file"] },
+ options: { properties: { inputFormat: { enum: ["csv", "json"] } } },
});
expect(calls).toHaveLength(0);
});
diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts
index eb40b32ae..dd7502acf 100644
--- a/sdk/typescript/tests-ts/cli.test.ts
+++ b/sdk/typescript/tests-ts/cli.test.ts
@@ -1026,8 +1026,11 @@ describe("CLI", () => {
definitions.options?.properties ?? {},
)) {
const flag = `--${name.replace(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`)}`;
- // The CSV input belongs to the internal publication destination.
- if (command.join(" ") === "publish scan" && flag === "--csv") {
+ // Keep the internal CSV input and the redundant Linear selector out of help.
+ if (
+ (command.join(" ") === "publish scan" && flag === "--csv") ||
+ (command.join(" ") === "publish check" && flag === "--to")
+ ) {
expect(help.text()).not.toContain(flag);
} else {
expect(help.text()).toContain(flag);
@@ -3298,7 +3301,7 @@ describe("CLI", () => {
expect(exportFindings).not.toHaveBeenCalled();
expect(stdout.text()).toBe("");
expect(stderr.text()).toContain(
- "CSV stdout cannot be combined with JSON output",
+ "CSV stdout cannot be combined with --format json",
);
}
});
diff --git a/sdk/typescript/tests-ts/semgrep-platform-collector.test.ts b/sdk/typescript/tests-ts/semgrep-platform-collector.test.ts
index bcf9d4c1d..f5eced5dd 100644
--- a/sdk/typescript/tests-ts/semgrep-platform-collector.test.ts
+++ b/sdk/typescript/tests-ts/semgrep-platform-collector.test.ts
@@ -1520,7 +1520,12 @@ test("CLI emits a replayable report for the requested product", async () => {
rule_name: "example.rule",
};
const cli = createCliTest(main);
- const code = await cli.runCli([...cliArgs, "--source-repository-url", url], {
+ const flags = cliArgs.map((flag) =>
+ flag
+ .replace("--semgrep-deployment", "--deployment")
+ .replace("--semgrep-ref", "--ref"),
+ );
+ const code = await cli.runCli([...flags, "--source-repository-url", url], {
...dependencies({ environment }),
hostedScannerFetch: async (endpoint) =>
Response.json(