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(threat-model): preserve literal scope paths across renderers (#1850)

wjd8cbf5713384
diff --git a/plugins/codex-security/mcp-app/src/threat-model-format.ts b/plugins/codex-security/mcp-app/src/threat-model-format.ts
index c57a77196..b683cd78e 100644
--- a/plugins/codex-security/mcp-app/src/threat-model-format.ts
+++ b/plugins/codex-security/mcp-app/src/threat-model-format.ts
@@ -9,6 +9,29 @@ function collapse(value: string): string {
return value.replace(whitespace, " ").replace(/^ | $/gu, "");
}
+/** Match report_projection._path_text with ensure_ascii for quoted scope paths. */
+export function pathText(value: string): string {
+ if (
+ !value.includes(",") &&
+ value === collapse(value) &&
+ !/[\u0000-\u001f]/u.test(value)
+ )
+ return value.replace(/([\\`*_\[\]<>])/gu, "\\$1");
+
+ // Escape UTF-16 units so quoted paths do not depend on Unicode versions.
+ const label = JSON.stringify(value).replace(
+ /[\u007f-\uffff]/g,
+ (unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, "0")}`,
+ );
+ const marker = "`".repeat(
+ (label.match(/`+/gu) ?? []).reduce(
+ (length, run) => Math.max(length, run.length + 1),
+ 1,
+ ),
+ );
+ return `${marker}${label}${marker}`;
+}
+
/** Plain metadata remains text; authored single-backtick spans remain intact. */
export function text(value: unknown, fallback = ""): string {
const candidate =
diff --git a/plugins/codex-security/mcp-app/src/threat-model-render.ts b/plugins/codex-security/mcp-app/src/threat-model-render.ts
index 237d755d0..8b8439856 100644
--- a/plugins/codex-security/mcp-app/src/threat-model-render.ts
+++ b/plugins/codex-security/mcp-app/src/threat-model-render.ts
@@ -1,5 +1,5 @@
import { isRecord } from "./record.js";
-import { nonblank, text } from "./threat-model-format.js";
+import { nonblank, pathText, text } from "./threat-model-format.js";
import { threatModelSchemas } from "./threat-model-schema.js";
import * as z from "zod/v4";
@@ -116,14 +116,16 @@ function scopeLines(scope: unknown, label: string): string[] {
) {
return [`- ${label}: not recorded`];
}
- const lines = [`- ${label}: ${text(scope.includePaths.join(", "), "none")}`];
+ const lines = [
+ `- ${label}: ${scope.includePaths.map(pathText).join(", ") || "none"}`,
+ ];
if (
Array.isArray(scope.excludePaths) &&
scope.excludePaths.length &&
scope.excludePaths.every((path) => typeof path === "string")
) {
lines.push(
- `- ${label} exclusions: ${text(scope.excludePaths.join(", "), "none")}`,
+ `- ${label} exclusions: ${scope.excludePaths.map(pathText).join(", ") || "none"}`,
);
}
if (typeof scope.summary === "string" && scope.summary)
diff --git a/plugins/codex-security/mcp-app/tests/test_threat_model_render.ts b/plugins/codex-security/mcp-app/tests/test_threat_model_render.ts
index 7c189f4e5..e5d065382 100644
--- a/plugins/codex-security/mcp-app/tests/test_threat_model_render.ts
+++ b/plugins/codex-security/mcp-app/tests/test_threat_model_render.ts
@@ -109,6 +109,56 @@ equivalent(
},
},
);
+for (const [paths, expected] of [
+ [
+ [
+ ".",
+ "src/",
+ "path with space",
+ "src/[queue]",
+ "tmp/*",
+ "Résumé.md",
+ "😀.md",
+ ],
+ String.raw`., src/, path with space, src/\[queue\], tmp/\*, Résumé.md, 😀.md`,
+ ],
+ [
+ ["a,b.ts", "a, b.ts", "a b", "a b", " ", " "],
+ '`"a,b.ts"`, `"a, b.ts"`, `"a b"`, a b, `" "`, `" "`',
+ ],
+ [
+ [" a`b ", "a``b,c", "`literal`"],
+ '``" a`b "``, ```"a``b,c"```, \\`literal\\`',
+ ],
+ [
+ [
+ "docs/Résumé, final.md",
+ "a\u202eb, c.md",
+ "a\u00a0b",
+ "😀, c.md",
+ "\u{1fae9},notes.md",
+ ],
+ '`"docs/R\\u00e9sum\\u00e9, final.md"`, `"a\\u202eb, c.md"`, `"a\\u00a0b"`, `"\\ud83d\\ude00, c.md"`, `"\\ud83e\\udee9,notes.md"`',
+ ],
+ [
+ ["a\u001bb", "a\u007fb, c.md", "a\nb", "a\tb"],
+ '`"a\\u001bb"`, `"a\\u007fb, c.md"`, `"a\\nb"`, `"a\\tb"`',
+ ],
+] satisfies [string[], string][]) {
+ test(`literal scope paths match Python: ${JSON.stringify(paths)}`, () => {
+ const scope = { includePaths: paths, excludePaths: paths };
+ const input = {
+ threatModel: { ...markdownModel, scope },
+ provenance: { scanScope: scope },
+ };
+ const rendered = renderThreatModel(input);
+ assert.equal(rendered, pythonRender(input));
+ for (const label of ["Model scope", "Scan scope"]) {
+ assert.ok(rendered.includes(`- ${label}: ${expected}\n`));
+ assert.ok(rendered.includes(`- ${label} exclusions: ${expected}\n`));
+ }
+ });
+}
for (const ending of ["", "\n", "\n\n", "\r\n"]) {
equivalent(`authored Markdown ending ${JSON.stringify(ending)}`, {
...markdownModel,
@@ -174,7 +224,11 @@ test("non-object models report a threatModel diagnostic", () => {
});
test("Python finalizer recognizes native renderer bytes as the current projection", () => {
- const threatModel = { summary: "Saved model", assets: ["Queue"] };
+ const scope = {
+ includePaths: ["src", "a,b.ts", "a b", "\u{1fae9},notes.md"],
+ excludePaths: [" "],
+ };
+ const threatModel = { summary: "Saved model", assets: ["Queue"], scope };
const scan = {
id: "example-scan",
status: "running",
@@ -183,7 +237,7 @@ test("Python finalizer recognizes native renderer bytes as the current projectio
displayName: "Example [workspace]",
revision: "example-revision",
},
- scope: { includePaths: ["src"], excludePaths: [] },
+ scope,
};
const markdown = renderThreatModel({
threatModel,
diff --git a/plugins/codex-security/scripts/report_projection.py b/plugins/codex-security/scripts/report_projection.py
index 63c8600bf..3e6b56aef 100644
--- a/plugins/codex-security/scripts/report_projection.py
+++ b/plugins/codex-security/scripts/report_projection.py
@@ -45,15 +45,15 @@ def _strings(value: Any) -> list[str]:
return [text for item in value if (text := _text(item, ""))]
-def _path_label(value: str) -> str:
+def _path_label(value: str, *, ensure_ascii: bool = False) -> str:
if "," in value or value != " ".join(value.split()) or any(ord(c) < 32 for c in value):
- quoted = json.dumps(value, ensure_ascii=False)
+ quoted = json.dumps(value, ensure_ascii=ensure_ascii)
return "".join(c if c.isprintable() else json.dumps(c)[1:-1] for c in quoted)
return value
-def _path_text(value: str) -> str:
- label = _path_label(value)
+def _path_text(value: str, *, ensure_ascii: bool = False) -> str:
+ label = _path_label(value, ensure_ascii=ensure_ascii)
if label != value:
marker = _code_fence(label, minimum=1)
return f"{marker}{label}{marker}"
diff --git a/plugins/codex-security/scripts/threat_model_projection.py b/plugins/codex-security/scripts/threat_model_projection.py
index 8f21780b9..ff17b7334 100644
--- a/plugins/codex-security/scripts/threat_model_projection.py
+++ b/plugins/codex-security/scripts/threat_model_projection.py
@@ -101,10 +101,12 @@ def _scope_lines(scope: Any, label: str, text: Callable[[Any, str], str]) -> lis
included = scope.get("includePaths") if isinstance(scope, dict) else None
if not isinstance(included, list) or not all(isinstance(path, str) for path in included):
return [f"- {label}: not recorded"]
- lines = [f"- {label}: {text(', '.join(included), 'none')}"]
+ included_text = ", ".join(report._path_text(path, ensure_ascii=True) for path in included)
+ lines = [f"- {label}: {included_text or 'none'}"]
excluded = scope.get("excludePaths")
if isinstance(excluded, list) and excluded and all(isinstance(path, str) for path in excluded):
- lines.append(f"- {label} exclusions: {text(', '.join(excluded), 'none')}")
+ excluded_text = ", ".join(report._path_text(path, ensure_ascii=True) for path in excluded)
+ lines.append(f"- {label} exclusions: {excluded_text or 'none'}")
summary = scope.get("summary")
if isinstance(summary, str) and summary:
lines.append(f"- {label} description: {text(summary, 'not recorded')}")
diff --git a/plugins/codex-security/tests/test_threat_model_projection.py b/plugins/codex-security/tests/test_threat_model_projection.py
index ecbf721e9..2c4041409 100644
--- a/plugins/codex-security/tests/test_threat_model_projection.py
+++ b/plugins/codex-security/tests/test_threat_model_projection.py
@@ -80,6 +80,36 @@ class ThreatModelProjectionTest(ScanFixtureTestCase):
self.assertIn(b"tmp/\\*", document)
self.assertIn(b"Service boundaries.", document)
+ def test_scope_paths_keep_ambiguous_literals_distinct(self) -> None:
+ scope = {"includePaths": ["a,b.ts", "a b", "src"], "excludePaths": [" "]}
+ document = FINALIZER._render_threat_model(
+ {"summary": "Existing structured model.", "scope": scope}, {"scanScope": scope}
+ )
+ for label in (b"Model scope", b"Scan scope"):
+ self.assertIn(label + b': `"a,b.ts"`, `"a b"`, src\n', document)
+ self.assertIn(label + b' exclusions: `" "`\n', document)
+
+ def test_legacy_empty_scope_paths_keep_none_placeholder(self) -> None:
+ scope = {"includePaths": [""], "excludePaths": [""]}
+ document = FINALIZER._render_threat_model(
+ {"summary": "Existing structured model.", "scope": scope}, {"scanScope": scope}
+ )
+ for label in (b"Model scope", b"Scan scope"):
+ self.assertIn(label + b": none\n", document)
+ self.assertIn(label + b" exclusions: none\n", document)
+
+ def test_quoted_scope_paths_use_version_independent_unicode_escapes(self) -> None:
+ scope = {"includePaths": ["Résumé.md", "Résumé, final.md", "\U0001fae9,notes.md"]}
+ document = FINALIZER._render_threat_model(
+ {"summary": "Existing structured model.", "scope": scope}, {"scanScope": scope}
+ ).decode()
+ for label in ("Model scope", "Scan scope"):
+ self.assertIn(
+ f'- {label}: Résumé.md, `"R\\u00e9sum\\u00e9, final.md"`, '
+ '`"\\ud83e\\udee9,notes.md"`\n',
+ document,
+ )
+
def test_exports_legacy_structured_model_extensions(self) -> None:
for extensions, expected_origin in (
({"format": "markdown"}, "not recorded"),