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

30.0 KB
Raw Blame
import { setFindingIdentity, sha256 } from "./support/finding-identity.js";
import { VERSION } from "../src/version.js";
import type { FindingsDocument, ScanManifest } from "../src/models.js";
import { responding } from "./support/responses.js";
import { once } from "node:events";
import { rejecting } from "./support/errors.js";
import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import * as fs from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, test, mock, spyOn } from "bun:test";
import {
  publishFindingsCsvToCloud,
  publishScanToCloud,
} from "../src/cloud-publish.js";
import {
  codexSecurityCredentialHome,
  setCodexSecurityCredentialLogout,
  writeCredentialHomeConfig,
} from "../src/runtime.js";
import { copyCompletedScanFixture } from "./plugin-root.js";
import { createApiTestFixtures } from "./support/temporary-directories.js";

const { temporaryDirectory, cleanup } = createApiTestFixtures(
  "codex-security-cloud-csv-",
  false,
);
const login = {
  auth_mode: "chatgpt",
  tokens: {
    access_token: "synthetic-access-token",
    account_id: "synthetic-account",
    refresh_token: "synthetic-refresh-token",
    id_token: "synthetic-id-token",
  },
};
const receipt = {
  status: "accepted",
  finding_ids: ["finding-1"],
  finding_count: 1,
};
const csvHeader = [
  "occurrence_id",
  "finding_id",
  "title",
  "summary",
  "severity",
  "confidence",
  "status",
  "close_reason",
  "note",
  "remediation",
  "path",
  "start_line",
  "end_line",
].join(",");
const csvRow = [
  "occ_e79cb19591e696572a1c22be",
  "csf_852f90d6e1177502ff113d4a",
  '"Unsafe archive extraction, including nested entries"',
  "An attacker-controlled path reaches a filesystem write.",
  "high",
  "high",
  "open",
  "",
  "",
  "Normalize and validate destinations.",
  "src/extract.py",
  "41",
  "44",
].join(",");

async function csvFixture(contents = `${csvHeader}\n${csvRow}\n`) {
  const root = await temporaryDirectory();
  const path = join(root, "findings.csv");
  await writeFile(path, contents);
  return path;
}

afterEach(cleanup);

async function fixture(homeName = "home") {
  const root = await temporaryDirectory("codex-security-cloud-");
  const scan = join(root, "scan");
  const home = join(root, homeName);
  await copyCompletedScanFixture(scan);
  if (process.platform !== "win32") await chmod(scan, 0o700);
  await mkdir(home, { mode: 0o700 });
  await writeFile(join(home, "auth.json"), JSON.stringify(login), {
    mode: 0o600,
  });
  await writeFile(
    join(home, "config.toml"),
    'cli_auth_credentials_store = "file"\n',
  );
  return {
    scan,
    home,
    environment: {
      CODEX_HOME: home,
      CODEX_SECURITY_STATE_DIR: join(root, "state"),
    },
  };
}

async function addSecondFinding(scan: string): Promise<void> {
  const findingsPath = join(scan, "findings.json");
  const manifestPath = join(scan, "scan-manifest.json");
  const findings = JSON.parse(
    await readFile(findingsPath, "utf8"),
  ) as FindingsDocument;
  const manifest = JSON.parse(
    await readFile(manifestPath, "utf8"),
  ) as ScanManifest;
  const second = structuredClone(findings.findings[0]!);
  second.identity.instance = "second-instance";
  second.title = "A second synthetic finding";
  setFindingIdentity(manifest.scan, second);
  findings.findings.push(second);
  await writeFile(findingsPath, `${JSON.stringify(findings, null, 2)}\n`);
  const artifact = manifest.scan.artifacts.find(
    ({ path }) => path === "findings.json",
  )!;
  artifact.sha256 = sha256(await readFile(findingsPath));
  await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
}

