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(scan): keep state and output paths disjoint (#418)

mldangelo-oai0bef7e20af32
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index 5c4d7606b..157334b7e 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -262,6 +262,7 @@ export interface ScanPreflight extends DeepScanOptions {
interface LocalScanInputs
extends Omit<ScanPreflight, "model" | "reasoningEffort" | "authentication"> {
protectedRoot: string;
+ stateDirectory: string;
}
export interface CodexSecurityMetadata {
@@ -450,11 +451,8 @@ export class CodexSecurity {
mode,
outputDir: requestedOutput,
protectedRoot,
+ stateDirectory,
} = await this.#validateLocalInputs(repository, options, signal);
- const stateDirectory = codexSecurityStateDirectory(
- this.#dependencies.environment,
- );
- requireOutputOutsideRepository(protectedRoot, stateDirectory);
checkOpen();
let temporaryRoot: string | undefined;
if (
@@ -469,9 +467,6 @@ export class CodexSecurity {
"temporary",
);
}
- if (requestedOutput !== null) {
- requireOutputOutsideRepository(protectedRoot, requestedOutput);
- }
if (options.knowledgeBasePaths?.length) {
knowledgeBase = await prepareKnowledgeBase(
options.knowledgeBasePaths,
@@ -633,7 +628,11 @@ export class CodexSecurity {
? await preparePersistentScanRoot(stateDirectory, basename(repo))
: temporaryRoot;
if (scanOutputRoot !== undefined) {
- requireOutputOutsideRepository(protectedRoot, scanOutputRoot);
+ requireOutputOutsideRepository(
+ protectedRoot,
+ scanOutputRoot,
+ scanOutputRoot === temporaryRoot ? "temporary" : "output",
+ );
}
scanDir = await (this.#dependencies.prepareOutputDir ?? prepareOutputDir)(
requestedOutput ?? undefined,
@@ -1746,12 +1745,32 @@ export class CodexSecurity {
if (requestedOutput !== null) {
requireOutputOutsideRepository(protectedRoot, requestedOutput);
}
+ const stateDirectory = codexSecurityStateDirectory(
+ this.#dependencies.environment,
+ );
+ let canonicalStateDirectory = stateDirectory;
+ while (true) {
+ try {
+ canonicalStateDirectory = join(
+ await realpath(canonicalStateDirectory),
+ relative(canonicalStateDirectory, stateDirectory),
+ );
+ break;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ const parent = dirname(canonicalStateDirectory);
+ if (parent === canonicalStateDirectory) throw error;
+ canonicalStateDirectory = parent;
+ }
+ }
+ requireOutputOutsideRepository(protectedRoot, canonicalStateDirectory);
return {
repository: repo,
target: normalized,
mode,
outputDir: requestedOutput,
protectedRoot,
+ stateDirectory,
};
}
@@ -2905,11 +2924,16 @@ function requireOutputOutsideRepository(
pathKind: ProtectedScanPathKind = "output",
): void {
const outputRelative = relative(repository, outputDirectory);
+ const repositoryRelative = relative(outputDirectory, repository);
if (
outputRelative === "" ||
(outputRelative !== ".." &&
!outputRelative.startsWith(`..${sep}`) &&
- !isAbsolute(outputRelative))
+ !isAbsolute(outputRelative)) ||
+ (pathKind === "output" &&
+ repositoryRelative !== ".." &&
+ !repositoryRelative.startsWith(`..${sep}`) &&
+ !isAbsolute(repositoryRelative))
) {
throw new OutputInsideProtectedRootError(
outputDirectory,
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index 7dfa8e875..a73840930 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -1272,9 +1272,18 @@ export async function preparePersistentScanRoot(
stateDirectory: string,
repositoryName: string,
): Promise<string> {
- const root = join(stateDirectory, "scans", safePrefix(repositoryName));
- await mkdir(root, { recursive: true, mode: 0o700 });
- return await realpath(root);
+ await mkdir(stateDirectory, { recursive: true, mode: 0o700 });
+ let root = await realpath(stateDirectory);
+ for (const directory of ["scans", safePrefix(repositoryName)]) {
+ root = join(root, directory);
+ await mkdir(root, { recursive: true, mode: 0o700 });
+ if (!(await lstat(root)).isDirectory()) {
+ throw new OutputDirectoryError(
+ `Persistent scan output must use real directories: ${root}`,
+ );
+ }
+ }
+ return root;
}
export async function runWorkbench(
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index c6feff274..049680b98 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -1464,10 +1464,11 @@ describe("CodexSecurity orchestration", () => {
await client.close();
});
- test("rejects scan output inside the repository before runtime initialization", async () => {
+ test("rejects overlapping scan output before runtime initialization", async () => {
const root = await temporaryDirectory();
const repository = join(root, "repository");
await mkdir(repository);
+ await writeFile(join(repository, "preserved.txt"), "preserved\n");
let runtimeStarted = false;
const client = new TestClient(
{},
@@ -1483,6 +1484,22 @@ describe("CodexSecurity orchestration", () => {
await expect(
client.run(repository, { outputDir: join(repository, "scan") }),
).rejects.toBeInstanceOf(OutputDirectoryError);
+ for (const operation of ["preflight", "run"] as const) {
+ await expect(
+ client[operation](repository, {
+ outputDir: root,
+ archiveExisting: true,
+ }),
+ ).rejects.toMatchObject({
+ name: OutputInsideProtectedRootError.name,
+ outputDirectory: root,
+ protectedRoot: repository,
+ pathKind: "output",
+ });
+ expect(await readFile(join(repository, "preserved.txt"), "utf8")).toBe(
+ "preserved\n",
+ );
+ }
if (process.platform !== "win32") {
const linkedRepository = join(root, "linked-repository");
await symlink(repository, linkedRepository);
@@ -3902,30 +3919,45 @@ describe("CodexSecurity orchestration", () => {
expect(existsSync(join(result.scanDir, "scan-manifest.json"))).toBe(true);
});
- test("rejects repository-local state even when scan output is outside", async () => {
+ test("rejects state directories overlapping the selected repository", async () => {
const root = await temporaryDirectory();
const repository = join(root, "repository");
- const stateDirectory = join(repository, "state");
+ const linkedState = join(root, "linked-state");
await mkdir(repository);
- const client = new TestClient(
- {},
- {
- environment: { CODEX_SECURITY_STATE_DIR: stateDirectory },
- prepareRuntime: async () => {
- throw new Error("Runtime must not start");
- },
- resolvePluginPython: async () => "/managed/python",
- createCodex: () => {
- throw new Error("Codex must not start");
+ await symlink(
+ root,
+ linkedState,
+ process.platform === "win32" ? "junction" : "dir",
+ );
+ for (const stateDirectory of [
+ join(repository, "state"),
+ root,
+ linkedState,
+ join(linkedState, "repository", "missing", "state"),
+ ]) {
+ const client = new TestClient(
+ {},
+ {
+ environment: { CODEX_SECURITY_STATE_DIR: stateDirectory },
+ prepareRuntime: async () => {
+ throw new Error("Runtime must not start");
+ },
+ resolvePluginPython: async () => "/managed/python",
+ createCodex: () => {
+ throw new Error("Codex must not start");
+ },
},
- },
- );
+ );
- await expect(
- client.run(repository, { outputDir: join(root, "output") }),
- ).rejects.toBeInstanceOf(OutputInsideProtectedRootError);
- expect(existsSync(stateDirectory)).toBe(false);
- await client.close();
+ for (const operation of ["preflight", "run"] as const) {
+ await expect(
+ client[operation](repository, { outputDir: join(root, "output") }),
+ ).rejects.toBeInstanceOf(OutputInsideProtectedRootError);
+ }
+ if (stateDirectory !== root && stateDirectory !== linkedState)
+ expect(existsSync(stateDirectory)).toBe(false);
+ await client.close();
+ }
});
test("rejects reruns when the original plugin version is unavailable", async () => {
@@ -5926,7 +5958,7 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
{},
{
environment: {
- CODEX_SECURITY_STATE_DIR: root,
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
OPENAI_API_KEY: "ambient-key",
},
prepareRuntime: async () => ({
@@ -6107,7 +6139,7 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
{},
{
environment: {
- CODEX_SECURITY_STATE_DIR: root,
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
OPENAI_API_KEY: "ambient-key",
},
prepareRuntime: async () => ({
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index 3bb9daa31..65006ff9f 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -3466,6 +3466,41 @@ describe("runtime directories and plugin Python boundary", () => {
if (process.platform !== "win32") {
expect((await stat(scanRoot)).mode & 0o777).toBe(0o700);
}
+
+ const linkedState = join(root, "linked-state");
+ await symlink(
+ join(root, "state"),
+ linkedState,
+ process.platform === "win32" ? "junction" : "dir",
+ );
+ expect(
+ await preparePersistentScanRoot(linkedState, "linked repository"),
+ ).toBe(join(root, "state", "scans", "linked-repository"));
+ });
+
+ test("rejects symbolic children beneath persistent scan state", async () => {
+ const root = await temporaryDirectory();
+ const external = join(root, "external");
+ await mkdir(external);
+
+ for (const [name, path] of [
+ ["scans", "scans"],
+ ["repository", join("scans", "repository")],
+ ] as const) {
+ const state = join(root, `state-${name}`);
+ const linked = join(state, path);
+ await mkdir(dirname(linked), { recursive: true });
+ await symlink(
+ external,
+ linked,
+ process.platform === "win32" ? "junction" : "dir",
+ );
+
+ await expect(
+ preparePersistentScanRoot(state, "repository"),
+ ).rejects.toThrow("Persistent scan output must use real directories");
+ expect(await readdir(external)).toEqual([]);
+ }
});
test("expands a tilde CODEX_HOME when discovering preflight configuration", async () => {