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(sdk): restore completed artifacts after follow-up cancellation (#1057)
mldangelo-oai83502fdff897
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 0282c60f8..e04cd0ff4 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -1207,6 +1207,7 @@ export class CodexSecurity {let deepProgressTracker: DeepScanProgressTracker | null = null;let releaseCredentialHome: (() => Promise<void>) | null = null;let scanFailure = false;+ let artifactRestorationFailure: OutputDirectoryError | null = null;let customValidationComplete = false;let completionCost: ScanCost | null = null;let budgetRecovery: {@@ -2195,7 +2196,6 @@ export class CodexSecurity {});checkOpen();} catch (error) {- if (signal.aborted || this.#closed) throw error;if (artifactRestorer !== null) {for (const artifact of completedArtifacts) {try {@@ -2204,14 +2204,15 @@ export class CodexSecurity {artifact.contents,);} catch (cause) {- if (signal.aborted || this.#closed) throw cause;- throw new OutputDirectoryError(+ artifactRestorationFailure = new OutputDirectoryError("Cannot restore an artifact outside the scan directory.",{ cause },);+ throw artifactRestorationFailure;}}}+ if (signal.aborted || this.#closed) throw error;await collectResult(result.turnResult,result.threadId,@@ -2282,6 +2283,7 @@ export class CodexSecurity {// scan, and cleanup must treat all of those as a failure it is not allowed to mask.scanFailure = true;const snapshot = await costTracker?.stop().catch(() => null);+ if (artifactRestorationFailure !== null) throw artifactRestorationFailure;let failure =signal.reason instanceof ScanCostLimitExceededError? signal.reasondiff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 505469bf5..7b19a682c 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -1832,7 +1832,6 @@ export async function prepareScanArtifactRestorer(],pluginHelperEnvironment(options.environment),contents,- options.signal,);if (!result.success) {throw new Error(@@ -1842,7 +1841,6 @@ export async function prepareScanArtifactRestorer();}} catch (error) {- if (options.signal?.aborted) throw error;throw new OutputDirectoryError("Could not safely restore a completed scan artifact.",{ cause: error },diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 322b8da26..59b672390 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -4606,6 +4606,83 @@ describe("CodexSecurity orchestration", () => {},);+ test.each(["cancel", "close", "restore failure"])(+ "preserves completed artifacts when a follow-up ends with %s",+ async (scenario) => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const codexHome = join(root, "codex-home");+ const scanDir = join(root, "scan");+ await Promise.all([mkdir(repository), mkdir(codexHome)]);+ const controller = new AbortController();+ await mkdir(scanDir, { mode: 0o700 });+ let originalFindings: string;+ let turns = 0;+ let closing: Promise<void> | undefined;+ const client = new TestClient(+ {},+ {+ prepareRuntime: async () => preparedRuntime(codexHome),+ resolvePluginPython: async () => "/managed/python",+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ prepareScanArtifactRestorer: async () => ({+ restore: async (name, contents) => {+ if (scenario === "restore failure")+ throw new Error("write failed");+ await writeFile(join(scanDir, name), contents);+ },+ }),+ createCodex: () => ({+ startThread: () => ({+ id: "thread-1",+ async runStreamed() {+ if (++turns === 1) {+ await copyCompletedScan(root);+ originalFindings = await readFile(+ join(scanDir, "findings.json"),+ "utf8",+ );+ } else {+ await writeFile(+ join(scanDir, "findings.json"),+ '{"unfinished":',+ );+ await writeFile(+ join(scanDir, "report.md"),+ "unfinished report",+ );+ if (scenario === "close") closing = client.close();+ else controller.abort();+ }+ return { events: completedEvents() };+ },+ }),+ }),+ },+ );+ const result = client.run(repository, {+ postScanPrompt: "Draft confirmed fixes.",+ signal: controller.signal,+ });+ if (scenario === "restore failure") {+ await expect(result).rejects.toBeInstanceOf(OutputDirectoryError);+ } else {+ await expect(result).rejects.toThrow(+ scenario === "close" ? "closed" : "interrupted",+ );+ expect(await readFile(join(scanDir, "findings.json"), "utf8")).toBe(+ originalFindings!,+ );+ expect(await readFile(join(scanDir, "report.md"), "utf8")).toBe(+ "# Scan report\n",+ );+ }+ expect(turns).toBe(2);+ await (closing ?? client.close());+ },+ );+test("raises a live budget twice without restarting or resetting accumulated usage", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex e1f310dd9..fc08454c3 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -2219,15 +2219,18 @@ describe("plugin runtime preparation", () => {});await writeFile(join(scanDir, artifact), expected);const python = await resolvePluginPython({ environment });+ const restorationSignal = new AbortController();const restorer = await prepareScanArtifactRestorer({python,pluginRoot: upgraded.installedRoot,environment,+ signal: restorationSignal.signal,},scanDir,);await writeFile(join(scanDir, artifact), Buffer.from([9, 0, 8]));+ restorationSignal.abort();await restorer.restore(artifact, expected);expect(await readFile(join(scanDir, artifact))).toEqual(expected);