describe("Cloud publication", () => {
  test("rejects invalid CSV UTF-8 before credentials or upload", async () => {
    const path = await csvFixture();
    const { environment } = await fixture();
    const [prefix, suffix] = `${csvHeader}\n${csvRow}\n`.split(
      "including nested entries",
    );
    const fetchMock = mock(rejecting("unexpected request"));
    const reading = spyOn(fs, "readFile");
    try {
      for (const bytes of [Buffer.from([0xff]), Buffer.from([0xe2, 0x82])]) {
        let decodeError: Error | undefined;
        try {
          new TextDecoder("utf-8", { fatal: true }).decode(bytes);
        } catch (error) {
          decodeError = error as Error;
        }
        expect(decodeError).toBeInstanceOf(TypeError);
        await writeFile(
          path,
          Buffer.concat([Buffer.from(prefix!), bytes, Buffer.from(suffix!)]),
        );
        await expect(
          publishFindingsCsvToCloud(path, { environment, fetch: fetchMock }),
        ).rejects.toMatchObject({
          name: "CodexSecurityError",
          message: `Could not read findings CSV. ${decodeError!.message}`,
          cause: expect.objectContaining({ message: decodeError!.message }),
        });
      }
      expect(reading.mock.calls.map(([file]) => file)).toEqual([path, path]);
      expect(fetchMock).not.toHaveBeenCalled();
    } finally {
      reading.mockRestore();
    }
  });

  test("preserves the filesystem cause when the selected CSV is missing", async () => {
    const path = join(await temporaryDirectory(), "missing.csv");
    const fetchMock = mock(rejecting("unexpected request"));
    await expect(
      publishFindingsCsvToCloud(path, { dryRun: true, fetch: fetchMock }),
    ).rejects.toMatchObject({
      name: "CodexSecurityError",
      message: expect.stringContaining("ENOENT"),
      cause: expect.objectContaining({ code: "ENOENT" }),
    });
    expect(fetchMock).not.toHaveBeenCalled();
  });

  test("preserves valid Unicode and BOM-bearing CSV source identities", async () => {
    const path = await csvFixture();
    const fetchMock = mock(rejecting("unexpected request"));
    for (const marker of ["�", "😀"]) {
      for (const bom of ["", "\uFEFF"]) {
        const source = `${bom}${csvHeader}\n${csvRow.replace("including nested entries", marker)}\n`;
        await writeFile(path, source);
        const result = await publishFindingsCsvToCloud(path, {
          dryRun: true,
          fetch: fetchMock,
        });
        expect(result.findings?.[0]?.title).toBe(
          `Unsafe archive extraction, ${marker}`,
        );
        expect(result.scanId).toBe(
          `scan_csv_${sha256(
            ["codex-security-csv-import/v1", VERSION, source].join("\0"),
          ).slice(0, 24)}`,
        );
      }
    }
    expect(fetchMock).not.toHaveBeenCalled();
  });

  test("previews a validated findings export CSV without credentials or network access", async () => {
    const path = await csvFixture();
    const fetchMock = mock(rejecting("unexpected request"));
    const result = await publishFindingsCsvToCloud(path, {
      dryRun: true,
      fetch: fetchMock,
    });
    expect(result).toMatchObject({
      scanId: expect.stringMatching(/^scan_csv_[a-f0-9]{24}$/),
      findingIds: [],
      findingCount: 1,
      dryRun: true,
      findings: [
        {
          findingId: expect.stringMatching(/^csf_[a-f0-9]{24}$/),
          occurrenceId: expect.stringMatching(/^occ_[a-f0-9]{24}$/),
          title: "Unsafe archive extraction, including nested entries",
          severity: { level: "high" },
          confidence: { level: "high" },
          locations: [{ path: "src/extract.py", startLine: 41, endLine: 44 }],
          validation: {
            method: "Source-reported CSV import metadata",
            status: "open",
            summary:
              "Source finding ID: csf_852f90d6e1177502ff113d4a\nSource occurrence ID: occ_e79cb19591e696572a1c22be\nSource status: open",
          },
          provenance: { source: "csv_import" },
        },
      ],
    });
    expect(fetchMock).toHaveBeenCalledTimes(0);
  });

  test("publishes separate CSV occurrences with distinct canonical identities", async () => {
    const secondOccurrence = "occ_000000000000000000000002";
    const secondRow = csvRow.replace(
      "occ_e79cb19591e696572a1c22be",
      secondOccurrence,
    );
    const path = await csvFixture(`${csvHeader}\n${csvRow}\n${secondRow}\n`);
    const { environment } = await fixture();
    const preview = await publishFindingsCsvToCloud(path, { dryRun: true });
    const findings = preview.findings!;
    expect(new Set(findings.map((finding) => finding.findingId)).size).toBe(2);
    expect(new Set(findings.map((finding) => finding.occurrenceId)).size).toBe(
      2,
    );
    expect(findings.map((finding) => finding.identity.anchor)).toEqual([
      "occ_e79cb19591e696572a1c22be",
      secondOccurrence,
    ]);
    for (const finding of findings) {
      expect(finding.findingId).toBe(
        `csf_${sha256(finding.fingerprints.primary).slice(0, 24)}`,
      );
      expect(finding.occurrenceId).toBe(
        `occ_${sha256([preview.scanId, finding.fingerprints.primary].join("\0")).slice(0, 24)}`,
      );
    }
    const result = await publishFindingsCsvToCloud(path, {
      environment,
      fetch: async (_url, options) => {
        const payload = JSON.parse(String(options.body));
        expect(payload.findings).toEqual(findings);
        return Response.json(
          {
            status: "accepted",
            finding_ids: ["first", "second"],
            finding_count: 2,
          },
          { status: 201 },
        );
      },
    });
    expect(result.findingCount).toBe(2);
  });

  test("posts CSV findings with generated scan provenance", async () => {
    const path = await csvFixture();
    const { environment } = await fixture();
    let payload: Record<string, unknown> | undefined;
    const result = await publishFindingsCsvToCloud(path, {
      environment,
      fetch: async (_url, options) => {
        payload = JSON.parse(String(options.body));
        return Response.json(receipt, { status: 201 });
      },
    });
    expect(result).toEqual({
      scanId: result.scanId,
      findingIds: ["finding-1"],
      findingCount: 1,
    });
    expect(result.scanId).toMatch(/^scan_csv_[a-f0-9]{24}$/);
    expect(payload).toMatchObject({
      schemaVersion: "1.0",
      scan: {
        id: result.scanId,
        producer: { name: "codex-security-cli" },
        status: "completed",
        startedAt: "1970-01-01T00:00:00.000Z",
        target: {
          kind: "directory_snapshot",
          displayName: "findings.csv",
        },
      },
      findings: [
        {
          remediation: "Normalize and validate destinations.",
          provenance: { source: "csv_import" },
        },
      ],
    });
    const [finding] = payload!["findings"] as Array<{
      findingId: string;
      occurrenceId: string;
    }>;
    expect(finding!.findingId).toMatch(/^csf_[a-f0-9]{24}$/);
    expect(finding!.occurrenceId).toMatch(/^occ_[a-f0-9]{24}$/);
  });

  test("accepts the candidate_id column from a Deep scan export", async () => {
    const path = await csvFixture(
      `${csvHeader.replace("finding_id,", "finding_id,candidate_id,")}\n${csvRow.replace("csf_852f90d6e1177502ff113d4a,", "csf_852f90d6e1177502ff113d4a,candidate-001,")}\n`,
    );
    const result = await publishFindingsCsvToCloud(path, { dryRun: true });
    expect(result.findings?.[0]?.extensions).toMatchObject({
      candidateId: "candidate-001",
    });
  });

  test("preserves source IDs and triage fields in finding validation", async () => {
    const path = await csvFixture(
      `${csvHeader}\n${csvRow.replace(",open,,,", ',closed,wont_fix,"Accepted risk.",')}\n`,
    );
    const result = await publishFindingsCsvToCloud(path, { dryRun: true });
    expect(result.findings?.[0]?.validation).toEqual({
      method: "Source-reported CSV import metadata",
      status: "closed",
      summary:
        "Source finding ID: csf_852f90d6e1177502ff113d4a\nSource occurrence ID: occ_e79cb19591e696572a1c22be\nSource status: closed\nSource close reason: wont_fix\nSource note: Accepted risk.",
    });
    expect(result.findings?.[0]?.provenance).toEqual({
      source: "csv_import",
    });
  });

  test("decodes exported CSV cells without stripping literal apostrophes", async () => {
    const path = await csvFixture(
      `${csvHeader}\n${csvRow
        .replace(
          '"Unsafe archive extraction, including nested entries"',
          '"\'\tTabbed title"',
        )
        .replace(
          "An attacker-controlled path reaches a filesystem write.",
          "'Literal apostrophe.",
        )
        .replace(
          "Normalize and validate destinations.",
          "'  @owner should remediate.",
        )
        .replace("src/extract.py", "'-generated/extract.py")}\n`,
    );
    const result = await publishFindingsCsvToCloud(path, { dryRun: true });
    expect(result.findings?.[0]).toMatchObject({
      title: "\tTabbed title",
      summary: "'Literal apostrophe.",
      remediation: "  @owner should remediate.",
      locations: [{ path: "-generated/extract.py" }],
    });
  });

  test.each([
    ["missing required header", csvHeader.replace("summary,", "")],
    ["unknown header", `${csvHeader},unknown`],
    ["no findings", csvHeader],
    ["wrong column count", `${csvHeader}\n${csvRow},extra`],
    [
      "invalid finding ID",
      `${csvHeader}\n${csvRow.replace("csf_852f90d6e1177502ff113d4a", "finding-1")}`,
    ],
    [
      "empty title",
      `${csvHeader}\n${csvRow.replace('"Unsafe archive extraction, including nested entries"', '""')}`,
    ],
    [
      "invalid severity",
      `${csvHeader}\n${csvRow.replace(",high,high,", ",urgent,high,")}`,
    ],
    [
      "invalid close reason",
      `${csvHeader}\n${csvRow.replace(",open,,,", ",closed,deferred,,")}`,
    ],
    [
      "missing required close note",
      `${csvHeader}\n${csvRow.replace(",open,,,", ",closed,false_positive,,")}`,
    ],
    [
      "unsafe path",
      `${csvHeader}\n${csvRow.replace("src/extract.py", "../escape.py")}`,
    ],
    [
      "invalid line range",
      `${csvHeader}\n${csvRow.replace(",41,44", ",45,44")}`,
    ],
    ["duplicate finding", `${csvHeader}\n${csvRow}\n${csvRow}`],
  ])("rejects a CSV with %s before authentication", async (_name, source) => {
    const path = await csvFixture(`${source}\n`);
    const fetchMock = mock(rejecting("unexpected request"));
    await expect(
      publishFindingsCsvToCloud(path, {
        environment: {},
        fetch: fetchMock,
      }),
    ).rejects.toThrow(/Findings CSV/);
    expect(fetchMock).toHaveBeenCalledTimes(0);
  });

  test.each([false, true])(
    "rejects artifacts from another scan before upload or preview (dryRun=%j)",
    async (dryRun) => {
      const { scan, environment } = await fixture();
      const fetchMock = mock(rejecting("unexpected request"));
      await expect(
        publishScanToCloud(scan, {
          environment,
          dryRun,
          expectedScanId: "another-scan",
          fetch: fetchMock,
        }),
      ).rejects.toThrow(
        "Scan artifacts do not match selected scan another-scan.",
      );
      expect(fetchMock).toHaveBeenCalledTimes(0);
    },
  );

  test("previews validated findings without credentials or network access", async () => {
    const { scan, home, environment } = await fixture();
    await rm(join(home, "auth.json"));
    const manifest = JSON.parse(
      await readFile(join(scan, "scan-manifest.json"), "utf8"),
    );
    const findings = JSON.parse(
      await readFile(join(scan, "findings.json"), "utf8"),
    );
    const fetchMock = mock(rejecting("unexpected request"));
    expect(
      await publishScanToCloud(scan, {
        environment,
        dryRun: true,
        expectedScanId: manifest.scan.id,
        fetch: fetchMock,
      }),
    ).toEqual({
      scanId: manifest.scan.id,
      findingIds: [],
      findingCount: findings.findings.length,
      dryRun: true,
      findings: findings.findings,
    });
    expect(fetchMock).toHaveBeenCalledTimes(0);
    await writeFile(join(scan, "findings.json"), "{}");
    await expect(
      publishScanToCloud(scan, { environment, dryRun: true }),
    ).rejects.toThrow();
  });

  test("posts validated findings and scan provenance with only ChatGPT access credentials", async () => {
    const { scan, home, environment } = await fixture(
      process.platform === "win32" ? "home" : " home ",
    );
    if (home !== home.trim()) {
      await mkdir(home.trim(), { mode: 0o700 });
      await writeFile(
        join(home.trim(), "config.toml"),
        'cli_auth_credentials_store = "file"\n',
      );
      await writeFile(
        join(home.trim(), "auth.json"),
        JSON.stringify({
          ...login,
          tokens: { ...login.tokens, access_token: "wrong-trimmed-home-token" },
        }),
        { mode: 0o600 },
      );
    }
    const manifest = JSON.parse(
      await readFile(join(scan, "scan-manifest.json"), "utf8"),
    );
    const findings = JSON.parse(
      await readFile(join(scan, "findings.json"), "utf8"),
    );
    const fetchMock = mock(async (url: string, options: RequestInit) => {
      expect(new URL(String(url)).origin).toBe("https://chatgpt.com");
      expect(options).toMatchObject({
        method: "POST",
        redirect: "error",
        headers: {
          Authorization: "Bearer synthetic-access-token",
          "ChatGPT-Account-ID": "synthetic-account",
          "Content-Type": "application/json",
          Accept: "application/json",
        },
      });
      expect(JSON.parse(String(options!.body))).toEqual({
        schemaVersion: "1.0",
        scan: manifest.scan,
        findings: findings.findings,
      });
      expect(JSON.stringify(options)).not.toContain("synthetic-refresh-token");
      expect(JSON.stringify(options)).not.toContain("synthetic-id-token");
      expect(options!.signal).toBeInstanceOf(AbortSignal);
      return Response.json(receipt, { status: 201 });
    });
    const result = await publishScanToCloud(scan, {
      environment: { ...environment, OPENAI_API_KEY: "synthetic-api-key" },
      fetch: fetchMock,
    });
    expect(result).toEqual({
      scanId: manifest.scan.id,
      findingIds: ["finding-1"],
      findingCount: 1,
    });
    expect(fetchMock).toHaveBeenCalledTimes(1);
  });

  test("accepts opaque Cloud finding IDs that differ from local finding IDs", async () => {
    const { scan, environment } = await fixture();
    const localFindings = JSON.parse(
      await readFile(join(scan, "findings.json"), "utf8"),
    ) as { findings: Array<{ findingId: string }> };
    const opaqueId = "cloud-observation-synthetic";
    expect(
      localFindings.findings.map(({ findingId }) => findingId),
    ).not.toContain(opaqueId);
    expect(
      await publishScanToCloud(scan, {
        environment,
        fetch: async () =>
          Response.json({
            status: "accepted",
            finding_ids: [opaqueId],
            finding_count: 1,
          }),
      }),
    ).toEqual({
      scanId: "scan_example_001",
      findingIds: [opaqueId],
      findingCount: 1,
    });
  });

  test("uses the shared Cloud API base while preserving the publication URL override", async () => {
    const { scan, environment } = await fixture();
    const cloudBase = "https://cloud.example.test/pilot/backend-api/aardvark";
    const urls: string[] = [];
    const fetch = async (url: string | URL | Request) => {
      urls.push(String(url));
      return Response.json(receipt);
    };
    const publishUrl = "https://other-cloud.example.test/publish";
    for (const settings of [
      { CODEX_SECURITY_CLOUD_BASE_URL: `${cloudBase}/` },
      { CODEX_SECURITY_CLOUD_PUBLISH_URL: publishUrl },
      {
        CODEX_SECURITY_CLOUD_BASE_URL: cloudBase,
        CODEX_SECURITY_CLOUD_PUBLISH_URL: publishUrl,
      },
    ]) {
      await publishScanToCloud(scan, {
        environment: { ...environment, ...settings },
        fetch,
      });
    }
    expect(urls).toEqual([`${cloudBase}/cli/findings`, publishUrl, publishUrl]);
  });

  test("rejects a remote HTTP Cloud base before reading credentials or sending a scan", async () => {
    const { scan, home, environment } = await fixture();
    await rm(join(home, "auth.json"));
    let requests = 0;
    await expect(
      publishScanToCloud(scan, {
        environment: {
          ...environment,
          CODEX_SECURITY_CLOUD_BASE_URL:
            "http://cloud.example.test/backend-api/aardvark",
        },
        fetch: async () => {
          requests++;
          return Response.json(receipt);
        },
      }),
    ).rejects.toThrow("requires HTTPS");
    expect(requests).toBe(0);
  });

  test("reuses the dedicated Codex Security login and honors an explicit logout", async () => {
    const { scan, environment } = await fixture();
    const home = codexSecurityCredentialHome(environment);
    await mkdir(home, { recursive: true, mode: 0o700 });
    await writeFile(
      join(home, "auth.json"),
      JSON.stringify({
        ...login,
        tokens: { ...login.tokens, account_id: "dedicated-account" },
      }),
      { mode: 0o600 },
    );
    await writeCredentialHomeConfig(home, {
      cli_auth_credentials_store: "auto",
    });

    const send = mock(async (_url: string, options: RequestInit) => {
      expect(new Headers(options!.headers).get("ChatGPT-Account-ID")).toBe(
        "dedicated-account",
      );
      return Response.json(receipt);
    });
    await publishScanToCloud(scan, { environment, fetch: send });
    await setCodexSecurityCredentialLogout(home, true);
    await expect(
      publishScanToCloud(scan, { environment, fetch: send }),
    ).rejects.toThrow("ChatGPT login already available to Codex Security");
    expect(send).toHaveBeenCalledTimes(1);
  });

  test.each(["auto", "keyring", "ephemeral"])(
    "does not publish an ambient account copied into the dedicated %s store",
    async (store) => {
      const { scan, home: ambient, environment } = await fixture();
      const home = codexSecurityCredentialHome(environment);
      await mkdir(home, { recursive: true, mode: 0o700 });
      await writeCredentialHomeConfig(home, {
        cli_auth_credentials_store: store,
      });
      // A successful native keyring login removed the old file. Account status
      // can subsequently import a different account's ambient credentials.
      await setCodexSecurityCredentialLogout(home, false);
      await fs.copyFile(join(ambient, "auth.json"), join(home, "auth.json"));
      const send = mock(receiptResponse);
      await expect(
        publishScanToCloud(scan, { environment, fetch: send }),
      ).rejects.toThrow("ChatGPT login already available to Codex Security");
      expect(send).not.toHaveBeenCalled();
    },
  );

  test("resolves missing or empty CODEX_HOME through the existing user-home helper", async () => {
    const { scan, home, environment } = await fixture();
    await mkdir(join(home, ".codex"), { mode: 0o700 });
    await writeFile(join(home, ".codex", "auth.json"), JSON.stringify(login), {
      mode: 0o600,
    });
    await writeFile(
      join(home, ".codex", "config.toml"),
      'cli_auth_credentials_store = "file"\n',
    );
    for (const codexHome of [undefined, "", "  "]) {
      const result = await publishScanToCloud(scan, {
        environment: {
          ...environment,
          CODEX_HOME: codexHome,
          HOME: home,
          USERPROFILE: home,
        },
        fetch: receiptResponse,
      });
      expect(result.findingIds).toEqual(["finding-1"]);
    }
  });

  test("requires an explicit file credential setting before reading auth.json", async () => {
    const { scan, home, environment } = await fixture();

    const send = mock(receiptResponse);
    for (const config of [undefined, "[features]\nplugins = true\n"]) {
      if (config === undefined) {
        await rm(join(home, "config.toml"));
      } else {
        await writeFile(join(home, "config.toml"), config);
      }
      await expect(
        publishScanToCloud(scan, { environment, fetch: send }),
      ).rejects.toThrow("ChatGPT login already available to Codex Security");
    }
    expect(send).toHaveBeenCalledTimes(0);
  });

  test("rejects unsupported, missing, or malformed credentials without leaking their contents", async () => {
    const { scan, home, environment } = await fixture();

    const send = mock(receiptResponse);
    for (const credentials of [
      { auth_mode: "apikey", OPENAI_API_KEY: "synthetic-api-secret" },
      { ...login, auth_mode: "personal_access_token" },
      { ...login, tokens: { access_token: "synthetic-access-token" } },
      {},
    ]) {
      await writeFile(join(home, "auth.json"), JSON.stringify(credentials), {
        mode: 0o600,
      });
      await expect(
        publishScanToCloud(scan, { environment, fetch: send }),
      ).rejects.toThrow("ChatGPT login already available to Codex Security");
    }
    await writeFile(join(home, "auth.json"), "malformed-synthetic-secret");
    await expect(
      publishScanToCloud(scan, { environment, fetch: send }),
    ).rejects.toThrow("ChatGPT login already available to Codex Security");
    await rm(join(home, "auth.json"));
    await expect(
      publishScanToCloud(scan, { environment, fetch: send }),
    ).rejects.toThrow("ChatGPT login already available to Codex Security");
    expect(send).toHaveBeenCalledTimes(0);
  });

  test("does not use a stale file when keyring or automatic credential storage is selected", async () => {
    const { scan, home, environment } = await fixture();
    const fetchMock = mock(receiptResponse);
    for (const mode of ["keyring", "auto"]) {
      await writeFile(
        join(home, "config.toml"),
        `cli_auth_credentials_store = "${mode}"\n`,
      );
      const error = await publishScanToCloud(scan, {
        environment,
        fetch: fetchMock,
      }).then(
        () => undefined,
        (failure: unknown) => failure,
      );
      expect(String(error)).toContain(
        "ChatGPT login already available to Codex Security",
      );
    }
    expect(fetchMock).toHaveBeenCalledTimes(0);

    await writeFile(
      join(home, "config.toml"),
      'cli_auth_credentials_store = "file"\n[ghost_snapshot]\nignore_large_untracked_files = 9223372036854775807\n',
    );
    await publishScanToCloud(scan, {
      environment,
      fetch: fetchMock,
    });
    expect(fetchMock).toHaveBeenCalledTimes(1);
  });

  test("rejects tampered scan artifacts before reading credentials or uploading", async () => {
    const { scan, environment } = await fixture();
    await writeFile(join(scan, "findings.json"), "{}");
    const fetchMock = mock(receiptResponse);
    await expect(
      publishScanToCloud(scan, {
        environment,
        fetch: fetchMock,
      }),
    ).rejects.toThrow();
    expect(fetchMock).toHaveBeenCalledTimes(0);
  });

  test("does not retry HTTP errors or expose server response bodies", async () => {
    const { scan, environment } = await fixture();
    for (const status of [401, 403, 404, 413, 422, 429, 503]) {
      const fetchMock = mock(responding("synthetic-access-token", status));
      try {
        await publishScanToCloud(scan, {
          environment,
          fetch: fetchMock,
        });
        throw new Error("expected publication to fail");
      } catch (error) {
        expect(String(error)).toContain(`HTTP ${status}`);
        expect(String(error)).not.toContain("synthetic-access-token");
      }
      expect(fetchMock).toHaveBeenCalledTimes(1);
    }
  });

  test("does not retry an ambiguous transport failure", async () => {
    const { scan, environment } = await fixture();
    const fetchMock = mock(rejecting("synthetic-access-token"));
    await expect(
      publishScanToCloud(scan, {
        environment,
        fetch: fetchMock,
      }),
    ).rejects.toThrow("synthetic-access-token");
    expect(fetchMock).toHaveBeenCalledTimes(1);
  });

  test("preserves caller cancellation during the publication request", async () => {
    const { scan, environment } = await fixture();
    const controller = new AbortController();
    const cancellation = new Error("publication cancelled");

    await expect(
      publishScanToCloud(scan, {
        environment,
        signal: controller.signal,
        fetch: async (_url, options) => {
          const signal = options.signal as AbortSignal;
          const waiting = once(signal, "abort");
          controller.abort(cancellation);
          await waiting;
          throw signal.reason;
        },
      }),
    ).rejects.toBe(cancellation);
  });

  test("preserves caller cancellation while parsing the acceptance receipt", async () => {
    const { scan, environment } = await fixture();
    const controller = new AbortController();
    const cancellation = new Error("receipt parsing cancelled");
    const response = {
      ok: true,
      status: 201,
      body: null,
      json: async () => {
        const waiting = once(controller.signal, "abort");
        controller.abort(cancellation);
        await waiting;
        throw controller.signal.reason;
      },
    } as unknown as Response;

    await expect(
      publishScanToCloud(scan, {
        environment,
        signal: controller.signal,
        fetch: async () => response,
      }),
    ).rejects.toBe(cancellation);
  });

  test("requires a complete acceptance receipt instead of treating any 2xx as success", async () => {
    const { scan, environment } = await fixture();
    for (const body of [
      {},
      { ...receipt, status: "queued" },
      { ...receipt, finding_count: 2 },
      { ...receipt, finding_ids: [] },
    ]) {
      await expect(
        publishScanToCloud(scan, {
          environment,
          fetch: async () => Response.json(body),
        }),
      ).rejects.toThrow("invalid acceptance receipt");
    }
    await expect(
      publishScanToCloud(scan, {
        environment,
        fetch: async () => Response.json(receipt, { status: 202 }),
      }),
    ).rejects.toThrow("invalid acceptance receipt");
  });

  test("rejects duplicate opaque IDs in an otherwise complete receipt", async () => {
    const { scan, environment } = await fixture();
    await addSecondFinding(scan);
    await expect(
      publishScanToCloud(scan, {
        environment,
        fetch: async () =>
          Response.json({
            status: "accepted",
            finding_ids: [
              "cloud-observation-duplicate",
              "cloud-observation-duplicate",
            ],
            finding_count: 2,
          }),
      }),
    ).rejects.toThrow("invalid acceptance receipt");
  });
});

async function receiptResponse() {
  return Response.json(receipt);
}