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: resolve path aliases consistently across scan workflows (#1267)

mldangelo-oai2ec54a087d3e
diff --git a/plugins/codex-security/mcp-app/server.ts b/plugins/codex-security/mcp-app/server.ts
index ef6ed8870..a755f0533 100644
--- a/plugins/codex-security/mcp-app/server.ts
+++ b/plugins/codex-security/mcp-app/server.ts
@@ -2502,6 +2502,7 @@ async function executeWorkbench(
[workbenchScriptPath(), ...workbenchArgs],
{
cwd: PLUGIN_ROOT,
+ windowsHide: true,
env: stateDir
? { ...process.env, CODEX_SECURITY_STATE_DIR: stateDir }
: process.env,
diff --git a/plugins/codex-security/mcp-app/src/helpers/resolve-security-md.ts b/plugins/codex-security/mcp-app/src/helpers/resolve-security-md.ts
index 6b4269329..164f33b9f 100644
--- a/plugins/codex-security/mcp-app/src/helpers/resolve-security-md.ts
+++ b/plugins/codex-security/mcp-app/src/helpers/resolve-security-md.ts
@@ -231,13 +231,43 @@ function asciiJson(value: string): string {
);
}
+function directoryEntries(directory: Buffer) {
+ return windows
+ ? windowsFiles().entriesWithTypes(directory)
+ : readdirSync(directory, {
+ encoding: "buffer",
+ withFileTypes: true,
+ }).flatMap((entry) => {
+ // Some Node-compatible runtimes return names without their types.
+ if (!(entry instanceof Uint8Array)) return [entry];
+ const name = Buffer.from(entry);
+ let metadata;
+ try {
+ metadata = lstatSync(appendPath(directory, name));
+ } catch (error) {
+ if (
+ ["ENOENT", "ENOTDIR"].includes(
+ (error as NodeJS.ErrnoException).code ?? "",
+ )
+ )
+ return [];
+ throw error;
+ }
+ return [
+ {
+ name,
+ isDirectory: () => metadata.isDirectory(),
+ isSymbolicLink: () => metadata.isSymbolicLink(),
+ },
+ ];
+ });
+}
+
function listSecurityMd(repo: string, posixHome: string | undefined): string[] {
const root = resolveRoot(repo, posixHome);
const policies: string[] = [];
function walk(directory: Buffer, prefix: string): void {
- const entries = windows
- ? windowsFiles().entriesWithTypes(directory)
- : readdirSync(directory, { encoding: "buffer", withFileTypes: true });
+ const entries = directoryEntries(directory);
for (const listedEntry of entries) {
const bytes = listedEntry.name;
const name = decodePath(bytes);
diff --git a/plugins/codex-security/scripts/finalize_scan_contract.py b/plugins/codex-security/scripts/finalize_scan_contract.py
index e8466e087..ad62d17f6 100644
--- a/plugins/codex-security/scripts/finalize_scan_contract.py
+++ b/plugins/codex-security/scripts/finalize_scan_contract.py
@@ -581,15 +581,23 @@ def _open_scan_local_directory(root_fd: int, parts: tuple[str, ...], *, create:
raise
-def open_scan_local_file_descriptor(scan_dir: Path, relative_path: str, context: str) -> int:
- return _open_scan_local_file_with_path(scan_dir, relative_path, context)[0]
+def open_scan_local_file_descriptor(
+ scan_dir: Path, relative_path: str, context: str, *, portable: bool = True
+) -> int:
+ return _open_scan_local_file_with_path(scan_dir, relative_path, context, portable=portable)[0]
def _open_scan_local_file_with_path(
- scan_dir: Path, relative_path: str, context: str, *, resolve_spelling: bool = False
+ scan_dir: Path,
+ relative_path: str,
+ context: str,
+ *,
+ resolve_spelling: bool = False,
+ portable: bool = True,
) -> tuple[int, str]:
scan_dir = _require_scan_directory(scan_dir)
- relative_path = _require_portable_relative_path(relative_path, context)
+ validate_path = _require_portable_relative_path if portable else _require_safe_relative_path
+ relative_path = validate_path(relative_path, context)
if not (os.open in os.supports_dir_fd and hasattr(os, "O_NOFOLLOW")):
if not _is_windows():
raise ContractError("scan-local input requires descriptor-relative file operations")
@@ -2243,7 +2251,7 @@ def _open_source_file(source_root: Path, relative_path: str) -> TextIO | None:
file_fd: int | None = None
try:
file_fd = open_scan_local_file_descriptor(
- source_root, relative_path, f"source file {relative_path}"
+ source_root, relative_path, f"source file {relative_path}", portable=False
)
handle = os.fdopen(file_fd, "r", encoding="utf-8", errors="replace")
file_fd = None
@@ -3073,6 +3081,7 @@ def main() -> int:
parser.add_argument("--write-threat-model", action="store_true")
args = parser.parse_args()
try:
+ args.scan_dir = args.scan_dir.resolve()
if args.describe_threat_model:
sys.stdout.buffer.write(
_json_bytes(describe_threat_model(args.scan_dir, args.schema_dir))
diff --git a/plugins/codex-security/scripts/workbench_db.py b/plugins/codex-security/scripts/workbench_db.py
index ade65b349..b614f4ab1 100644
--- a/plugins/codex-security/scripts/workbench_db.py
+++ b/plugins/codex-security/scripts/workbench_db.py
@@ -396,7 +396,7 @@ def inspect_setup_values(
def require_review_changes_target(target: Path) -> str:
revision = require_git_worktree_head(target)
repository_root = git_output(target, "rev-parse", "--show-toplevel")
- if repository_root is None or Path(repository_root).resolve() != target:
+ if repository_root is None or not Path(repository_root).samefile(target):
raise SystemExit(
"Review changes requires the checked-out Git repository root as the target."
)
diff --git a/plugins/codex-security/scripts/workbench_target.py b/plugins/codex-security/scripts/workbench_target.py
index 04fed9335..34a49e5ec 100644
--- a/plugins/codex-security/scripts/workbench_target.py
+++ b/plugins/codex-security/scripts/workbench_target.py
@@ -431,11 +431,17 @@ def git_worktree_context(target: Path) -> tuple[Path, str]:
if root is None:
raise SystemExit("Could not inspect the selected Git working tree.")
repository = Path(root).resolve()
+ prefix = git_bytes(target, "rev-parse", "--show-prefix")
+ if prefix is None:
+ raise SystemExit("Could not inspect the selected Git working tree.")
+ pathspec = os.fsdecode(prefix.removesuffix(b"\n")).removesuffix("/") or "."
+ scoped = (repository / pathspec).resolve()
try:
- relative = target.resolve().relative_to(repository)
- except ValueError as exc:
+ if not scoped.is_relative_to(repository) or not scoped.samefile(target):
+ raise ValueError("Git working tree does not contain the selected target")
+ except (OSError, ValueError) as exc:
raise SystemExit("Scan target must stay inside its Git working tree.") from exc
- return repository, relative.as_posix() or "."
+ return repository, pathspec
def git_submodule_entries(target: Path) -> tuple[tuple[Path, str], ...]:
@@ -454,7 +460,8 @@ def git_submodule_entries(target: Path) -> tuple[tuple[Path, str], ...]:
) from exc
if mode != b"160000":
continue
- entries.append((repository / os.fsdecode(raw_path), object_id.decode("ascii")))
+ relative_path = Path(os.fsdecode(raw_path)).relative_to(pathspec)
+ entries.append((target / relative_path, object_id.decode("ascii")))
return tuple(entries)
@@ -469,7 +476,7 @@ def require_clean_submodule_worktrees(target: Path) -> None:
continue
root = git_output(submodule, "rev-parse", "--show-toplevel")
try:
- is_initialized = root is not None and Path(root).resolve() == submodule.resolve()
+ is_initialized = root is not None and Path(root).samefile(submodule)
except OSError:
is_initialized = False
if not is_initialized:
@@ -541,7 +548,6 @@ def git_directory_snapshot_paths(target: Path) -> list[Path] | None:
paths: list[Path] = []
for raw_path in (raw_path for raw_path in listed.split(b"\0") if raw_path):
relative = Path(os.fsdecode(raw_path))
- path = repository / relative
if scope_depth:
if len(relative.parts) <= scope_depth:
continue
@@ -558,7 +564,7 @@ def git_directory_snapshot_paths(target: Path) -> list[Path] | None:
# POSIX volumes; WindowsPath equality also folds distinct names.
if not matching_prefixes[key]:
continue
- path = scope.joinpath(*relative.parts[scope_depth:])
+ path = target.joinpath(*relative.parts[scope_depth:])
try:
metadata = path.lstat()
except FileNotFoundError:
@@ -568,10 +574,7 @@ def git_directory_snapshot_paths(target: Path) -> list[Path] | None:
if not stat.S_ISDIR(metadata.st_mode):
continue
nested_repository_root = git_output(path, "rev-parse", "--show-toplevel")
- if (
- nested_repository_root is not None
- and Path(nested_repository_root).resolve() == path.resolve()
- ):
+ if nested_repository_root is not None and Path(nested_repository_root).samefile(path):
nested_paths = git_directory_snapshot_paths(path)
if nested_paths is not None:
paths.extend(nested_paths)
@@ -698,9 +701,16 @@ def copy_git_worktree_files(source: Path, destination: Path, excluded: tuple[Pat
)
if listed is None:
raise SystemExit("Could not inspect files in the selected Git working tree.")
- excluded_relative = [
- path.relative_to(repository) for path in excluded if path.is_relative_to(repository)
- ]
+ excluded_relative = []
+ for path in excluded:
+ try:
+ relative_path = path.relative_to(repository)
+ except ValueError:
+ try:
+ relative_path = Path(pathspec) / path.relative_to(source)
+ except ValueError:
+ continue
+ excluded_relative.append(relative_path)
destination.mkdir()
for raw_path in sorted(path for path in listed.split(b"\0") if path):
relative = Path(os.fsdecode(raw_path))
@@ -744,7 +754,7 @@ def git_target_metadata(target: Path) -> dict[str, Any]:
and is_worktree
and revision is not None
and repository_root is not None
- and Path(repository_root).resolve() == target
+ and Path(repository_root).samefile(target)
)
metadata: dict[str, Any] = {
"hasHead": revision is not None,
diff --git a/plugins/codex-security/tests/test_finalize_scan_contract.py b/plugins/codex-security/tests/test_finalize_scan_contract.py
index 8f46e59da..92c2ae6e9 100644
--- a/plugins/codex-security/tests/test_finalize_scan_contract.py
+++ b/plugins/codex-security/tests/test_finalize_scan_contract.py
@@ -130,7 +130,46 @@ class FinalizeScanContractTest(ScanFixtureTestCase):
self.assertEqual(findings, original)
return compatible["findings"][0]
- def run_finalizer(self, *args: str) -> subprocess.CompletedProcess[str]:
+ def test_cli_resolves_noncanonical_scan_directory_arguments(self) -> None:
+ self.write_scan()
+ for spelling in (
+ self.scan_dir.name,
+ str(self.scan_dir / ".." / self.scan_dir.name),
+ ):
+ with self.subTest(spelling=spelling):
+ result = self.run_finalizer("--scan-dir", spelling, cwd=self.scan_dir.parent)
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+ @unittest.skipIf(os.name == "nt", "POSIX directory alias fixture")
+ def test_cli_resolves_scan_directory_symlink(self) -> None:
+ self.write_scan()
+ with tempfile.TemporaryDirectory() as directory:
+ alias = Path(directory) / "alias"
+ alias.symlink_to(self.scan_dir, target_is_directory=True)
+ result = self.run_finalizer("--scan-dir", str(alias))
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+ @unittest.skipIf(os.name == "nt", "POSIX source filenames")
+ def test_sarif_hashes_source_names_that_are_not_portable_artifact_names(self) -> None:
+ source_root = self.scan_dir / "source"
+ for name in ("aux.c", "con.py", "src/a:b.c", "what?.md"):
+ with self.subTest(name=name):
+ source = source_root / name
+ source.parent.mkdir(parents=True, exist_ok=True)
+ source.write_text("synthetic_source()\n")
+ self.findings["findings"][0]["locations"] = [{"path": name, "startLine": 1}]
+ self.write_scan()
+ FINALIZER.finalize_scan(self.scan_dir, source_root=source_root)
+ sarif = json.loads((self.scan_dir / "exports/results.sarif").read_text())
+ self.assertIn(
+ "primaryLocationLineHash", sarif["runs"][0]["results"][0]["partialFingerprints"]
+ )
+ with self.assertRaises(FINALIZER.ContractError):
+ FINALIZER.open_scan_local_file_descriptor(source_root, name, "artifact")
+
+ def run_finalizer(
+ self, *args: str, cwd: Path | None = None
+ ) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[
sys.executable,
@@ -142,6 +181,7 @@ class FinalizeScanContractTest(ScanFixtureTestCase):
capture_output=True,
text=True,
check=False,
+ cwd=cwd,
)
def write_scan(self) -> None:
diff --git a/plugins/codex-security/tests/test_workbench_db.py b/plugins/codex-security/tests/test_workbench_db.py
index 74cbe1750..44c93f60e 100644
--- a/plugins/codex-security/tests/test_workbench_db.py
+++ b/plugins/codex-security/tests/test_workbench_db.py
@@ -2934,7 +2934,6 @@ def test_completed_finding_projects_writeup_and_poc_artifact_paths(
outside = tmp_path / "outside.txt"
outside.write_text("must not be projected\n")
(poc / "outside-link.txt").symlink_to(outside)
-
completed = run_workbench(state_dir, "complete-scan", "--scan-id", scan_id)
if non_utf8_artifact:
(poc / os.fsdecode(b"caf\xe9.txt")).write_text("Supplemental fixture.\n")
diff --git a/plugins/codex-security/tests/test_workbench_target.py b/plugins/codex-security/tests/test_workbench_target.py
index aad9e07d5..39297ae2e 100644
--- a/plugins/codex-security/tests/test_workbench_target.py
+++ b/plugins/codex-security/tests/test_workbench_target.py
@@ -160,9 +160,71 @@ def test_directory_content_digest_uses_git_file_set(tmp_path: Path) -> None:
assert directory_content_digest(target) == original_digest
[email protected]("scope", [".", "component"])
+def test_directory_snapshot_preserves_target_alias_spelling(tmp_path: Path, scope: str) -> None:
+ target = tmp_path / "target"
+ initialize_unborn_git_repository(target)
+ (target / "component").mkdir()
+ (target / "component" / "app.py").write_text("print('fixture')\n")
+ (target / "root.py").write_text("print('root')\n")
+ alias = tmp_path / "alias"
+ alias.symlink_to(target, target_is_directory=True)
+ scoped = target / scope
+ selected = alias / scope
+ expected = [
+ selected / path.relative_to(scoped)
+ for path in WORKBENCH_TARGET["git_directory_snapshot_paths"](scoped)
+ ]
+
+ paths = WORKBENCH_TARGET["git_directory_snapshot_paths"](selected)
+ assert [str(path) for path in paths] == [str(path) for path in expected]
+ original_digest = directory_content_digest(selected)
+ assert original_digest == directory_content_digest(scoped)
+ (selected / "changed.py").write_text("print('changed')\n")
+ assert directory_content_digest(selected) == directory_content_digest(scoped)
+ assert directory_content_digest(selected) != original_digest
+
+
[email protected]("scope", [".", "component"])
[email protected]("alias_kind", ["symlink", "case"])
+def test_submodule_checks_preserve_target_alias_spelling(
+ tmp_path: Path, scope: str, alias_kind: str
+) -> None:
+ target = tmp_path / "target"
+ initialize_git_repository(target)
+ scoped = target / scope
+ scoped.mkdir(exist_ok=True)
+ submodule = scoped / "submodule"
+ revision = initialize_git_repository(submodule)
+ subprocess.run(
+ [
+ "git",
+ "update-index",
+ "--add",
+ "--cacheinfo",
+ f"160000,{revision},{(Path(scope) / 'submodule').as_posix()}",
+ ],
+ cwd=target,
+ check=True,
+ )
+ alias = tmp_path / ("alias" if alias_kind == "symlink" else "TARGET")
+ if alias_kind == "symlink":
+ alias.symlink_to(target, target_is_directory=True)
+ elif not alias.exists():
+ pytest.skip("filesystem does not support case aliases")
+ selected = alias / scope
+ entries = WORKBENCH_TARGET["git_submodule_entries"](selected)
+ assert entries == ((selected / "submodule", revision),)
+ WORKBENCH_TARGET["require_clean_submodule_worktrees"](selected)
+ (submodule / "README.md").write_text("changed after commit\n")
+ with pytest.raises(SystemExit, match="Dirty Git submodules.*submodule"):
+ WORKBENCH_TARGET["require_clean_submodule_worktrees"](selected)
+
+
@pytest.mark.parametrize("content_digest", [directory_content_digest, worktree_content_digest])
[email protected]("alias_kind", ["original", "symlink", "case"])
def test_content_digest_expands_nested_git_repositories(
- tmp_path: Path, content_digest: Callable[[Path], str]
+ tmp_path: Path, content_digest: Callable[[Path], str], alias_kind: str
) -> None:
target = tmp_path / "target"
initialize_git_repository(target)
@@ -175,19 +237,26 @@ def test_content_digest_expands_nested_git_repositories(
ignored_cache.mkdir()
ignored_output = ignored_cache / "build-output"
ignored_output.write_text("ignored runtime data\n")
- original_digest = content_digest(target)
+ selected = target
+ if alias_kind != "original":
+ selected = tmp_path / ("alias" if alias_kind == "symlink" else "TARGET")
+ if alias_kind == "symlink":
+ selected.symlink_to(target, target_is_directory=True)
+ elif not selected.exists():
+ pytest.skip("filesystem does not support case aliases")
+ original_digest = content_digest(selected)
nested_source.write_text("print('changed')\n")
- assert content_digest(target) != original_digest
+ assert content_digest(selected) != original_digest
nested_source.write_text("print('fixture')\n")
(nested / "README.md").write_text("changed after commit\n")
- assert content_digest(target) != original_digest
+ assert content_digest(selected) != original_digest
(nested / "README.md").write_text("fixture\n")
(nested / ".git" / "runtime-cache").write_text("runtime metadata\n")
ignored_output.write_text("changed ignored runtime data\n")
- assert content_digest(target) == original_digest
+ assert content_digest(selected) == original_digest
def test_directory_content_digest_skips_missing_cached_paths(tmp_path: Path) -> None:
@@ -376,3 +445,128 @@ def test_git_discovery_preserves_symlink_parent_traversal(
if os.name != "nt":
assert expected == host_git
assert trusted_git_executable(repository) == str(expected)
+
+
+ "name",
+ [
+ "component with spaces",
+ pytest.param(
+ "component with spaces ",
+ marks=pytest.mark.skipif(os.name == "nt", reason="Windows strips trailing spaces"),
+ ),
+ ],
+)
+def test_git_context_retains_scoped_directory_spelling(tmp_path: Path, name: str) -> None:
+ target = tmp_path / "target"
+ initialize_git_repository(target)
+ scoped = target / name
+ scoped.mkdir()
+ repository, pathspec = WORKBENCH_TARGET["git_worktree_context"](scoped)
+ assert repository.samefile(target)
+ assert pathspec == scoped.name
+
+
+def test_git_target_accepts_filesystem_case_aliases(tmp_path: Path) -> None:
+ target = tmp_path / "target"
+ initialize_git_repository(target)
+ alias = tmp_path / "TARGET"
+ if not alias.exists():
+ pytest.skip("filesystem does not support case aliases")
+ assert WORKBENCH_TARGET["git_target_metadata"](alias)["reviewChangesSupported"]
+ repository, pathspec = WORKBENCH_TARGET["git_worktree_context"](alias)
+ assert repository.samefile(target)
+ assert pathspec == "."
+ scoped = target / "component"
+ scoped.mkdir()
+ repository, pathspec = WORKBENCH_TARGET["git_worktree_context"](alias / "COMPONENT")
+ assert repository.samefile(target)
+ assert (repository / pathspec).samefile(scoped)
+
+
[email protected](os.name == "nt", reason="Windows does not preserve trailing path whitespace")
[email protected]("sibling_exists", [False, True])
+def test_git_context_preserves_trailing_root_whitespace(
+ tmp_path: Path, sibling_exists: bool
+) -> None:
+ target = tmp_path / "target "
+ initialize_git_repository(target)
+ if sibling_exists:
+ initialize_git_repository(tmp_path / "target")
+ assert WORKBENCH_TARGET["git_target_metadata"](target)["reviewChangesSupported"]
+ repository, pathspec = WORKBENCH_TARGET["git_worktree_context"](target)
+ assert repository.samefile(target)
+ assert pathspec == "."
+ original_digest = worktree_content_digest(target)
+ (target / "synthetic.txt").write_text("selected target content\n")
+ assert worktree_content_digest(target) != original_digest
+ destination = tmp_path / "copied"
+ WORKBENCH_TARGET["copy_git_worktree_files"](target, destination, ())
+ assert (destination / "synthetic.txt").read_text() == "selected target content\n"
+
+
+def test_git_context_rejects_an_unrelated_configured_worktree(tmp_path: Path) -> None:
+ target = tmp_path / "target"
+ unrelated = tmp_path / "unrelated"
+ initialize_git_repository(target)
+ unrelated.mkdir()
+ subprocess.run(["git", "config", "core.worktree", str(unrelated)], cwd=target, check=True)
+ with pytest.raises(SystemExit, match="inside its Git working tree"):
+ WORKBENCH_TARGET["git_worktree_context"](target)
+ with pytest.raises(SystemExit, match="inside its Git working tree"):
+ worktree_content_digest(target)
+ destination = tmp_path / "copied"
+ with pytest.raises(SystemExit, match="inside its Git working tree"):
+ WORKBENCH_TARGET["copy_git_worktree_files"](target, destination, ())
+ assert not destination.exists()
+
+
[email protected]("scope", [".", "component"])
[email protected]("alias_kind", ["original", "symlink", "case"])
+def test_copy_retains_alias_rooted_gitlink_exclusions(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, scope: str, alias_kind: str
+) -> None:
+ repository = tmp_path / "repository"
+ revision = initialize_git_repository(repository)
+ scoped = repository / scope
+ scoped.mkdir(exist_ok=True)
+ (scoped / "fixture.py").write_text("synthetic = True\n")
+ submodule = scoped / "submodule"
+ submodule.mkdir()
+ subprocess.run(
+ [
+ "git",
+ "update-index",
+ "--add",
+ "--cacheinfo",
+ f"160000,{revision},{(Path(scope) / 'submodule').as_posix()}",
+ ],
+ cwd=repository,
+ check=True,
+ )
+ selected = scoped
+ if alias_kind != "original":
+ alias = tmp_path / ("selected-alias" if alias_kind == "symlink" else "REPOSITORY")
+ if alias_kind == "symlink":
+ alias.symlink_to(repository, target_is_directory=True)
+ elif not alias.exists():
+ pytest.skip("filesystem does not support case aliases")
+ selected = alias / scope
+ entries = WORKBENCH_TARGET["git_submodule_entries"](selected)
+ WORKBENCH_TARGET["require_clean_submodule_worktrees"](selected)
+ copy = WORKBENCH_TARGET["copy_git_worktree_files"]
+ calls = []
+
+ def checked_copy(source: Path, destination: Path, excluded: tuple[Path, ...]) -> Path:
+ assert not source.samefile(submodule), "An excluded uninitialized gitlink was traversed"
+ calls.append(source)
+ return copy(source, destination, excluded)
+
+ monkeypatch.setitem(copy.__globals__, "copy_git_worktree_files", checked_copy)
+ selected_exclusions = tuple(path for path, _ in entries)
+ for index, excluded in enumerate({selected_exclusions, (submodule,)}):
+ calls.clear()
+ copied = checked_copy(selected, tmp_path / f"copied-{index}", excluded)
+ assert len(calls) == 1
+ assert (copied / "fixture.py").read_text() == "synthetic = True\n"
+ assert not (copied / "submodule").exists()
diff --git a/sdk/typescript/src/artifact-export.ts b/sdk/typescript/src/artifact-export.ts
index 76ab58573..993c7b797 100644
--- a/sdk/typescript/src/artifact-export.ts
+++ b/sdk/typescript/src/artifact-export.ts
@@ -1,5 +1,5 @@
import { spawn } from "node:child_process";
-import { realpath } from "node:fs/promises";
+import { lstat, realpath } from "node:fs/promises";
import { basename, dirname, join, relative, resolve } from "node:path";
import { Writable as NodeWritable } from "node:stream";
import { pipeline } from "node:stream/promises";
@@ -264,13 +264,39 @@ export async function resolveArtifactExportOutput(
);
if (arguments_.output !== "-") {
const outputFromCurrent = relative(currentDirectory, arguments_.output);
- if (!isOutsidePath(outputFromCurrent)) {
+ if (outputFromCurrent !== "" && !isOutsidePath(outputFromCurrent)) {
+ let existingParent: string | undefined;
+ for (
+ let directory = dirname(arguments_.output);
+ relative(currentDirectory, directory) !== "";
+ directory = dirname(directory)
+ ) {
+ const metadata = await lstat(directory).catch(
+ (error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") return undefined;
+ throw error;
+ },
+ );
+ if (metadata?.isSymbolicLink()) {
+ throw new CodexSecurityError(
+ "The export output path cannot traverse a repository symlink.",
+ );
+ }
+ if (metadata !== undefined) existingParent ??= directory;
+ }
const canonicalCurrent = await realpath(currentDirectory).catch(
() => currentDirectory,
);
+ const expectedOutput =
+ existingParent === undefined
+ ? resolve(canonicalCurrent, outputFromCurrent)
+ : resolve(
+ await realpath(existingParent),
+ relative(existingParent, arguments_.output),
+ );
if (
- relative(resolve(canonicalCurrent, outputFromCurrent), outputPath) !==
- ""
+ isOutsidePath(relative(canonicalCurrent, outputPath)) ||
+ relative(expectedOutput, outputPath) !== ""
) {
throw new CodexSecurityError(
"The export output path cannot traverse a repository symlink.",
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index ccded69ff..4bb90e321 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -195,6 +195,7 @@ import {
resolveCodexCommand,
resolvePluginPython,
runWorkbench,
+ sameFile,
setCodexSecurityCredentialLogout,
type CodexCommand,
} from "./runtime.js";
@@ -2060,17 +2061,43 @@ export async function main(
}),
output: z.record(z.string(), z.unknown()).optional(),
async run({ args, format }) {
- const repository = resolveCliPath(
+ const requestedRepository = resolveCliPath(
dependencies.currentDirectory(),
args.repository ?? ".",
);
+ const repository = await realpath(requestedRepository).catch(
+ () => requestedRepository,
+ );
return presentHistory(
await history(
["list-repositories"],
async (value): Promise<JsonObject> => {
- const target = (value["repositories"] as JsonObject[]).find(
+ const repositories = value["repositories"] as JsonObject[];
+ let target = repositories.find(
+ (entry) => entry["targetPath"] === requestedRepository,
+ );
+ const canonicalTarget = repositories.find(
(entry) => entry["targetPath"] === repository,
);
+ if (
+ target === undefined &&
+ canonicalTarget !== undefined &&
+ (await sameFile(
+ canonicalTarget["targetPath"] as string,
+ requestedRepository,
+ ))
+ ) {
+ target = canonicalTarget;
+ }
+ if (target === undefined) {
+ for (const entry of repositories) {
+ const storedPath = entry["targetPath"] as string;
+ if (await sameFile(storedPath, requestedRepository)) {
+ target = entry;
+ break;
+ }
+ }
+ }
const findings =
target === undefined
? []
@@ -3138,7 +3165,7 @@ export async function main(
try {
const result = await (
dependencies.checkScanPublication ?? checkScanPublication
- )(resolve(dependencies.currentDirectory(), args.scanDir), {
+ )(resolveCliPath(dependencies.currentDirectory(), args.scanDir), {
...publicationDestination(options, dependencies.environment),
signal: controller.signal,
});
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index 686d10da6..dc379f911 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -1673,8 +1673,8 @@ export async function validateOutputDir(
if (outputDirectory === undefined) {
return null;
}
- requireModelSafeOutputDir(outputDirectory);
const path = resolve(expandHome(outputDirectory));
+ requireModelSafeOutputDir(path);
try {
const metadata = await lstat(path).catch(nullIfMissingFileError);
if (metadata !== null) {
@@ -3283,7 +3283,8 @@ async function hasPluginManifest(root: string): Promise<boolean> {
);
}
-function sameFile(left: string, right: string): Promise<boolean> {
+/** @internal Compare filesystem identity without depending on path spelling. */
+export function sameFile(left: string, right: string): Promise<boolean> {
// NTFS file IDs can exceed JavaScript's safe integer range.
return Promise.all([
stat(left, { bigint: true }),
diff --git a/sdk/typescript/tests-ts/artifact-export.test.ts b/sdk/typescript/tests-ts/artifact-export.test.ts
index d53926a1f..0d8be39ba 100644
--- a/sdk/typescript/tests-ts/artifact-export.test.ts
+++ b/sdk/typescript/tests-ts/artifact-export.test.ts
@@ -1,4 +1,5 @@
import * as childProcess from "node:child_process";
+import * as filesystem from "node:fs/promises";
import { EventEmitter } from "node:events";
import {
cp,
@@ -6,6 +7,8 @@ import {
mkdtemp,
readdir,
readFile,
+ realpath,
+ stat,
rm,
symlink,
writeFile,
@@ -16,13 +19,23 @@ import { PassThrough } from "node:stream";
import { describe, expect, spyOn, test } from "bun:test";
import { exportArtifact } from "../src/index.js";
import {
+ resolveArtifactExportOutput,
readThreatModelPath,
+ runArtifactExport,
runArtifactHelper,
writeThreatModel,
} from "../src/artifact-export.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
import { PYTHON } from "./support/security-policy.js";
+const caseProbe = await mkdtemp(join(tmpdir(), "codex-security-case-probe-"));
+await mkdir(join(caseProbe, "reports"));
+const caseInsensitiveVolume = await stat(join(caseProbe, "REPORTS")).then(
+ () => true,
+ () => false,
+);
+await rm(caseProbe, { recursive: true, force: true });
+
describe("offline artifact export", () => {
test.each([0, 1])(
"preserves split UTF-8 diagnostics at exit %i",
@@ -72,6 +85,144 @@ describe("offline artifact export", () => {
},
);
+ test("resolves the current directory without traversing outside it", async () => {
+ const root = await mkdtemp(join(tmpdir(), "codex-security-cwd-output-"));
+ try {
+ const currentDirectory = join(root, "repository");
+ const scanDir = join(root, "scan");
+ await mkdir(currentDirectory);
+ await mkdir(scanDir);
+ const result = await resolveArtifactExportOutput(
+ { scanDir, output: currentDirectory, format: "json" },
+ currentDirectory,
+ );
+ expect(result.output).toBe(await realpath(currentDirectory));
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ test("resolves a scan-local export before its exports directory exists", async () => {
+ const root = await mkdtemp(join(tmpdir(), "codex-security-new-export-"));
+ try {
+ const scanDir = join(root, "scan");
+ await mkdir(scanDir);
+ const output = join(scanDir, "exports", "findings.json");
+ expect(
+ (
+ await resolveArtifactExportOutput(
+ { scanDir, output, format: "json" },
+ root,
+ )
+ ).output,
+ ).toBe(join(await realpath(scanDir), "exports", "findings.json"));
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ test.skipIf(!caseInsensitiveVolume)(
+ "accepts an export parent accessed through a case alias",
+ async () => {
+ const root = await mkdtemp(join(tmpdir(), "codex-security-case-output-"));
+ await mkdir(join(root, "reports"));
+ try {
+ const result = await resolveArtifactExportOutput(
+ {
+ scanDir: join(root, "scan"),
+ format: "json",
+ output: join(root, "REPORTS", "result.json"),
+ },
+ root,
+ );
+ await writeFile(result.output, "synthetic export");
+ expect(
+ await readFile(join(root, "reports", "result.json"), "utf8"),
+ ).toBe("synthetic export");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+ );
+
+ test("resolves real export directories while refusing linked repository parents", async () => {
+ const root = await mkdtemp(join(tmpdir(), "codex-security-output-path-"));
+ const reports = join(root, "reports");
+ await mkdir(reports);
+ const link = join(root, "linked");
+ await symlink(reports, link, "junction");
+ try {
+ const options = {
+ scanDir: join(root, "scan"),
+ format: "json" as const,
+ output: join(reports, "result.json"),
+ };
+ expect((await resolveArtifactExportOutput(options, root)).output).toBe(
+ join(await realpath(reports), "result.json"),
+ );
+ await expect(
+ resolveArtifactExportOutput(
+ { ...options, output: join(link, "result.json") },
+ root,
+ ),
+ ).rejects.toThrow("cannot traverse a repository symlink");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ test("rejects a repository output ancestor replaced after resolution", async () => {
+ const root = await mkdtemp(
+ join(tmpdir(), "codex-security-export-binding-"),
+ );
+ const repository = join(root, "repository");
+ const scanDir = join(root, "scan");
+ const outside = join(root, "outside");
+ const parent = join(repository, "reports");
+ const outsideOutput = join(outside, "result.md");
+ await mkdir(repository);
+ await mkdir(scanDir);
+ await mkdir(outside);
+ await writeFile(join(scanDir, "THREAT_MODEL.md"), "# Synthetic model\n");
+ await writeFile(outsideOutput, "Unrelated file\n");
+ await symlink(outside, parent, "junction");
+ let replaced = false;
+ const originalRealpath = filesystem.realpath;
+ const resolving = spyOn(filesystem, "realpath").mockImplementation((async (
+ ...args: Parameters<typeof originalRealpath>
+ ) => {
+ const canonical = await originalRealpath(...args);
+ if (args[0] === parent && !replaced) {
+ replaced = true;
+ await rm(parent, { recursive: true, force: true });
+ await mkdir(parent);
+ }
+ return canonical;
+ }) as typeof originalRealpath);
+ try {
+ const exporting = async () => {
+ const prepared = await resolveArtifactExportOutput(
+ {
+ scanDir,
+ output: join(parent, "result.md"),
+ artifact: "threat-model",
+ format: "md",
+ },
+ repository,
+ );
+ await runArtifactExport(prepared);
+ };
+ await expect(exporting()).rejects.toThrow(
+ "cannot traverse a repository symlink",
+ );
+ expect(replaced).toBe(true);
+ expect(await readFile(outsideOutput, "utf8")).toBe("Unrelated file\n");
+ } finally {
+ resolving.mockRestore();
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
test("only exposes a document matching the current canonical model", async () => {
const root = await mkdtemp(join(tmpdir(), "codex-security-current-model-"));
const modelPath = join(root, "threatmodel.md");
diff --git a/sdk/typescript/tests-ts/cli-publish.test.ts b/sdk/typescript/tests-ts/cli-publish.test.ts
index af13c288a..1b1f50421 100644
--- a/sdk/typescript/tests-ts/cli-publish.test.ts
+++ b/sdk/typescript/tests-ts/cli-publish.test.ts
@@ -1,5 +1,5 @@
import { mkdir, rm, symlink, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
+import { homedir, tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { stripVTControlCharacters } from "node:util";
import { afterEach, describe, expect, test, mock } from "bun:test";
@@ -242,69 +242,77 @@ describe("publish scan to custom", () => {
});
describe("publish check", () => {
- test("resolves the shared destination options without invoking publication", async () => {
- const { stdout, stderr, runCli } = createCliTest(main);
+ test.each(["completed-scan", "~/completed-scan"])(
+ "resolves %s and shared options without invoking publication",
+ async (scanDir) => {
+ const { stdout, stderr, runCli } = createCliTest(main);
- const currentDirectory = join(tmpdir(), "codex-security-check-current");
- const result: CheckScanPublicationResult = {
- scanId: "scan-example",
- destination: {
- type: "linear",
- teamId: "team-from-flags",
- projectId: "project-from-flags",
- },
- recorded: [],
- counts: { findings: 2, recorded: 0, pending: 2 },
- access: {
- transport: "linear-api",
- authentication: "verified",
- team: "verified",
- project: "verified",
- assignee: "verified",
- issueCreation: "not-tested",
- },
- };
- const deps = dependencies({
- currentDirectory,
- environment: {
- CODEX_SECURITY_LINEAR_API_KEY: "environment-key",
- CODEX_SECURITY_LINEAR_TEAM: "environment-team",
- },
- });
- deps.publishScan = async () => fail("Check must not publish.");
- deps.checkScanPublication = async (directory, options) => {
- expect(directory).toBe(resolve(currentDirectory, "completed-scan"));
- expect(options).toEqual({
- destination: "linear",
- teamId: "team-from-flags",
- projectId: "project-from-flags",
- linearApiKey: "explicit-key",
- assigneeId: "[email protected]",
- signal: expect.any(AbortSignal),
+ const currentDirectory = join(tmpdir(), "codex-security-check-current");
+ const result: CheckScanPublicationResult = {
+ scanId: "scan-example",
+ destination: {
+ type: "linear",
+ teamId: "team-from-flags",
+ projectId: "project-from-flags",
+ },
+ recorded: [],
+ counts: { findings: 2, recorded: 0, pending: 2 },
+ access: {
+ transport: "linear-api",
+ authentication: "verified",
+ team: "verified",
+ project: "verified",
+ assignee: "verified",
+ issueCreation: "not-tested",
+ },
+ };
+ const deps = dependencies({
+ currentDirectory,
+ environment: {
+ CODEX_SECURITY_LINEAR_API_KEY: "environment-key",
+ CODEX_SECURITY_LINEAR_TEAM: "environment-team",
+ },
});
- return result;
- };
- expect(
- await runCli(
- [
- "publish",
- "check",
- "completed-scan",
- ...DESTINATION_OPTIONS,
- "--linear-api-key",
- "explicit-key",
- "--linear-assignee",
- "--json",
- ],
- deps,
- ),
- ).toBe(0);
- expect(JSON.parse(stdout.text())).toEqual(result);
- expect(stderr.text()).toBe("");
- expect(stdout.text()).not.toContain("explicit-key");
- expect(stdout.text()).not.toContain("[email protected]");
- });
+ deps.publishScan = async () => fail("Check must not publish.");
+ deps.checkScanPublication = async (directory, options) => {
+ expect(directory).toBe(
+ resolve(
+ scanDir.startsWith("~/") ? homedir() : currentDirectory,
+ "completed-scan",
+ ),
+ );
+ expect(options).toEqual({
+ destination: "linear",
+ teamId: "team-from-flags",
+ projectId: "project-from-flags",
+ linearApiKey: "explicit-key",
+ assigneeId: "[email protected]",
+ signal: expect.any(AbortSignal),
+ });
+ return result;
+ };
+ expect(
+ await runCli(
+ [
+ "publish",
+ "check",
+ scanDir,
+ ...DESTINATION_OPTIONS,
+ "--linear-api-key",
+ "explicit-key",
+ "--linear-assignee",
+ "--json",
+ ],
+ deps,
+ ),
+ ).toBe(0);
+ expect(JSON.parse(stdout.text())).toEqual(result);
+ expect(stderr.text()).toBe("");
+ expect(stdout.text()).not.toContain("explicit-key");
+ expect(stdout.text()).not.toContain("[email protected]");
+ },
+ );
test("reports a failed check without publishing or returning a successful result", async () => {
const { stdout, stderr, runCli } = createCliTest(main);
diff --git a/sdk/typescript/tests-ts/cli-workbench.test.ts b/sdk/typescript/tests-ts/cli-workbench.test.ts
index 0085716cd..838340d41 100644
--- a/sdk/typescript/tests-ts/cli-workbench.test.ts
+++ b/sdk/typescript/tests-ts/cli-workbench.test.ts
@@ -1,7 +1,8 @@
import { codexWithRun, jsonCodex } from "./support/codex.js";
-import { mkdir, rm, writeFile } from "node:fs/promises";
+import { mkdir, realpath, rm, symlink, writeFile } from "node:fs/promises";
+import * as fs from "node:fs/promises";
import { join, resolve } from "node:path";
-import { describe, expect, test, mock } from "bun:test";
+import { describe, expect, test, mock, spyOn } from "bun:test";
import type { CodexSecurityConfig, JsonObject } from "../src/index.js";
import { DiffTarget, type ScanOptions } from "../src/index.js";
import { main } from "../src/cli.js";
@@ -25,6 +26,207 @@ import {
} from "./support/cli-run.js";
describe("CLI workbench", () => {
+ test("findings list matches directory identity when realpath preserves alias spelling", async () => {
+ const root = await temporaryDirectory("finding-repository-identity-");
+ const originalRealpath = fs.realpath;
+ let spelling: ReturnType<typeof spyOn> | undefined;
+ try {
+ const repository = join(root, "repository");
+ const upper = join(root, "first-alias");
+ const lower = join(root, "second-alias");
+ const other = join(root, "other");
+ await Promise.all([mkdir(repository), mkdir(other)]);
+ for (const alias of [upper, lower]) {
+ await symlink(
+ repository,
+ alias,
+ process.platform === "win32" ? "junction" : "dir",
+ );
+ }
+ const [upperMetadata, lowerMetadata, otherMetadata] = await Promise.all(
+ [upper, lower, other].map((path) => fs.stat(path, { bigint: true })),
+ );
+ expect(upperMetadata!.ino).toBe(lowerMetadata!.ino);
+ expect(upperMetadata!.dev).toBe(lowerMetadata!.dev);
+ expect(upperMetadata!.ino).not.toBe(otherMetadata!.ino);
+ // Case-insensitive POSIX realpath may retain each alias's spelling.
+ // Keep actual directory stat calls while controlling only that spelling.
+ const preserveSpelling = (async (
+ ...args: Parameters<typeof realpath>
+ ) => {
+ const result = await originalRealpath(...args);
+ const path = args[0];
+ return path === upper || path === lower
+ ? typeof result === "string"
+ ? path
+ : Buffer.from(path)
+ : result;
+ }) as typeof realpath;
+ spelling = spyOn(fs, "realpath").mockImplementation(preserveSpelling);
+ for (const [requested, stored] of [
+ [upper, lower],
+ [lower, upper],
+ ]) {
+ const calls: Array<readonly string[]> = [];
+ const stdout = captureCli(main, "stdout");
+ expect(
+ await stdout.run(
+ ["findings", "list", requested!, "--json"],
+ dependencies({
+ onWorkbench: (args): JsonObject => {
+ calls.push(args);
+ return args[0] === "list-repositories"
+ ? {
+ repositories: [
+ { targetId: "other", targetPath: other },
+ {
+ targetId: "missing",
+ targetPath: join(root, "missing"),
+ },
+ { targetId: "selected", targetPath: stored! },
+ ],
+ }
+ : {
+ findings: [{ title: "Saved finding" }],
+ nextOffset: null,
+ };
+ },
+ }),
+ ),
+ ).toBe(0);
+ expect(calls[1]).toEqual([
+ "list-global-findings",
+ "--target-id",
+ "selected",
+ "--status",
+ "open",
+ ]);
+ expect(JSON.parse(stdout.text()).findings).toEqual([
+ { title: "Saved finding" },
+ ]);
+ }
+ } finally {
+ spelling?.mockRestore();
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ test("findings list prefers an exact saved repository before directory aliases", async () => {
+ const root = await temporaryDirectory("finding-exact-repository-");
+ try {
+ const repository = join(root, "repository");
+ const alias = join(root, "previous-checkout");
+ await mkdir(repository);
+ await symlink(
+ repository,
+ alias,
+ process.platform === "win32" ? "junction" : "dir",
+ );
+ const unsavedAlias = join(root, "selected-checkout");
+ await symlink(
+ repository,
+ unsavedAlias,
+ process.platform === "win32" ? "junction" : "dir",
+ );
+ for (const [requested, first, exact] of [
+ [repository, alias, repository],
+ [alias, repository, alias],
+ [unsavedAlias, alias, repository],
+ ]) {
+ const calls: Array<readonly string[]> = [];
+ const stdout = captureCli(main, "stdout");
+ expect(
+ await stdout.run(
+ ["findings", "list", requested!, "--json"],
+ dependencies({
+ onWorkbench: (args): JsonObject => {
+ calls.push(args);
+ return args[0] === "list-repositories"
+ ? {
+ repositories: [
+ { targetId: "alias-target", targetPath: first! },
+ { targetId: "exact-target", targetPath: exact! },
+ ],
+ }
+ : {
+ findings: [
+ {
+ title:
+ args[2] === "exact-target"
+ ? "Exact saved finding"
+ : "Other target finding",
+ },
+ ],
+ nextOffset: null,
+ };
+ },
+ }),
+ ),
+ ).toBe(0);
+ expect(calls[1]).toEqual([
+ "list-global-findings",
+ "--target-id",
+ "exact-target",
+ "--status",
+ "open",
+ ]);
+ expect(JSON.parse(stdout.text()).findings).toEqual([
+ { title: "Exact saved finding" },
+ ]);
+ }
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ test("findings list resolves a repository directory alias", async () => {
+ const root = await temporaryDirectory("finding-repository-alias-");
+ try {
+ const repository = join(root, "repository");
+ const alias = join(root, "alias");
+ await mkdir(repository);
+ await symlink(
+ repository,
+ alias,
+ process.platform === "win32" ? "junction" : "dir",
+ );
+ const canonical = await realpath(repository);
+ for (const [requested, stored] of [
+ [alias, canonical],
+ [canonical, alias],
+ [alias, alias],
+ ]) {
+ const stdout = captureCli(main, "stdout");
+ expect(
+ await stdout.run(
+ ["findings", "list", requested!, "--json"],
+ dependencies({
+ onWorkbench: (args): JsonObject =>
+ args[0] === "list-repositories"
+ ? {
+ repositories: [
+ {
+ targetId: "other",
+ targetPath: join(root, "missing"),
+ },
+ { targetId: "selected", targetPath: stored! },
+ ],
+ }
+ : {
+ findings: [{ title: "Saved finding" }],
+ nextOffset: null,
+ },
+ }),
+ ),
+ ).toBe(0);
+ expect(JSON.parse(stdout.text()).findings).toEqual([
+ { title: "Saved finding" },
+ ]);
+ }
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
test("lists and summarizes open findings for the current repository", async () => {
const repository = resolve("/current/repository");
const stdout = captureCli(main, "stdout");
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index c039f1d94..282dd9e12 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -5961,6 +5961,9 @@ describe("runtime directories and plugin Python boundary", () => {
const root = await temporaryDirectory();
const absent = join(root, "scan");
expect(await validateOutputDir(absent)).toBe(absent);
+ expect(
+ await validateOutputDir(`${root}/parent/../${basename(absent)}`),
+ ).toBe(absent);
expect(await canonicalizeModelSafePath(join(root, "missing", "scan"))).toBe(
join(root, "missing", "scan"),
);
diff --git a/sdk/typescript/tests-ts/security-policy-helper.test.ts b/sdk/typescript/tests-ts/security-policy-helper.test.ts
index b6674d543..a1210b29b 100644
--- a/sdk/typescript/tests-ts/security-policy-helper.test.ts
+++ b/sdk/typescript/tests-ts/security-policy-helper.test.ts
@@ -5,6 +5,7 @@ import {
existsSync,
mkdirSync,
readFileSync,
+ renameSync,
symlinkSync,
writeFileSync,
} from "node:fs";
@@ -244,6 +245,54 @@ describe("built SECURITY.md helper", () => {
expect(existsSync(join(root, "temporary.tmp"))).toBe(false);
});
+ test
+ .skipIf(process.platform === "win32")
+ .each(["ENOENT", "ENOTDIR", "EACCES"])(
+ "handles %s for an unrelated raw directory entry",
+ (code) => {
+ const { root, output } = fixture();
+ write(root, "SECURITY.md", "root policy\n");
+ write(root, "unrelated.txt", "temporary file\n");
+ const hook = join(output, "raw-entry-race.cjs");
+ write(
+ output,
+ "raw-entry-race.cjs",
+ `
+ const fs = require("node:fs");
+ const readdir = fs.readdirSync;
+ const lstat = fs.lstatSync;
+ const directory = fs.realpathSync.native(${JSON.stringify(root)});
+ const unrelated = require("node:path").join(directory, "unrelated.txt");
+ fs.readdirSync = (path, options) => {
+ if (String(path) !== directory) return readdir(path, options);
+ const entries = readdir(path, { encoding: "buffer" });
+ if (${JSON.stringify(code)} === "ENOENT") fs.unlinkSync(unrelated);
+ return entries;
+ };
+ fs.lstatSync = (path, ...args) => {
+ if (String(path) === unrelated && ${JSON.stringify(code)} !== "ENOENT") {
+ throw Object.assign(new Error("synthetic raw entry ${code}"), { code: ${JSON.stringify(code)} });
+ }
+ return lstat(path, ...args);
+ };
+ require("node:module").syncBuiltinESMExports();
+ `,
+ );
+ const result = run(["--repo", root, "--list"], {
+ ...process.env,
+ NODE_OPTIONS: `${process.env["NODE_OPTIONS"] ?? ""} --require ${JSON.stringify(hook)}`,
+ });
+ if (code === "EACCES") {
+ expect(result.status).toBe(2);
+ expect(result.stderr).toContain("synthetic raw entry EACCES");
+ } else {
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout).toBe('["SECURITY.md"]\n');
+ expect(result.stderr).toBe("");
+ }
+ },
+ );
+
test("frames Unicode paths as ASCII JSON in standard string order", () => {
const { root } = fixture();
for (const name of ["\u{10000}", "\ue000", "\u0080", "\u007f"]) {
@@ -285,12 +334,71 @@ describe("built SECURITY.md helper", () => {
);
write(root, "é\ue000/SECURITY.md", "BMP policy\n");
write(root, "é\u{10000}/SECURITY.md", "supplementary policy\n");
- const result = inventory(root);
- expect(result.status, result.stderr).toBe(0);
- expect(result.stdout).toBe(
- '["SECURITY.md", "\\u00e9\\ud800\\udc00/SECURITY.md", "\\u00e9\\udcff/SECURITY.md", "\\u00e9\\ue000/SECURITY.md"]\n',
+ const rawRoot = Buffer.concat([Buffer.from(root), Buffer.from([0xff])]);
+ renameSync(root, rawRoot);
+ symlinkSync(rawRoot, root);
+ for (const runtime of ["node", process.execPath]) {
+ const result = spawnSync(
+ runtime,
+ [helper, "resolve-security-md", "--repo", root, "--list"],
+ { encoding: "utf8" },
+ );
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout).toBe(
+ '["SECURITY.md", "\\u00e9\\ud800\\udc00/SECURITY.md", "\\u00e9\\udcff/SECURITY.md", "\\u00e9\\ue000/SECURITY.md"]\n',
+ );
+ expect(result.stderr).toBe("");
+ const scoped = spawnSync(
+ runtime,
+ [helper, "resolve-security-md", "--repo", root, "--scope", "."],
+ { encoding: "utf8" },
+ );
+ expect(scoped.status, scoped.stderr).toBe(0);
+ expectGuidance(scoped.stdout, [["SECURITY.md", "root policy"]]);
+ }
+ },
+ );
+
+ test.skipIf(process.platform === "win32")(
+ "reads policies when filesystem directory entry types are unknown",
+ () => {
+ const { root } = fixture();
+ write(root, "SECURITY.md", "root policy\n");
+ write(root, "nested/SECURITY.md", "nested policy\n");
+ const preload = join(dirname(root), "unknown-entry-types.cjs");
+ writeFileSync(
+ preload,
+ `
+const binding = process.binding("fs");
+const original = binding.readdir;
+binding.readdir = function (...args) {
+ const result = original.apply(this, args);
+ if (args[2] === true && result?.[1]) result[1].fill(0);
+ return result;
+};
+`,
);
- expect(result.stderr).toBe("");
+ for (const args of [["--list"], ["--scope", "."]]) {
+ const result = spawnSync(
+ "node",
+ [
+ "--require",
+ preload,
+ helper,
+ "resolve-security-md",
+ "--repo",
+ root,
+ ...args,
+ ],
+ { encoding: "utf8" },
+ );
+ expect(result.status, result.stderr).toBe(0);
+ if (args[0] === "--list") {
+ expect(result.stdout).toBe('["SECURITY.md", "nested/SECURITY.md"]\n');
+ } else {
+ expectGuidance(result.stdout, [["SECURITY.md", "root policy"]]);
+ }
+ }
},
);
diff --git a/sdk/typescript/tests-ts/workbench-canonical-paths.test.ts b/sdk/typescript/tests-ts/workbench-canonical-paths.test.ts
index 9ef602522..b2564e6dd 100644
--- a/sdk/typescript/tests-ts/workbench-canonical-paths.test.ts
+++ b/sdk/typescript/tests-ts/workbench-canonical-paths.test.ts
@@ -1,4 +1,5 @@
import { chmod, mkdir, realpath, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
import { basename, dirname, join } from "node:path";
import { afterEach, describe, expect, test } from "bun:test";
import { PLUGIN_ROOT } from "./plugin-root.js";
@@ -109,6 +110,56 @@ function runPythonProbe(
}
describe("bundled workbench canonical paths", () => {
+ const nativeCaseAliases =
+ runPythonProbe(
+ [
+ "import json, sys, tempfile",
+ "from pathlib import Path",
+ "with tempfile.TemporaryDirectory(dir=sys.argv[2]) as directory:",
+ " target = Path(directory) / 'component'",
+ " target.mkdir()",
+ " alias = target.with_name('COMPONENT')",
+ " print(json.dumps({'supported': alias.exists() and alias.samefile(target)}))",
+ ].join("\n"),
+ tmpdir(),
+ )["supported"] === true;
+
+ test.skipIf(!nativeCaseAliases)(
+ "hashes and inventories native filesystem case aliases for Git roots and components",
+ async () => {
+ const root = await temporaryDirectory();
+ expect(
+ runPythonProbe(
+ [
+ "import json, subprocess, sys",
+ "from pathlib import Path",
+ "sys.path.insert(0, sys.argv[1])",
+ "import workbench_target as target",
+ "root = Path(sys.argv[2])",
+ "repository = root / 'repository'",
+ "repository.mkdir()",
+ "subprocess.run(['git', 'init', '-q', str(repository)], check=True, capture_output=True)",
+ "component = repository / 'component'",
+ "component.mkdir()",
+ "(component / 'app.py').write_text('print(1)\\n')",
+ "(repository / 'root.py').write_text('print(2)\\n')",
+ "scopes = root / 'scopes.json'",
+ "scopes.write_text(json.dumps(['.']))",
+ "output = root / 'inventory.jsonl'",
+ "cases = [(root / 'REPOSITORY', repository, ['component/app.py', 'root.py']), (repository / 'COMPONENT', component, ['app.py'])]",
+ "for selected, original, expected in cases:",
+ " assert selected.samefile(original)",
+ " assert target.directory_content_digest(selected) == target.directory_content_digest(original)",
+ " subprocess.run([sys.executable, str(Path(sys.argv[1]) / 'generate_rank_input.py'), 'make-repo-scope-input', '--repo', str(selected), '--scopes-file', str(scopes), '--out', str(output)], check=True, capture_output=True)",
+ " assert [json.loads(line)['path'] for line in output.read_text().splitlines()] == expected",
+ "print(json.dumps({'targetsChecked': len(cases)}))",
+ ].join("\n"),
+ root,
+ ),
+ ).toEqual({ targetsChecked: 2 });
+ },
+ );
+
test("reads Unicode commit subjects regardless of locale or Git log encoding", async () => {
const repository = await temporaryDirectory();
expect(