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: allow existing scan output directory permissions (#2120)

Suhail Patel11a45947c7dc
diff --git a/docker/README.md b/docker/README.md
index c3cb936f0..8adc454ae 100644
--- a/docker/README.md
+++ b/docker/README.md
@@ -120,12 +120,13 @@ commands, output, and exit codes through the existing scanner entrypoint.
Run these commands from the repository root after
[verifying an image](#image-metadata-and-verification). Keep the verified
-`reference` in the same shell. Prepare private directories and choose the host
-user's UID/GID so the runner can write its bind mounts:
+`reference` in the same shell. Prepare the output and state directories, keep
+state private, and choose the host user's UID/GID so the runner can write its
+bind mounts:
```bash
mkdir -p results state
-chmod 700 results state
+chmod 700 state
export CODEX_SECURITY_USER="$(id -u):$(id -g)"
export CODEX_SECURITY_IMAGE="$reference"
docker compose -f compose.runner.yaml pull
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts
index 440b71529..0f1bc506f 100644
--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts
+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts
@@ -15,6 +15,7 @@ import {
readFile,
realpath,
rm,
+ stat,
symlink,
writeFile,
} from "node:fs/promises";
@@ -767,6 +768,7 @@ model_reasoning_summary = "none"
assertNoError(started);
const resumedScan = started.result.structuredContent.workspace.results;
const resumedScanId = resumedScan.scanId;
+ await chmod(resumedScan.scanDir, 0o755);
const handoffClaimToken = randomUUID();
for (const [id, name, arguments_] of [
[
@@ -999,6 +1001,7 @@ model_reasoning_summary = "none"
threadId: resumedThreadId,
});
assert.equal(finished.status, "succeeded");
+ assert.equal((await stat(resumedScan.scanDir)).mode & 0o777, 0o755);
assert.equal(
finished.coordinatorGeneration,
partial!.coordinatorGeneration + 1,
@@ -1287,7 +1290,8 @@ async function testCliDeepScanEngine({
const threadId = "cli-engine-session";
const register = async (name: string, scoped = false) => {
const scanDir = path.join(canonicalRoot, name);
- await mkdir(scanDir, { mode: 0o700 });
+ await mkdir(scanDir, { mode: 0o775 });
+ await chmod(scanDir, 0o775);
const registration = await runWorkbench(
environment,
[
@@ -1400,6 +1404,7 @@ async function testCliDeepScanEngine({
code: "ENOENT",
});
await launch(completed.scanId);
+ assert.equal((await stat(completed.scanDir)).mode & 0o777, 0o775);
assert.equal(
(await readLogLines(environment.FAKE_CODEX_START_LOG!)).length,
count,
diff --git a/plugins/codex-security/scripts/workbench_db.py b/plugins/codex-security/scripts/workbench_db.py
index 155cbe0b9..be917615c 100644
--- a/plugins/codex-security/scripts/workbench_db.py
+++ b/plugins/codex-security/scripts/workbench_db.py
@@ -3248,10 +3248,8 @@ def require_canonical_scan_directory(scan_dir: Path) -> Path:
scan_dir
):
raise SystemExit("Scan directory must be an existing canonical non-symlink directory.")
- # Re-check privacy so a shared parent cannot be used to substitute forged artifacts.
+ # Re-check ownership and parents so the scan directory cannot be substituted.
if os.name != "nt":
- if stat.S_IMODE(metadata.st_mode) & 0o077:
- raise SystemExit("Scan directory must not be accessible to other users (chmod 700).")
geteuid = getattr(os, "geteuid", None)
effective_uid = geteuid() if geteuid is not None else None
if effective_uid is not None and metadata.st_uid != effective_uid:
diff --git a/plugins/codex-security/tests/test_workbench_scan_archive.py b/plugins/codex-security/tests/test_workbench_scan_archive.py
index 368934956..41a78042c 100644
--- a/plugins/codex-security/tests/test_workbench_scan_archive.py
+++ b/plugins/codex-security/tests/test_workbench_scan_archive.py
@@ -4,6 +4,7 @@ import argparse
import json
import os
import sqlite3
+import stat
import threading
import uuid
from pathlib import Path
@@ -36,15 +37,20 @@ def register_scan(
)
[email protected]("output_mode", [0o700, 0o755, 0o775])
def test_archived_output_preserves_old_scan_and_allows_fresh_registration(
tmp_path: Path,
+ output_mode: int,
) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
scan_dir = tmp_path / "scan"
repository.mkdir()
- scan_dir.mkdir(mode=0o700)
+ scan_dir.mkdir(mode=output_mode)
+ scan_dir.chmod(output_mode)
previous = register_scan(state_dir, repository, scan_dir)
+ if os.name != "nt":
+ assert stat.S_IMODE(scan_dir.stat().st_mode) == output_mode
fail_scan(state_dir, str(previous["scanId"]), "The previous scan was interrupted.")
(scan_dir / "previous.txt").write_text("keep the previous scan\n")
report_path = scan_dir / "report.md"
@@ -61,7 +67,8 @@ def test_archived_output_preserves_old_scan_and_allows_fresh_registration(
)
archived_scan_dir = tmp_path / "scan.previous-test"
scan_dir.rename(archived_scan_dir)
- scan_dir.mkdir(mode=0o700)
+ scan_dir.mkdir(mode=output_mode)
+ scan_dir.chmod(output_mode)
current = register_scan(
state_dir,
@@ -77,6 +84,9 @@ def test_archived_output_preserves_old_scan_and_allows_fresh_registration(
assert current["archivedScanDir"] == str(archived_scan_dir)
assert (archived_scan_dir / "report.md").read_text() == "# Previous scan\n"
assert (archived_scan_dir / "previous.txt").read_text() == "keep the previous scan\n"
+ if os.name != "nt":
+ assert stat.S_IMODE(scan_dir.stat().st_mode) == output_mode
+ assert stat.S_IMODE(archived_scan_dir.stat().st_mode) == output_mode
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
assert connection.execute(
"SELECT scan_dir, status FROM scans WHERE id = ?",
@@ -92,12 +102,14 @@ def test_archived_output_preserves_old_scan_and_allows_fresh_registration(
).fetchone() == (str(archived_scan_dir / "report.md"),)
-def test_empty_failed_scan_can_be_archived_and_reused(tmp_path: Path) -> None:
[email protected]("output_mode", [0o700, 0o755, 0o775])
+def test_empty_failed_scan_can_be_archived_and_reused(tmp_path: Path, output_mode: int) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
scan_dir = tmp_path / "scan"
repository.mkdir()
- scan_dir.mkdir(mode=0o700)
+ scan_dir.mkdir(mode=output_mode)
+ scan_dir.chmod(output_mode)
previous = register_scan(state_dir, repository, scan_dir)
fail_scan(
state_dir, str(previous["scanId"]), "The previous scan failed before writing artifacts."
@@ -116,6 +128,9 @@ def test_empty_failed_scan_can_be_archived_and_reused(tmp_path: Path) -> None:
assert archived_scan_dir.is_dir()
assert not any(archived_scan_dir.iterdir())
assert current["scanDir"] == str(scan_dir)
+ if os.name != "nt":
+ assert stat.S_IMODE(archived_scan_dir.stat().st_mode) == output_mode
+ assert stat.S_IMODE(scan_dir.stat().st_mode) == 0o700
def test_archive_requires_previous_directory_when_artifacts_exist(tmp_path: Path) -> None:
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 93d40045d..f61a4f885 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -174,8 +174,8 @@ try {
Omitting `outputDir` saves results in the private Codex Security state directory.
To choose another location, use a new or empty directory outside the scanned
-repository and its enclosing Git worktree. On macOS and Linux, an existing output
-directory must be private to you (`chmod 700`).
+repository and its enclosing Git worktree. Existing output directories keep their
+permissions; newly created directories are private to you by default.
### Read results
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index cf4448a4f..5a924b881 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -460,8 +460,9 @@ explicit unsupported binary files are rejected. Bulk scans share this context
with every repository.
Use `--output-dir DIR` to choose where a scan saves its results. The directory
-must be empty and outside the scanned directory and enclosing Git worktree. On
-macOS/Linux, existing directories must be private (`chmod 700`).
+must be empty and outside the scanned directory and enclosing Git worktree.
+Existing directories keep their permissions; newly created directories are
+private to you by default.
`--archive-existing` moves earlier output to
`<output-dir>.previous-<timestamp>-<id>`; `--dry-run` previews the move.
@@ -2894,7 +2895,7 @@ from the repository root with the published image:
```bash
mkdir -p results state
-chmod 700 results state
+chmod 700 state
export CODEX_SECURITY_USER="$(id -u):$(id -g)"
export CODEX_SECURITY_IMAGE=ghcr.io/openai/codex-security:latest
docker compose pull codex-security
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index cb9e76c30..17cc39fe9 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -246,7 +246,7 @@ import {
requireOutputOutsideRepositories,
requireOutputOutsideRepository,
requirePrivateCredentialHome,
- requirePrivatePolicyOutputDirectory,
+ preparePolicyOutputDirectory,
resolveCodexCommand,
resolvePluginPath,
resolvePluginPython,
@@ -671,7 +671,7 @@ interface ClientDependencies {
) => Promise<PreparedRuntime>;
resolvePluginPython?: typeof resolvePluginPython;
prepareOutputDir?: typeof prepareOutputDir;
- requirePrivatePolicyOutputDirectory?: typeof requirePrivatePolicyOutputDirectory;
+ preparePolicyOutputDirectory?: typeof preparePolicyOutputDirectory;
prepareScanArtifactRestorer?: typeof prepareScanArtifactRestorer;
repositoryRevision?: typeof repositoryRevision;
resolveCodexCommand?: () => CodexCommand;
@@ -1696,8 +1696,8 @@ export class CodexSecurity {
requireOutputOutsideRepositories(inputs.protectedRoots, outputDir);
requireModelSafeOutputDir(outputDir);
await (
- this.#dependencies.requirePrivatePolicyOutputDirectory ??
- requirePrivatePolicyOutputDirectory
+ this.#dependencies.preparePolicyOutputDirectory ??
+ preparePolicyOutputDirectory
)(outputDir);
if (options.knowledgeBasePaths?.length) {
knowledgeBase = await prepareKnowledgeBase(
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index bd4eb7661..24468acfc 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -10879,7 +10879,7 @@ function protectedRootErrorMessage(
` Reason: ${reason}`,
error.pathKind === "output"
? suggestion === undefined
- ? "Choose a private output directory outside the protected root."
+ ? "Choose an output directory outside the protected root."
: `Re-run with --output-dir ${quoteCliPath(suggestion)}.`
: suggestion === undefined
? "Set TMPDIR (or TEMP on Windows) to a writable directory outside the protected root."
diff --git a/sdk/typescript/src/contract.ts b/sdk/typescript/src/contract.ts
index 3fcd03ba4..aceca16ea 100644
--- a/sdk/typescript/src/contract.ts
+++ b/sdk/typescript/src/contract.ts
@@ -25,7 +25,7 @@ import type {
ScanManifest,
} from "./models.js";
import {
- requirePrivateOutputDirectory,
+ requireOutputDirectoryOwnership,
requireSecureOutputAncestry,
} from "./runtime.js";
import type { NormalizedTarget, ScanMode } from "./targets.js";
@@ -724,16 +724,13 @@ async function requireScanRoot(
throw new Error("not a directory");
}
try {
- requirePrivateOutputDirectory(
- { mode: Number(returned.mode), uid: Number(returned.uid) },
- canonical,
- );
+ requireOutputDirectoryOwnership({ uid: Number(returned.uid) }, canonical);
await requireSecureOutputAncestry(canonical);
} catch (error) {
throw new ContractValidationError(
error instanceof Error
? error.message
- : "Scan directory must remain private to the current user.",
+ : "Scan directory must remain owned by the current user.",
{ cause: error },
);
}
@@ -762,10 +759,7 @@ async function verifyScanRoot(
) {
throw new Error("scan directory changed while reading");
}
- requirePrivateOutputDirectory(
- { mode: Number(current.mode), uid: Number(current.uid) },
- root.path,
- );
+ requireOutputDirectoryOwnership({ uid: Number(current.uid) }, root.path);
await requireSecureOutputAncestry(root.path);
} catch (error) {
throwIfAborted(signal);
diff --git a/sdk/typescript/src/custom-validation.ts b/sdk/typescript/src/custom-validation.ts
index f2cc71bdb..3f2367af1 100644
--- a/sdk/typescript/src/custom-validation.ts
+++ b/sdk/typescript/src/custom-validation.ts
@@ -18,7 +18,7 @@ import {
import { IncompleteScanError, errorMessage } from "./errors.js";
import type { CoverageDocument, FindingsDocument } from "./models.js";
import { isRecord } from "./record.js";
-import { requirePrivateOutputDirectory } from "./runtime.js";
+import { requireOutputDirectoryOwnership } from "./runtime.js";
import type { NormalizedTarget } from "./targets.js";
type Finding = Pick<
@@ -89,7 +89,7 @@ async function writeJson(
throw new IncompleteScanError(
"The scan directory is no longer a real directory.",
);
- requirePrivateOutputDirectory(root, directory);
+ requireOutputDirectoryOwnership(root, directory);
for (const part of name.split("/").slice(0, -1)) {
directory = join(directory, part);
await mkdir(directory, { recursive: true, mode: 0o700 });
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index e34f74337..c49ca468f 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -382,12 +382,17 @@ export async function requirePrivateCredentialHome(
await requirePrivateDirectory(metadata, path, "credential home", options);
}
-export async function requirePrivatePolicyOutputDirectory(
+export async function preparePolicyOutputDirectory(
path: string,
options: Parameters<typeof requirePrivateDirectory>[3] = {},
): Promise<void> {
+ const metadata = await lstat(path);
+ if ((options.platform ?? process.platform) !== "win32") {
+ requireOutputDirectoryOwnership(metadata, path);
+ return;
+ }
await requirePrivateDirectory(
- await lstat(path),
+ metadata,
path,
"policy output directory",
options,
@@ -1786,7 +1791,7 @@ export async function validateOutputDir(
if (!archiveExisting && (await readdir(path)).length !== 0) {
throw new OutputDirectoryNotEmptyError(path);
}
- requirePrivateOutputDirectory(metadata, path);
+ requireOutputDirectoryOwnership(metadata, path);
await requireSecureOutputAncestry(path);
const canonical = await realpath(path);
requireModelSafeOutputDir(canonical);
@@ -2152,7 +2157,7 @@ export async function validatePreparedOutputDir(
`Scan output directory must be empty: ${path}`,
);
}
- requirePrivateOutputDirectory(metadata, path);
+ requireOutputDirectoryOwnership(metadata, path);
await requireSecureOutputAncestry(canonical);
return canonical;
}
@@ -2168,6 +2173,15 @@ export function requirePrivateOutputDirectory(
`Scan output directory must not be accessible to other users (chmod 700): ${path}`,
);
}
+ requireOutputDirectoryOwnership(metadata, path, effectiveUid);
+}
+
+export function requireOutputDirectoryOwnership(
+ metadata: Pick<Stats, "uid">,
+ path: string,
+ effectiveUid = process.geteuid?.(),
+): void {
+ if (process.platform === "win32") return;
if (effectiveUid !== undefined && metadata.uid !== effectiveUid) {
throw new OutputDirectoryError(
`Scan output directory must be owned by the current user: ${path}`,
@@ -2175,7 +2189,7 @@ export function requirePrivateOutputDirectory(
}
}
-/** Reject shared parents whose owner can rename or replace private scan output. */
+/** Reject shared parents whose owner can rename or replace scan output. */
export async function requireSecureOutputAncestry(
path: string,
effectiveUid = process.geteuid?.(),
diff --git a/sdk/typescript/tests-ts/api-events.test.ts b/sdk/typescript/tests-ts/api-events.test.ts
index 7257cb3c5..fbe55f0bf 100644
--- a/sdk/typescript/tests-ts/api-events.test.ts
+++ b/sdk/typescript/tests-ts/api-events.test.ts
@@ -2,7 +2,7 @@ import { copyCompletedScan, PLUGIN_ROOT } from "./plugin-root.js";
import { once } from "node:events";
import { chmod, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import {
Codex,
type McpToolCallItem,
@@ -1002,11 +1002,18 @@ test.skipIf(process.platform === "win32")(
"preserves unsafe scan-root diagnostics instead of reporting missing files",
async () => {
const scanDir = await copyCompletedScan(await temporaryDirectory());
- await chmod(scanDir, 0o755);
- await expect(runEvents(scanDir, completedEvents())).rejects.toMatchObject({
- name: ContractValidationError.name,
- message: expect.stringContaining("chmod 700"),
- cause: expect.any(Error),
- });
+ const parent = dirname(scanDir);
+ await chmod(parent, 0o777);
+ try {
+ await expect(runEvents(scanDir, completedEvents())).rejects.toMatchObject(
+ {
+ name: ContractValidationError.name,
+ message: expect.stringContaining("sticky bit"),
+ cause: expect.any(Error),
+ },
+ );
+ } finally {
+ await chmod(parent, 0o700);
+ }
},
);
diff --git a/sdk/typescript/tests-ts/api-policy.test.ts b/sdk/typescript/tests-ts/api-policy.test.ts
index b700eb3e2..dad43b350 100644
--- a/sdk/typescript/tests-ts/api-policy.test.ts
+++ b/sdk/typescript/tests-ts/api-policy.test.ts
@@ -114,7 +114,7 @@ async function setup(
pythonSelections.push(selection);
return PYTHON;
},
- requirePrivatePolicyOutputDirectory: async (path: string) => {
+ preparePolicyOutputDirectory: async (path: string) => {
await options.secureOutput?.(path);
},
repositoryRevision: async () => {
@@ -423,10 +423,10 @@ describe("CodexSecurity policy API", () => {
},
);
- test("requires private output before starting a policy turn", async () => {
+ test("prepares output permissions before starting a policy turn", async () => {
const onOutputDirReady = mock();
const secured = mock(async (_path: string) => {
- throw new Error("Policy output could not be made private");
+ throw new Error("Policy output permissions could not be prepared");
});
const f = await setup({
secureOutput: secured,
@@ -436,7 +436,7 @@ describe("CodexSecurity policy API", () => {
outputDir: f.outputDir,
onOutputDirReady,
}),
- ).rejects.toThrow("Policy output could not be made private");
+ ).rejects.toThrow("Policy output permissions could not be prepared");
expect(secured.mock.calls.map(([value]) => value)).toEqual([f.outputDir]);
expect(onOutputDirReady).not.toHaveBeenCalled();
expect(f.threads).toHaveLength(0);
diff --git a/sdk/typescript/tests-ts/api-validation-persistence.test.ts b/sdk/typescript/tests-ts/api-validation-persistence.test.ts
index 4ab4fb12f..15d89b6ab 100644
--- a/sdk/typescript/tests-ts/api-validation-persistence.test.ts
+++ b/sdk/typescript/tests-ts/api-validation-persistence.test.ts
@@ -5,6 +5,7 @@ import {
readFile,
realpath,
rm,
+ stat,
writeFile,
} from "node:fs/promises";
import { join, relative } from "node:path";
@@ -163,7 +164,7 @@ describe("CodexSecurity finding validation", () => {
"modified",
"git metadata",
"unbound",
- ...(process.platform === "win32" ? [] : ["insecure permissions"]),
+ ...(process.platform === "win32" ? [] : ["shared permissions"]),
])(
"checks saved validation evidence before cache reuse: %s",
async (change) => {
@@ -217,21 +218,22 @@ describe("CodexSecurity finding validation", () => {
join(first.outputDir, ".git", "HEAD"),
"Changed metadata.\n",
);
- if (change === "insecure permissions")
- await chmod(first.outputDir, 0o777);
+ if (change === "shared permissions") await chmod(first.outputDir, 0o777);
const second = await client.validate(request);
- expect(modelCalls).toBe(change === "unchanged" ? 1 : 2);
+ const reusesEvidence =
+ change === "unchanged" || change === "shared permissions";
+ expect(modelCalls).toBe(reusesEvidence ? 1 : 2);
expect(await readFile(join(second.outputDir, "proof.txt"), "utf8")).toBe(
`Synthetic evidence ${modelCalls}.\n`,
);
expect(await client.validate(request)).toEqual(second);
- expect(modelCalls).toBe(change === "unchanged" ? 1 : 2);
- if (change === "insecure permissions") {
- expect(second.outputDir).not.toBe(first.outputDir);
+ expect(modelCalls).toBe(reusesEvidence ? 1 : 2);
+ if (change === "shared permissions") {
+ expect(second.outputDir).toBe(first.outputDir);
+ expect((await stat(first.outputDir)).mode & 0o777).toBe(0o777);
expect(await readFile(join(first.outputDir, "proof.txt"), "utf8")).toBe(
"Synthetic evidence 1.\n",
);
- await chmod(first.outputDir, 0o700);
}
},
);
@@ -257,10 +259,8 @@ describe("CodexSecurity finding validation", () => {
expect(modelCalls).toBe(1);
if (process.platform !== "win32") {
await chmod(first.outputDir, 0o770);
- await expect(client.validate(request)).rejects.toThrow(
- "must not be accessible to other users",
- );
- await chmod(first.outputDir, 0o700);
+ expect(await client.validate(request)).toEqual(first);
+ expect((await stat(first.outputDir)).mode & 0o777).toBe(0o770);
}
await writeFile(join(first.outputDir, "proof.txt"), "Changed evidence.\n");
await expect(client.validate(request)).rejects.toBeInstanceOf(
diff --git a/sdk/typescript/tests-ts/cli-output-directory.test.ts b/sdk/typescript/tests-ts/cli-output-directory.test.ts
new file mode 100644
index 000000000..82522a051
--- /dev/null
+++ b/sdk/typescript/tests-ts/cli-output-directory.test.ts
@@ -0,0 +1,131 @@
+import { chmod, mkdir, stat, symlink, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { afterEach, describe, expect, mock, test } from "bun:test";
+import { main } from "../src/cli.js";
+import { validateOutputDir } from "../src/runtime.js";
+import { dependencies } from "./cli-fixtures.js";
+import { git } from "./git-fixture.js";
+import { createCliTest } from "./support/cli-run.js";
+import { createApiTestFixtures } from "./support/temporary-directories.js";
+
+const fixtures = createApiTestFixtures("codex-security-cli-output-");
+afterEach(fixtures.cleanup);
+
+async function scanFixture() {
+ const root = await fixtures.temporaryDirectory();
+ const repository = join(root, "repository");
+ const output = join(root, "results");
+ await mkdir(repository);
+ git(repository, "init", "-q");
+ const started = mock();
+ const deps = dependencies({
+ currentDirectory: repository,
+ onRun: started,
+ });
+ const createSecurity = deps.createSecurity;
+ deps.createSecurity = (config) => {
+ const security = createSecurity(config);
+ return {
+ ...security,
+ run: async (target, options) => {
+ await validateOutputDir(options?.outputDir, options?.archiveExisting);
+ return security.run(target, options);
+ },
+ preflight: async (target, options) => {
+ await validateOutputDir(options?.outputDir, options?.archiveExisting);
+ return security.preflight(target, options);
+ },
+ };
+ };
+ return { root, output, started, deps };
+}
+
+describe("CLI output directory permissions", () => {
+ test.skipIf(process.platform === "win32").each([
+ ["standard", [], 0o755],
+ ["deep", [], 0o775],
+ ["standard", ["--headless"], 0o770],
+ ] as const)(
+ "preserves existing permissions for a %s scan %j",
+ async (mode, flags, permissions) => {
+ const { output, started, deps } = await scanFixture();
+ await mkdir(output);
+ await chmod(output, permissions);
+ const { runCli } = createCliTest(main, { stderr: true });
+
+ expect(
+ await runCli(
+ ["scan", ".", "--mode", mode, "--output-dir", output, ...flags],
+ deps,
+ ),
+ ).toBe(0);
+ expect((await stat(output)).mode & 0o777).toBe(permissions);
+ expect(started).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ test.skipIf(process.platform === "win32")(
+ "accepts existing permissions during non-interactive scans and dry runs",
+ async () => {
+ for (const scenario of [
+ { flags: ["--json"] },
+ { flags: ["--format", "jsonl"] },
+ { flags: ["--dry-run"], dryRun: true },
+ { environment: { CI: "true" } },
+ { environment: { TERM: "dumb" } },
+ { terminal: false },
+ ]) {
+ const { output, started, deps } = await scanFixture();
+ await mkdir(output);
+ await chmod(output, 0o755);
+ deps.environment = scenario.environment ?? {};
+ const { runCli } = createCliTest(main, {
+ stderr: scenario.terminal !== false,
+ });
+
+ expect(
+ await runCli(
+ ["scan", ".", "--output-dir", output, ...(scenario.flags ?? [])],
+ deps,
+ ),
+ ).toBe(0);
+ expect((await stat(output)).mode & 0o777).toBe(0o755);
+ expect(started).toHaveBeenCalledTimes(scenario.dryRun ? 0 : 1);
+ }
+ },
+ );
+
+ test.each(["missing", "private"])(
+ "accepts a %s output directory",
+ async (state) => {
+ const { output, started, deps } = await scanFixture();
+ if (state === "private") await mkdir(output, { mode: 0o700 });
+ const { runCli } = createCliTest(main, { stderr: true });
+
+ expect(await runCli(["scan", ".", "--output-dir", output], deps)).toBe(0);
+ expect(started).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ test.skipIf(process.platform === "win32")(
+ "still rejects nonempty or linked output directories",
+ async () => {
+ for (const state of ["nonempty", "symlink"] as const) {
+ const { root, output, started, deps } = await scanFixture();
+ const actual =
+ state === "symlink" ? join(root, "actual-results") : output;
+ await mkdir(actual);
+ await chmod(actual, 0o755);
+ if (state === "symlink") await symlink(actual, output, "dir");
+ else await writeFile(join(output, "previous.txt"), "previous scan\n");
+ const { runCli } = createCliTest(main, { stderr: true });
+
+ expect(await runCli(["scan", ".", "--output-dir", output], deps)).toBe(
+ 2,
+ );
+ expect((await stat(actual)).mode & 0o777).toBe(0o755);
+ expect(started).not.toHaveBeenCalled();
+ }
+ },
+ );
+});
diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts
index ced943770..6b3daf6cd 100644
--- a/sdk/typescript/tests-ts/cli.test.ts
+++ b/sdk/typescript/tests-ts/cli.test.ts
@@ -4542,7 +4542,7 @@ describe("CLI", () => {
[
"output directory rejected",
new OutputDirectoryError(
- "Scan output directory must not be accessible to other users (chmod 700): /out",
+ "Scan output directory must be owned by the current user: /out",
),
],
[
diff --git a/sdk/typescript/tests-ts/contract.test.ts b/sdk/typescript/tests-ts/contract.test.ts
index 566a6ab23..41289d7a7 100644
--- a/sdk/typescript/tests-ts/contract.test.ts
+++ b/sdk/typescript/tests-ts/contract.test.ts
@@ -725,14 +725,19 @@ describe("canonical scan contract", () => {
).rejects.toMatchObject({ name: "AbortError" });
});
- test.skipIf(process.platform === "win32")(
- "rejects a scan directory that is no longer private to the current user",
- async () => {
+ test.skipIf(process.platform === "win32").each([0o755, 0o775])(
+ "reads a scan directory with mode %o without changing its permissions",
+ async (mode) => {
const scanDir = await copyExample();
- await chmod(scanDir, 0o755);
+ await chmod(scanDir, mode);
await expect(
loadContract(scanDir, { pluginRoot: PLUGIN_ROOT }),
- ).rejects.toThrow("must not be accessible to other users");
+ ).resolves.toBeDefined();
+ const exported = pythonExport(scanDir);
+ expect(exported.exitCode, new TextDecoder().decode(exported.stderr)).toBe(
+ 0,
+ );
+ expect((await lstat(scanDir)).mode & 0o777).toBe(mode);
},
);
diff --git a/sdk/typescript/tests-ts/custom-validation.test.ts b/sdk/typescript/tests-ts/custom-validation.test.ts
index df1a3873c..fc1a13ae1 100644
--- a/sdk/typescript/tests-ts/custom-validation.test.ts
+++ b/sdk/typescript/tests-ts/custom-validation.test.ts
@@ -1,11 +1,13 @@
import { execFileSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import {
+ chmod,
cp,
mkdir,
readFile,
rename,
rm,
+ stat,
symlink,
writeFile,
type FileHandle,
@@ -458,8 +460,9 @@ describe("custom validation", () => {
},
);
- test("applies dispositions and assessments without changing source identity", async () => {
+ test("applies dispositions and assessments without changing source identity or output permissions", async () => {
const f = await fixture(4);
+ if (process.platform !== "win32") await chmod(f.scanDir, 0o755);
const output = result(
"reportable",
"suppressed",
@@ -514,6 +517,8 @@ describe("custom validation", () => {
return JSON.stringify(output);
},
});
+ if (process.platform !== "win32")
+ expect((await stat(f.scanDir)).mode & 0o777).toBe(0o755);
const findings = await json<FindingsDocument>(
join(f.scanDir, "findings.json"),
);
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index 6be4227e9..f227d99d9 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -88,8 +88,8 @@ import {
environmentWithGit,
requirePrivateCredentialHome,
requirePrivateCredentialFile,
- requirePrivateOutputDirectory,
- requirePrivatePolicyOutputDirectory,
+ requireOutputDirectoryOwnership,
+ preparePolicyOutputDirectory,
requireSecureCredentialHome,
requireSecureOutputAncestry,
requireTrustedOutputAncestor,
@@ -3510,13 +3510,13 @@ describe("runtime directories and plugin Python boundary", () => {
for (const [description, secure] of [
[
"credential home",
- (options: Parameters<typeof requirePrivatePolicyOutputDirectory>[1]) =>
+ (options: Parameters<typeof preparePolicyOutputDirectory>[1]) =>
requirePrivateCredentialHome(metadata, home, options),
],
[
"policy output directory",
- (options: Parameters<typeof requirePrivatePolicyOutputDirectory>[1]) =>
- requirePrivatePolicyOutputDirectory(home, options),
+ (options: Parameters<typeof preparePolicyOutputDirectory>[1]) =>
+ preparePolicyOutputDirectory(home, options),
],
] as const) {
await secure({
@@ -4698,7 +4698,7 @@ describe("runtime directories and plugin Python boundary", () => {
"*S-1-1-0:(OI)(CI)R",
]);
expect(grant.status, grant.stderr).toBe(0);
- await requirePrivatePolicyOutputDirectory(output);
+ await preparePolicyOutputDirectory(output);
const draft = join(output, "THREAT_MODEL.md");
await writeFile(draft, "Synthetic private draft\n");
const descriptor = inspectWindowsTestAcl(
@@ -5754,20 +5754,12 @@ describe("runtime directories and plugin Python boundary", () => {
},
);
- testPosix("rejects private output directories owned by another user", () => {
+ testPosix("rejects output directories owned by another user", () => {
expect(() =>
- requirePrivateOutputDirectory(
- { mode: 0o40700, uid: 1001 },
- "/scan",
- 1000,
- ),
+ requireOutputDirectoryOwnership({ uid: 1001 }, "/scan", 1000),
).toThrow("must be owned by the current user");
expect(() =>
- requirePrivateOutputDirectory(
- { mode: 0o40700, uid: 1000 },
- "/scan",
- 1000,
- ),
+ requireOutputDirectoryOwnership({ uid: 1000 }, "/scan", 1000),
).not.toThrow();
});
@@ -5845,7 +5837,7 @@ describe("runtime directories and plugin Python boundary", () => {
).not.toThrow();
});
- test("prepares a private output directory without moving prior results", async () => {
+ test("prepares an output directory without moving prior results", async () => {
const root = await temporaryDirectory();
const output = join(root, "scan");
await mkdir(output, { mode: 0o700 });
@@ -5885,10 +5877,17 @@ describe("runtime directories and plugin Python boundary", () => {
);
await chmod(output, 0o770);
- await expect(validateOutputDir(output, true)).rejects.toThrow(
- "must not be accessible to other users",
- );
- await chmod(output, 0o700);
+ expect(await validateOutputDir(output, true)).toBe(output);
+ expect(
+ await prepareScanRegistrationOutput(
+ output,
+ "repo",
+ undefined,
+ undefined,
+ true,
+ ),
+ ).toBe(output);
+ expect((await stat(output)).mode & 0o777).toBe(0o770);
}
expect(await planOutputArchive(output)).not.toBeNull();
@@ -6048,18 +6047,13 @@ describe("runtime directories and plugin Python boundary", () => {
if (process.platform !== "win32") {
const callerOwned = join(root, "caller-owned");
await mkdir(callerOwned, { mode: 0o700 });
- for (const mode of [0o770, 0o777]) {
+ for (const mode of [0o700, 0o755, 0o770, 0o775, 0o777]) {
await chmod(callerOwned, mode);
- await expect(validateOutputDir(callerOwned)).rejects.toThrow(
- "must not be accessible to other users",
- );
- await expect(prepareOutputDir(callerOwned, "repo")).rejects.toThrow(
- "must not be accessible to other users",
- );
+ expect(await validateOutputDir(callerOwned)).toBe(callerOwned);
+ expect(await prepareOutputDir(callerOwned, "repo")).toBe(callerOwned);
+ await preparePolicyOutputDirectory(callerOwned);
+ expect((await stat(callerOwned)).mode & 0o777).toBe(mode);
}
- await chmod(callerOwned, 0o700);
- expect(await prepareOutputDir(callerOwned, "repo")).toBe(callerOwned);
- expect((await stat(callerOwned)).mode & 0o777).toBe(0o700);
}
if (process.platform !== "win32") {
const filesystemChild = join(
diff --git a/sdk/typescript/tests-ts/scan-resume.test.ts b/sdk/typescript/tests-ts/scan-resume.test.ts
index 5647f3c3e..24e2261bc 100644
--- a/sdk/typescript/tests-ts/scan-resume.test.ts
+++ b/sdk/typescript/tests-ts/scan-resume.test.ts
@@ -7,12 +7,14 @@ import { randomUUID } from "node:crypto";
import { stripVTControlCharacters } from "node:util";
import {
appendFile,
+ chmod,
cp,
mkdir,
readFile,
readdir,
rename,
rm,
+ stat,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
@@ -382,8 +384,9 @@ test.each([
},
);
-test("CLI resumes through native execution with current permissions and preserves interrupted state", async () => {
+test("CLI resumes through native execution with current permissions and preserves interrupted state and output permissions", async () => {
const f = await interruptedScan();
+ if (process.platform !== "win32") await chmod(f.scanDir, 0o755);
const feedbackPath = join(
f.scanDir,
"artifacts",
@@ -479,6 +482,8 @@ test("CLI resumes through native execution with current permissions and preserve
return {
id: threadId,
async runStreamed(prompt) {
+ if (process.platform !== "win32")
+ expect((await stat(f.scanDir)).mode & 0o777).toBe(0o755);
expect(await readFile(feedbackPath, "utf8")).toBe(
originalFeedback,
);
@@ -524,6 +529,8 @@ test("CLI resumes through native execution with current permissions and preserve
).toMatchObject({ progress: { status: "running" } });
expect(await readFile(f.checkpoint, "utf8")).toBe('{"completed":"setup"}\n');
expect(await readFile(feedbackPath, "utf8")).toBe(originalFeedback);
+ if (process.platform !== "win32")
+ expect((await stat(f.scanDir)).mode & 0o777).toBe(0o755);
});
test("resumed Bedrock scans retain provider context for the account advisory", async () => {