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

6.8 KB
Raw Blame
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 {
  FindingNeighborhood,
  FindingSearchScope,
} from "./finding-retrieval.js";

export type FindingsRequest = (
  url: URL,
  init: RequestInit,
) => Promise<Response>;

class FindingsHttpError extends CodexSecurityError {
  constructor(
    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> {
    // Service errors are JSON; other gateway bodies need not finish to report HTTP failure.
    const mediaType = response.headers
      .get("Content-Type")
      ?.split(";", 1)[0]
      ?.trim()
      .toLowerCase();
    let body: unknown;
    if (mediaType === "application/json" || mediaType?.endsWith("+json")) {
      body = await response.json().catch(() => undefined);
    } else {
      void response.body?.cancel().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 {
  if (error instanceof FindingsHttpError)
    return [408, 429, 500, 502, 503, 504].includes(error.status);
  // Fetch rejects network failures with TypeError; JSON truncation can produce SyntaxError.
  return error instanceof TypeError || error instanceof SyntaxError;
}

export function findingsBaseUrl(value: string): URL {
  const url = new URL(value);
  if (!url.pathname.endsWith("/")) url.pathname += "/";
  url.search = "";
  url.hash = "";
  return url;
}

export class FindingsClient {
  private readonly url: URL;
  constructor(
    url: string,
    private readonly signal?: AbortSignal,
    private readonly request: FindingsRequest = fetch,
    private readonly retries: {
      wait?: typeof waitForRetry;
      random?: () => number;
    } = {},
  ) {
    this.url = findingsBaseUrl(url);
  }

  async potentialDuplicates(
    findingId: string,
    scope: FindingSearchScope,
  ): Promise<FindingNeighborhood> {
    const url = this.endpoint(
      `v1/finding/${encodeURIComponent(findingId)}/potential-duplicates`,
    );
    if (scope.allRepositories === true)
      url.searchParams.set("allRepositories", "true");
    else url.searchParams.set("repositoryId", scope.repositoryId);
    return await this.retry(async () => {
      const response = await this.requestEndpoint(url);
      if (!response.ok) {
        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."
              : ""
          }`,
          this.signal,
        );
      }
      return (await response.json()) as FindingNeighborhood;
    });
  }

  async publish(
    findings: readonly Finding[],
    repositoryId: string,
  ): Promise<string[]> {
    const receipt = await this.post("v1/bulk/findings", {
      findings,
      repositoryId,
    });
    const expected = new Set(findings.map((finding) => finding.findingId));
    if (
      !Array.isArray(receipt) ||
      receipt.length !== findings.length ||
      new Set(receipt).size !== expected.size ||
      receipt.some((id) => !expected.has(id))
    ) {
      throw new CodexSecurityError(
        "The findings API did not acknowledge all published finding IDs. Check the service before retrying.",
      );
    }
    return receipt as string[];
  }

  async storeDedupeGroups(groups: readonly string[][]): Promise<void> {
    if (groups.length === 0) return;
    await this.retry(() => this.post("v1/dedupe-groups", { groups }));
  }

  private async retry<T>(operation: () => Promise<T>): Promise<T> {
    for (let attempt = 1; ; attempt++) {
      this.signal?.throwIfAborted();
      try {
        return await operation();
      } catch (error) {
        this.signal?.throwIfAborted();
        if (attempt === 3 || !isRetryable(error)) throw error;
        let delay = retryDelay(attempt, this.retries.random);
        if (error instanceof FindingsHttpError && error.retryAfter !== null) {
          const seconds = Number(error.retryAfter);
          const serverDelay = Number.isFinite(seconds)
            ? seconds * 1000
            : Date.parse(error.retryAfter) - Date.now();
          if (Number.isFinite(serverDelay))
            delay = Math.max(delay, serverDelay);
        }
        await (this.retries.wait ?? waitForRetry)(delay, this.signal);
      }
    }
  }

  private endpoint(path: string): URL {
    return new URL(path, this.url);
  }

  private async requestEndpoint(
    url: URL,
    post?: RequestInit,
  ): Promise<Response> {
    for (let redirects = 0; ; redirects++) {
      const response = await this.request(url, {
        ...post,
        signal: this.signal,
        redirect: "manual",
      });
      const location = response.headers.get("Location");
      if (
        location === null ||
        ![301, 302, 303, 307, 308].includes(response.status)
      )
        return response;
      void response.body?.cancel().catch(() => undefined);
      this.signal?.throwIfAborted();
      // Fetch exposes header bytes as a Latin-1 string; URL paths use UTF-8.
      const next = new URL(
        Buffer.from(location, "latin1").toString("utf8"),
        url,
      );
      if (next.protocol !== this.url.protocol || next.host !== this.url.host)
        throw new FindingsHttpError(
          `Findings API redirect leaves the configured service origin (HTTP ${response.status}). Configure the final service URL.`,
          response.status,
          null,
        );

      // Retain Fetch's redirect limit and POST-to-GET behavior.
      if (redirects === 20)
        throw new TypeError("Too many findings service redirects.");
      if ([301, 302, 303].includes(response.status)) post = undefined;
      url = next;
    }
  }

  private async post(path: string, body: unknown): Promise<unknown> {
    const response = await this.requestEndpoint(this.endpoint(path), {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
    if (!response.ok) {
      throw await FindingsHttpError.fromResponse(
        response,
        `Findings API POST /${path} failed (HTTP ${response.status}).`,
        this.signal,
      );
    }
    return await response.json();
  }
}