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(findings): preserve structured findings API errors (#1081)

mldangelo-oai6a8231e41bb9
diff --git a/sdk/typescript/docs/findings-service.md b/sdk/typescript/docs/findings-service.md
index 69ff91096..e91784c6a 100644
--- a/sdk/typescript/docs/findings-service.md
+++ b/sdk/typescript/docs/findings-service.md
@@ -244,6 +244,10 @@ For `finding_not_indexed`, import the finding with the matching `repositoryId`
before retrying. Updating a document can invalidate its earlier embedding.
This error does not mean that the finding has no duplicates.
+SDK findings API failures preserve the service's error code and message alongside
+the HTTP status. Responses without a recognized JSON error retain the HTTP-status
+diagnostic. Retry decisions continue to use the HTTP status and `Retry-After`.
+
## Browse the dashboard
The dashboard has Findings and Duplicate groups views with search, repository
diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjs
index 00d3affc2..4cea0591d 100644
--- a/sdk/typescript/scripts/check-package.mjs
+++ b/sdk/typescript/scripts/check-package.mjs
@@ -219,6 +219,7 @@ const allowedFiles = new Set([
"finding-retrieval",
"finding-workflow",
"findings-client",
+ "findings-errors",
"finding-dedupe-groups",
"deduplication/deduplication-prompts",
"deduplication/deduplication-reviewer",
diff --git a/sdk/typescript/src/findings-client.ts b/sdk/typescript/src/findings-client.ts
index 4579d4f97..265ff928b 100644
--- a/sdk/typescript/src/findings-client.ts
+++ b/sdk/typescript/src/findings-client.ts
@@ -1,4 +1,8 @@
import { CodexSecurityError } from "./errors.js";
+import {
+ parseFindingsErrorResponse,
+ type FindingsErrorCode,
+} from "./findings-errors.js";
import { retryDelay, waitForRetry } from "./deduplication/retry.js";
import type { Finding } from "./models.js";
import type {
@@ -16,9 +20,27 @@ class FindingsHttpError extends CodexSecurityError {
message: string,
readonly status: number,
readonly retryAfter: string | null,
+ readonly code?: FindingsErrorCode,
) {
super(message);
}
+
+ static async fromResponse(
+ response: Response,
+ message: string,
+ signal?: AbortSignal,
+ ): Promise<FindingsHttpError> {
+ // Gateways can return plain text or HTML instead of the service's JSON error.
+ const body: unknown = await response.json().catch(() => undefined);
+ signal?.throwIfAborted();
+ const error = parseFindingsErrorResponse(body);
+ return new FindingsHttpError(
+ error?.message ? `${message} ${error.message}` : message,
+ response.status,
+ response.headers.get("Retry-After"),
+ error?.error,
+ );
+ }
}
function isRetryable(error: unknown): boolean {
@@ -52,15 +74,14 @@ export class FindingsClient {
return await this.retry(async () => {
const response = await this.request(url, { signal: this.signal });
if (!response.ok) {
- await response.body?.cancel().catch(() => undefined);
- throw new FindingsHttpError(
+ throw await FindingsHttpError.fromResponse(
+ response,
`Potential-duplicates lookup for ${findingId} failed (HTTP ${response.status}).${
response.status === 404
? " Import the finding with its repositoryId through POST /v1/bulk/findings before deduplicating."
: ""
}`,
- response.status,
- response.headers.get("Retry-After"),
+ this.signal,
);
}
return (await response.json()) as FindingNeighborhood;
@@ -128,11 +149,10 @@ export class FindingsClient {
signal: this.signal,
});
if (!response.ok) {
- await response.body?.cancel().catch(() => undefined);
- throw new FindingsHttpError(
+ throw await FindingsHttpError.fromResponse(
+ response,
`Findings API POST /${path} failed (HTTP ${response.status}).`,
- response.status,
- response.headers.get("Retry-After"),
+ this.signal,
);
}
return await response.json();
diff --git a/sdk/typescript/src/findings-errors.ts b/sdk/typescript/src/findings-errors.ts
new file mode 100644
index 000000000..b3f502110
--- /dev/null
+++ b/sdk/typescript/src/findings-errors.ts
@@ -0,0 +1,35 @@
+export const FINDINGS_ERROR_STATUS = {
+ invalid_request: 400,
+ finding_conflict: 409,
+ embedding_unavailable: 503,
+ embedding_failed: 502,
+ finding_not_indexed: 404,
+ not_found: 404,
+ internal_error: 500,
+} as const;
+
+export type FindingsErrorCode = keyof typeof FINDINGS_ERROR_STATUS;
+
+export interface FindingsErrorResponse {
+ error: FindingsErrorCode;
+ message?: string;
+}
+
+export function parseFindingsErrorResponse(
+ value: unknown,
+): FindingsErrorResponse | undefined {
+ if (
+ typeof value !== "object" ||
+ value === null ||
+ !("error" in value) ||
+ typeof value.error !== "string" ||
+ !Object.hasOwn(FINDINGS_ERROR_STATUS, value.error) ||
+ ("message" in value && typeof value.message !== "string")
+ ) {
+ return undefined;
+ }
+ return {
+ error: value.error as FindingsErrorCode,
+ ...("message" in value ? { message: value.message as string } : {}),
+ };
+}
diff --git a/sdk/typescript/src/server/errors.ts b/sdk/typescript/src/server/errors.ts
index d212f66d7..07da666d2 100644
--- a/sdk/typescript/src/server/errors.ts
+++ b/sdk/typescript/src/server/errors.ts
@@ -1,13 +1,22 @@
+import {
+ FINDINGS_ERROR_STATUS,
+ type FindingsErrorCode,
+ type FindingsErrorResponse,
+} from "../findings-errors.js";
+
export class FindingsError extends Error {
constructor(
- readonly code:
- | "invalid_request"
- | "finding_conflict"
- | "embedding_unavailable"
- | "embedding_failed"
- | "finding_not_indexed",
+ readonly code: FindingsErrorCode,
message: string,
) {
super(message);
}
+
+ get status(): number {
+ return FINDINGS_ERROR_STATUS[this.code];
+ }
+
+ toJSON(): FindingsErrorResponse {
+ return { error: this.code, message: this.message };
+ }
}
diff --git a/sdk/typescript/src/server/routes.ts b/sdk/typescript/src/server/routes.ts
index 468517c61..fd33f0ca3 100644
--- a/sdk/typescript/src/server/routes.ts
+++ b/sdk/typescript/src/server/routes.ts
@@ -1,5 +1,9 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import type { ValidateFunction } from "ajv";
+import {
+ FINDINGS_ERROR_STATUS,
+ type FindingsErrorResponse,
+} from "../findings-errors.js";
import { FindingsError } from "./errors.js";
import { dashboardQuery, serveDashboard } from "./dashboard.js";
import type { FindingEmbedder } from "./embeddings.js";
@@ -107,20 +111,17 @@ export async function handleFindingsRequest(
return;
}
request.resume();
- json(response, 404, { error: "not_found" });
+ json(response, FINDINGS_ERROR_STATUS.not_found, {
+ error: "not_found",
+ } satisfies FindingsErrorResponse);
} catch (error) {
if (error instanceof FindingsError) {
- const status = {
- invalid_request: 400,
- finding_conflict: 409,
- embedding_unavailable: 503,
- embedding_failed: 502,
- finding_not_indexed: 404,
- }[error.code];
- json(response, status, { error: error.code, message: error.message });
+ json(response, error.status, error.toJSON());
} else {
console.error(error);
- json(response, 500, { error: "internal_error" });
+ json(response, FINDINGS_ERROR_STATUS.internal_error, {
+ error: "internal_error",
+ } satisfies FindingsErrorResponse);
}
}
}
diff --git a/sdk/typescript/tests-ts/findings-client-retry.test.ts b/sdk/typescript/tests-ts/findings-client-retry.test.ts
index a86f74a90..beb71c1aa 100644
--- a/sdk/typescript/tests-ts/findings-client-retry.test.ts
+++ b/sdk/typescript/tests-ts/findings-client-retry.test.ts
@@ -9,6 +9,131 @@ const neighborhood = {
potentialDuplicates: [],
};
+test("lookup preserves the service error code and explanation", async () => {
+ const message = "No current embedding exists in the requested repository.";
+ const client = new FindingsClient(
+ "http://synthetic.test",
+ undefined,
+ async () =>
+ Response.json({ error: "finding_not_indexed", message }, { status: 404 }),
+ );
+ await expect(
+ client.potentialDuplicates("synthetic", scope),
+ ).rejects.toMatchObject({
+ code: "finding_not_indexed",
+ status: 404,
+ message: expect.stringContaining(message),
+ });
+});
+
+test("publishing preserves conflict details without retrying", async () => {
+ const message = "The finding belongs to another repository.";
+ let requests = 0;
+ const client = new FindingsClient(
+ "http://synthetic.test",
+ undefined,
+ async () => {
+ requests++;
+ return Response.json(
+ { error: "finding_conflict", message },
+ { status: 409 },
+ );
+ },
+ );
+ await expect(client.publish([], scope.repositoryId)).rejects.toMatchObject({
+ code: "finding_conflict",
+ status: 409,
+ message: expect.stringContaining(message),
+ });
+ expect(requests).toBe(1);
+});
+
+test("publishing preserves cancellation while reading an error response", async () => {
+ const controller = new AbortController();
+ const reason = new Error("Synthetic caller cancellation");
+ const request = mock(async (_url: URL, init: RequestInit) => {
+ expect(init.signal).toBe(controller.signal);
+ const response = new Response(null, { status: 409 });
+ response.json = async () => {
+ controller.abort(reason);
+ throw new DOMException("Synthetic aborted body read", "AbortError");
+ };
+ return response;
+ });
+ const client = new FindingsClient(
+ "http://synthetic.test",
+ controller.signal,
+ request,
+ );
+ await expect(client.publish([], scope.repositoryId)).rejects.toBe(reason);
+ expect(request).toHaveBeenCalledTimes(1);
+});
+
+test.each([
+ "<html>Gateway unavailable</html>",
+ '{"error":',
+ "null",
+ '{"error":"finding_conflict","message":123}',
+])(
+ "keeps the HTTP diagnostic for a non-contract response: %s",
+ async (body) => {
+ const client = new FindingsClient(
+ "http://synthetic.test",
+ undefined,
+ async () => new Response(body, { status: 409 }),
+ );
+ await expect(client.storeDedupeGroups([["a", "b"]])).rejects.toMatchObject({
+ status: 409,
+ code: undefined,
+ message: "Findings API POST /v1/dedupe-groups failed (HTTP 409).",
+ });
+ },
+);
+
+test("preserves an error code when the service omits a message", async () => {
+ const client = new FindingsClient(
+ "http://synthetic.test",
+ undefined,
+ async () => Response.json({ error: "not_found" }, { status: 404 }),
+ );
+ await expect(client.publish([], scope.repositoryId)).rejects.toMatchObject({
+ code: "not_found",
+ status: 404,
+ message: "Findings API POST /v1/bulk/findings failed (HTTP 404).",
+ });
+});
+
+test("structured errors preserve retries and Retry-After", async () => {
+ const delays: number[] = [];
+ let requests = 0;
+ const message = "Embedding credentials are unavailable.";
+ const client = new FindingsClient(
+ "http://synthetic.test",
+ undefined,
+ async () => {
+ requests++;
+ return Response.json(
+ { error: "embedding_unavailable", message },
+ { status: 503, headers: { "Retry-After": "12" } },
+ );
+ },
+ {
+ wait: async (delay) => {
+ delays.push(delay);
+ },
+ random: () => 0,
+ },
+ );
+ await expect(client.storeDedupeGroups([["a", "b"]])).rejects.toMatchObject({
+ code: "embedding_unavailable",
+ status: 503,
+ retryAfter: "12",
+ message: expect.stringContaining(message),
+ });
+ expect(requests).toBe(3);
+ expect(delays).toEqual([12000, 12000]);
+});
+
test("lookup retries rate limits and honors Retry-After before continuing", async () => {
let requests = 0;
const delays = mock(async (_delay: number) => {});