OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix: keep scan output private through completion and exports (#118)
mldangelo-oai01532a58cbcc
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py b/sdk/typescript/_bundled_plugin/scripts/workbench_db.pyindex b0779226b..c2c36845e 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py@@ -3476,6 +3476,38 @@ 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 on every resolution so a mid-scan rename/replace under a+ # shared parent cannot substitute another user's forged artifact tree.+ 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:+ raise SystemExit("Scan directory must be owned by the current user.")+ for parent in scan_dir.parents:+ try:+ parent_metadata = parent.lstat()+ except OSError as exc:+ raise SystemExit("Scan output parent could not be inspected.") from exc+ if not stat.S_ISDIR(parent_metadata.st_mode) or stat.S_ISLNK(+ parent_metadata.st_mode+ ):+ raise SystemExit("Scan output parent must be a non-symlink directory.")+ if effective_uid is not None and parent_metadata.st_uid not in {+ 0,+ effective_uid,+ }:+ raise SystemExit("Scan output parent must have a trusted owner.")+ if (+ stat.S_IMODE(parent_metadata.st_mode) & 0o022+ and not parent_metadata.st_mode & stat.S_ISVTX+ ):+ raise SystemExit(+ "Scan output parent must not be group- or world-writable without the sticky bit."+ )return scan_dirdiff --git a/sdk/typescript/src/contract.ts b/sdk/typescript/src/contract.tsindex 7508bd609..454d77f0f 100644--- a/sdk/typescript/src/contract.ts+++ b/sdk/typescript/src/contract.ts@@ -17,6 +17,10 @@ import type {FindingsDocument,ScanManifest,} from "./models.js";+import {+ requirePrivateOutputDirectory,+ requireSecureOutputAncestry,+} from "./runtime.js";import type { NormalizedTarget, ScanMode } from "./targets.js";const DOCUMENTS = {@@ -581,9 +585,21 @@ async function requireScanRoot() {throw new Error("not a directory");}+ try {+ requirePrivateOutputDirectory(returned, canonical);+ await requireSecureOutputAncestry(canonical);+ } catch (error) {+ throw new ContractValidationError(+ error instanceof Error+ ? error.message+ : "Scan directory must remain private to the current user.",+ { cause: error },+ );+ }return { path: canonical, metadata: returned };} catch (error) {throwIfAborted(signal);+ if (error instanceof ContractValidationError) throw error;throw new ContractValidationError("Scan directory must be an existing non-symlink directory.",{ cause: error },@@ -606,6 +622,8 @@ async function verifyScanRoot() {throw new Error("scan directory changed while reading");}+ requirePrivateOutputDirectory(current, root.path);+ await requireSecureOutputAncestry(root.path);} catch (error) {throwIfAborted(signal);throw new ContractValidationError(diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 93b98c5eb..a608ddbfa 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -567,6 +567,7 @@ export async function validateOutputDir();}requirePrivateOutputDirectory(metadata, path);+ await requireSecureOutputAncestry(path);const canonical = await realpath(path);requireModelSafeOutputDir(canonical);return canonical;@@ -581,6 +582,7 @@ export async function validateOutputDir(relative(parent, path),);requireModelSafeOutputDir(canonical);+ await requireSecureOutputAncestry(canonical);return canonical;}break;@@ -704,6 +706,7 @@ export async function validatePreparedOutputDir();}requirePrivateOutputDirectory(metadata, path);+ await requireSecureOutputAncestry(canonical);return canonical;}@@ -725,6 +728,78 @@ export function requirePrivateOutputDirectory(}}+/** Reject shared parents whose owner can rename or replace private scan output. */+export async function requireSecureOutputAncestry(+ path: string,+ effectiveUid = process.geteuid?.(),+): Promise<void> {+ if (process.platform === "win32") return;+ let current = dirname(resolve(path));+ while (true) {+ try {+ current = await realpath(current);+ break;+ } catch (error) {+ if (nodeErrorCode(error) !== "ENOENT") {+ throw new OutputDirectoryError(+ `Unable to inspect scan output parent directory: ${current}`,+ { cause: error },+ );+ }+ const parent = dirname(current);+ if (parent === current) {+ throw new OutputDirectoryError(+ `Unable to inspect scan output parent directory: ${current}`,+ { cause: error },+ );+ }+ current = parent;+ }+ }+ while (true) {+ let metadata: Stats;+ try {+ metadata = await lstat(current);+ } catch (error) {+ throw new OutputDirectoryError(+ `Unable to inspect scan output parent directory: ${current}`,+ { cause: error },+ );+ }+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {+ throw new OutputDirectoryError(+ `Scan output parent must be a non-symlink directory: ${current}`,+ );+ }+ requireTrustedOutputAncestor(metadata, current, effectiveUid);+ const parent = dirname(current);+ if (parent === current) return;+ current = parent;+ }+}++export function requireTrustedOutputAncestor(+ metadata: Pick<Stats, "mode" | "uid">,+ path: string,+ effectiveUid = process.geteuid?.(),+): void {+ if (+ effectiveUid !== undefined &&+ metadata.uid !== 0 &&+ metadata.uid !== effectiveUid+ ) {+ throw new OutputDirectoryError(+ `Scan output parent must have a trusted owner: ${path}`,+ );+ }+ if ((metadata.mode & 0o022) === 0) return;+ if ((metadata.mode & 0o1000) === 0) {+ throw new OutputDirectoryError(+ `Scan output parent must not be group- or world-writable without the sticky bit: ${path}`,+ );+ }+}+async function removeEmptyDirectories(path: string,root: string,diff --git a/sdk/typescript/tests-ts/contract.test.ts b/sdk/typescript/tests-ts/contract.test.tsindex c61322ea0..1d9ac158d 100644--- a/sdk/typescript/tests-ts/contract.test.ts+++ b/sdk/typescript/tests-ts/contract.test.ts@@ -1,5 +1,6 @@import { createHash } from "node:crypto";import {+ chmod,cp,mkdir,mkdtemp,@@ -32,6 +33,7 @@ async function copyExample(): Promise<string> {temporaryDirectories.push(root);const scanDir = join(root, "scan");await cp(EXAMPLE, scanDir, { recursive: true });+ if (process.platform !== "win32") await chmod(scanDir, 0o700);return scanDir;}@@ -124,6 +126,34 @@ 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 () => {+ const scanDir = await copyExample();+ await chmod(scanDir, 0o755);+ await expect(+ loadContract(scanDir, { pluginRoot: PLUGIN_ROOT }),+ ).rejects.toThrow("must not be accessible to other users");+ },+ );++ test.skipIf(process.platform === "win32")(+ "rejects a private scan beneath an insecure shared ancestor",+ async () => {+ const scanDir = await copyExample();+ const parent = dirname(scanDir);+ await chmod(parent, 0o777);++ try {+ await expect(+ loadContract(scanDir, { pluginRoot: PLUGIN_ROOT }),+ ).rejects.toThrow("sticky bit");+ } finally {+ await chmod(parent, 0o700);+ }+ },+ );+test.skipIf(process.platform === "win32")("accepts a scan directory beneath a symlinked parent",async () => {@@ -134,7 +164,9 @@ describe("canonical scan contract", () => {const parent = join(root, "actual-parent");const linkedParent = join(root, "linked-parent");await mkdir(parent);- await cp(EXAMPLE, join(parent, "scan"), { recursive: true });+ const scanDir = join(parent, "scan");+ await cp(EXAMPLE, scanDir, { recursive: true });+ if (process.platform !== "win32") await chmod(scanDir, 0o700);await symlink(parent, linkedParent);await expect(diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex aa334915e..613d88310 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -57,6 +57,8 @@ import {preparePersistentScanRoot,requirePrivateCredentialHome,requirePrivateOutputDirectory,+ requireSecureOutputAncestry,+ requireTrustedOutputAncestor,runWorkbench,setCodexSecurityCredentialLogout,} from "../src/runtime.js";@@ -1664,6 +1666,80 @@ describe("runtime directories and plugin Python boundary", () => {).not.toThrow();});+ testPosix(+ "rejects scan output under a non-sticky shared parent directory",+ async () => {+ const root = await temporaryDirectory();+ const shared = join(root, "shared");+ await mkdir(shared, { mode: 0o777 });+ await chmod(shared, 0o777);+ const output = join(shared, "results");++ await expect(prepareOutputDir(output, "repo")).rejects.toThrow(+ "sticky bit",+ );+ await expect(requireSecureOutputAncestry(output)).rejects.toThrow(+ "sticky bit",+ );+ },+ );++ testPosix(+ "accepts scan output under a sticky shared parent directory",+ async () => {+ const root = await temporaryDirectory();+ const shared = join(root, "shared");+ await mkdir(shared, { mode: 0o1777 });+ await chmod(shared, 0o1777);+ // Some filesystems (notably user dirs on macOS APFS) ignore sticky on+ // chmod; fall back to the process temp root when it is already sticky.+ let stickyParent = shared;+ if (((await lstat(shared)).mode & 0o1000) === 0) {+ stickyParent = await realpath(tmpdir());+ if (((await lstat(stickyParent)).mode & 0o1000) === 0) {+ return;+ }+ }+ const output = join(+ stickyParent,+ `codex-security-sticky-${process.pid}-${Date.now()}`,+ );+ temporaryDirectories.push(output);++ await expect(+ requireSecureOutputAncestry(output),+ ).resolves.toBeUndefined();+ expect(await prepareOutputDir(output, "repo")).toBe(output);+ },+ );++ testPosix("rejects sticky shared parents controlled by another user", () => {+ expect(() =>+ requireTrustedOutputAncestor(+ { mode: 0o41777, uid: 1001 },+ "/shared",+ 1000,+ ),+ ).toThrow("trusted owner");+ expect(() =>+ requireTrustedOutputAncestor(+ { mode: 0o40755, uid: 1001 },+ "/other-user",+ 1000,+ ),+ ).toThrow("trusted owner");+ expect(() =>+ requireTrustedOutputAncestor(+ { mode: 0o41777, uid: 1000 },+ "/shared",+ 1000,+ ),+ ).not.toThrow();+ expect(() =>+ requireTrustedOutputAncestor({ mode: 0o41777, uid: 0 }, "/tmp", 1000),+ ).not.toThrow();+ });+test("archives a non-empty private output directory", async () => {const root = await temporaryDirectory();const output = join(root, "scan");diff --git a/sdk/typescript/tests-ts/support/api-events.ts b/sdk/typescript/tests-ts/support/api-events.tsindex 011dfc6bc..9c0975679 100644--- a/sdk/typescript/tests-ts/support/api-events.ts+++ b/sdk/typescript/tests-ts/support/api-events.ts@@ -1,4 +1,4 @@-import { cp, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";+import { chmod, cp, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import type { ThreadEvent } from "@openai/codex-sdk";@@ -31,6 +31,7 @@ export function createApiTestFixtures() {await cp(join(PLUGIN_ROOT, "examples", "completed-scan"), scanDir, {recursive: true,});+ await chmod(scanDir, 0o700);await writeFile(join(scanDir, "report.md"), "# Scan report\n");return scanDir;},diff --git a/sdk/typescript/tests-ts/workbench-canonical-paths.test.ts b/sdk/typescript/tests-ts/workbench-canonical-paths.test.tsindex 356215b15..dd04b8236 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,mkdtemp,realpath,@@ -13,6 +14,7 @@ import { PLUGIN_ROOT } from "./plugin-root.js";const temporaryDirectories: string[] = [];const testCaseSensitive = process.platform === "linux" ? test : test.skip;+const testPosix = process.platform === "win32" ? test.skip : test;const testWindows = process.platform === "win32" ? test : test.skip;const simulatedPathProbe = [@@ -127,6 +129,41 @@ function runPythonProbe(}describe("bundled workbench canonical paths", () => {+ testPosix(+ "rejects private scan directories under insecure shared parents",+ async () => {+ const root = await temporaryDirectory();+ const scanDirectory = join(root, "scan");+ await mkdir(scanDirectory, { mode: 0o700 });+ await chmod(root, 0o777);++ try {+ expect(+ runPythonProbe(+ [+ "import json, sys",+ "from pathlib import Path",+ "sys.path.insert(0, sys.argv[1])",+ "import workbench_db as workbench",+ "try:",+ " workbench.require_canonical_scan_directory(Path(sys.argv[2]))",+ "except SystemExit as error:",+ " print(json.dumps({'accepted': False, 'error': str(error)}))",+ "else:",+ " print(json.dumps({'accepted': True}))",+ ].join("\n"),+ scanDirectory,+ ),+ ).toMatchObject({+ accepted: false,+ error: expect.stringContaining("sticky bit"),+ });+ } finally {+ await chmod(root, 0o700);+ }+ },+ );+test("preserves native Windows case-insensitive path comparison", () => {expect(runPythonProbe(simulatedPathProbe, "windows")).toMatchObject({accepted: true,