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

35.1 KB
Raw Blame
import { execFileSync, spawnSync } from "node:child_process";
import { getEventListeners } from "node:events";
import { existsSync } from "node:fs";
import {
  chmod,
  mkdtemp,
  mkdir,
  readFile,
  realpath,
  rename,
  rm,
  symlink,
  utimes,
  writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { delimiter, join, relative } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, test } from "bun:test";
import {
  DiffTarget,
  InvalidTargetError,
  normalizeRepository,
  normalizeTarget,
  repositoryRevision,
  type ScanTarget,
} from "../src/index.js";
import {
  abortable,
  enclosingGitWorktreeRoot,
  gitMarkerRoot,
  isGitMetadataDirectory,
  gitProtectionRoots,
  validateCommittedDiffCheckout,
} from "../src/targets.js";
import { createApiTestFixtures } from "./support/temporary-directories.js";
import { runCommand } from "./support/shell.js";

// @ts-expect-error DiffTarget is intentionally nominal; use its constructor helpers.
const structurallyInvalidTarget: ScanTarget = {
  kind: "refs",
  base: "main",
  head: "HEAD",
};
void structurallyInvalidTarget;

const { temporaryDirectory, cleanup, temporaryDirectories } =
  createApiTestFixtures("codex-security-targets-");

afterEach(cleanup);

describe("abortable", () => {
  test.each([
    { label: "error", reason: new Error("Canceled before execution") },
    { label: "object", reason: { message: "Canceled before execution" } },
    { label: "string", reason: "Canceled before execution" },
    { label: "zero", reason: 0 },
    { label: "false", reason: false },
    { label: "null", reason: null },
    { label: "default", reason: undefined },
  ])(
    "does not start canceled work with a $label reason",
    async ({ reason }) => {
      for (const beforeAdmission of [true, false]) {
        const controller = new AbortController();
        let calls = 0;
        if (beforeAdmission) controller.abort(reason);
        const pending = abortable(async () => {
          calls++;
          return "unused";
        }, controller.signal);
        if (!beforeAdmission) controller.abort(reason);
        if (reason === null)
          await expect(pending).rejects.toMatchObject({
            name: "AbortError",
            message: "The operation was aborted.",
          });
        else await expect(pending).rejects.toBe(controller.signal.reason);
        expect(calls).toBe(0);
        expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
      }
    },
  );

  test.each([false, true])(
    "preserves operation ordering with a signal: %p",
    async (withSignal) => {
      const controller = new AbortController();
      const order: string[] = [];
      const result = { completed: true };
      const pending = abortable(
        async () => {
          order.push("operation");
          return result;
        },
        withSignal ? controller.signal : undefined,
      );
      order.push("returned");
      expect(await pending).toBe(result);
      expect(order).toEqual(
        withSignal ? ["returned", "operation"] : ["operation", "returned"],
      );
      expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
      controller.abort(new Error("Canceled after completion"));
      expect(await pending).toBe(result);
    },
  );

  test("cancels started work without awaiting its late failure", async () => {
    const controller = new AbortController();
    const started = Promise.withResolvers<void>();
    const operation = Promise.withResolvers<void>();
    const pending = abortable(() => {
      started.resolve();
      return operation.promise;
    }, controller.signal);
    await started.promise;
    const reason = new Error("Canceled while running");
    controller.abort(reason);
    await expect(pending).rejects.toBe(reason);
    expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
    operation.reject(new Error("Late operation failure"));
    await expect(pending).rejects.toBe(reason);
  });

  test.each(["resolve", "reject"])(
    "preserves cancellation before a queued %s is observed",
    async (settlement) => {
      const controller = new AbortController();
      const started = Promise.withResolvers<void>();
      const operation = Promise.withResolvers<number>();
      const pending = abortable(() => {
        started.resolve();
        return operation.promise;
      }, controller.signal);
      await started.promise;
      if (settlement === "resolve") operation.resolve(7);
      else operation.reject(new Error("Queued operation failure"));
      const reason = new Error("Canceled before settlement");
      controller.abort(reason);
      await expect(pending).rejects.toBe(reason);
      expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
    },
  );
});

async function repository(name = "repo"): Promise<string> {
  const root = await temporaryDirectory();
  const repo = join(root, name);
  await mkdir(join(repo, "src"), { recursive: true });
  await writeFile(join(repo, "src", "app.ts"), "export const ok = true;\n");
  git(repo, "init", "-b", "main");
  git(repo, "config", "--local", "core.autocrlf", "false");
  git(repo, "config", "user.email", "[email protected]");
  git(repo, "config", "user.name", "Test");
  git(repo, "add", ".");
  git(repo, "commit", "-m", "initial");
  return repo;
}

function git(repo: string, ...args: string[]): string {
  return execFileSync("git", args, { cwd: repo, encoding: "utf8" }).trim();
}

function validateCommittedDiffWithCredentialConfig(
  repo: string,
  environment: NodeJS.ProcessEnv = {},
) {
  return spawnSync(
    process.execPath,
    [
      "-e",
      "const { DiffTarget, normalizeTarget, validateCommittedDiffCheckout } = await import(process.argv[1]); const target = await normalizeTarget(process.argv[2], DiffTarget.refs({ base: 'HEAD' })); await validateCommittedDiffCheckout(process.argv[2], target);",
      fileURLToPath(new URL("../src/targets.ts", import.meta.url)),
      repo,
    ],
    {
      encoding: "utf8",
      env: {
        ...process.env,
        ...environment,
        GIT_CONFIG_COUNT: "1",
        GIT_CONFIG_KEY_0: "http.extraHeader",
        GIT_CONFIG_VALUE_0: "SYNTHETIC_GIT_CREDENTIAL",
      },
    },
  );
}

async function createRepositoryGitShim(
  directory: string,
  marker: string,
): Promise<void> {
  await mkdir(directory, { recursive: true });

  if (process.platform === "win32") {
    const batch = `@echo off\r\necho executed> "${marker}"\r\necho malicious\r\n`;
    await Promise.all([
      writeFile(join(directory, "git.exe"), "untrusted executable fixture\n"),
      writeFile(join(directory, "git.com"), "untrusted executable fixture\n"),
      writeFile(join(directory, "git.cmd"), batch),
      writeFile(join(directory, "git.bat"), batch),
      writeFile(join(directory, "git"), "untrusted extensionless fixture\n"),
    ]);
    return;
  }

  const executable = join(directory, "git");
  await writeFile(
    executable,
    `#!/bin/sh\nprintf 'executed\\n' > '${marker}'\nprintf 'malicious\\n'\n`,
  );
  await chmod(executable, 0o700);
}

function environmentWithPath(entries: readonly string[]): NodeJS.ProcessEnv {
  const inheritedPath = Object.entries(process.env).find(
    ([name]) => name.toUpperCase() === "PATH",
  )?.[1];
  const environment = Object.fromEntries(
    Object.entries(process.env).filter(
      ([name]) => name.toUpperCase() !== "PATH",
    ),
  );

  return {
    ...environment,
    ...(process.platform === "win32" ? { PATHEXT: ".CMD;.BAT;.COM;.EXE" } : {}),
    PATH: [...entries, inheritedPath ?? ""].join(delimiter),
  };
}

describe("scan target normalization", () => {
  test("normalizes repository and path targets", async () => {
    const repo = await repository();
    const alias = join(repo, "source-link");
    await symlink(
      join(repo, "src"),
      alias,
      process.platform === "win32" ? "junction" : "dir",
    );
    expect(await normalizeTarget(repo, "repository")).toEqual({
      kind: "repository",
      paths: [],
    });
    expect(
      await normalizeTarget(repo, [
        "src",
        join(repo, "src", "app.ts"),
        join(repo, "src"),
        "src/app.ts",
        alias,
      ]),
    ).toEqual({
      kind: "paths",
      paths: ["src", "src/app.ts"],
    });
  });

  test.skipIf(process.platform !== "win32")(
    "rejects Windows repository roots that alias across runtimes",
    async () => {
      const root = await temporaryDirectory("codex-security-repository-alias-");
      const repository = join(root, "repository");
      const ambiguous = join(root, "repository.");
      const linked = join(root, "linked-repository");
      await Promise.all([mkdir(repository), mkdir(ambiguous)]);
      await symlink(ambiguous, linked, "junction");

      expect(await realpath(repository)).not.toBe(await realpath(ambiguous));
      await expect(normalizeRepository(repository)).resolves.toBe(
        await realpath(repository),
      );
      for (const path of [ambiguous, linked]) {
        await expect(normalizeRepository(path)).rejects.toThrow(
          "Windows-ambiguous components",
        );
      }
    },
  );

  test.skipIf(process.platform === "win32")(
    "preserves trailing whitespace in Git worktree paths",
    async () => {
      for (const suffix of [" ", "\r"]) {
        const repo = await repository(`repo${suffix}`);
        expect(await enclosingGitWorktreeRoot(repo)).toBe(await realpath(repo));
        await expect(
          normalizeTarget(repo, DiffTarget.refs({ base: "HEAD" })),
        ).resolves.toMatchObject({ kind: "refs" });
      }
    },
  );

  test("rejects empty, missing, and escaping paths", async () => {
    const repo = await repository();
    await expect(normalizeTarget(repo, [""])).rejects.toThrow("empty path");
    await expect(normalizeTarget(repo, ["missing.ts"])).rejects.toThrow(
      "Path target does not exist: missing.ts",
    );
    await expect(normalizeTarget(repo, [join(repo, "..")])).rejects.toThrow(
      "outside the repository",
    );
  });

  test.skipIf(process.platform === "win32")(
    "rejects special filesystem targets the scan scope resolver cannot read",
    async () => {
      const repo = await repository();
      const fifo = join(repo, "src", "pending.fifo");
      execFileSync("mkfifo", [fifo]);
      await expect(normalizeTarget(repo, [fifo])).rejects.toThrow(
        "not a regular file or directory",
      );
    },
  );

  test("keeps repository and target paths distinct from their UTF-8 replacements", async () => {
    const root = await temporaryDirectory();
    const repository = join(root, "repo-\uFFFD");
    const file = "sibling-\uFFFD.ts";
    await mkdir(repository);
    await writeFile(join(repository, file), "");
    await expect(
      normalizeTarget(join(root, "repo-") + "\uD800", [file]),
    ).rejects.toThrow("Repository path cannot be represented as UTF-8");
    await expect(
      normalizeTarget(repository, ["sibling-\uDC00.ts"]),
    ).rejects.toThrow("Path target cannot be represented as UTF-8");
    expect((await normalizeTarget(repository, [file])).paths).toEqual([file]);
    if (process.platform === "linux") {
      const raw = Buffer.concat([
        Buffer.from(join(root, "repo-")),
        Buffer.from([0xff]),
      ]);
      const alias = join(root, "selected");
      await mkdir(raw);
      try {
        await symlink(raw, alias);
        await expect(normalizeTarget(alias, [file])).rejects.toThrow(
          "Repository path cannot be represented as UTF-8",
        );
      } finally {
        await rm(raw, { recursive: true });
      }
    }
  });

  test.skipIf(process.platform === "win32").each(["node", "bun"])(
    "identifies special file targets and their links in %s",
    async (runtime) => {
      const root = await temporaryDirectory("cs-target-");
      const build = await Bun.build({
        entrypoints: [
          fileURLToPath(
            new URL("./fixtures/socket-target.ts", import.meta.url),
          ),
        ],
        outdir: root,
        naming: "socket-target.mjs",
        target: "node",
      });
      const result = await runCommand(runtime, [build.outputs[0]!.path, root], {
        cwd: root,
      });
      expect(result.status, result.stderr || result.error?.message).toBe(0);
    },
  );

  test.skipIf(process.platform !== "win32")(
    "rejects NTFS alternate streams before runtime initialization",
    async () => {
      const repo = await repository();
      const stream = join(repo, "src", "app.ts:synthetic-stream");
      await writeFile(stream, "export const hidden = true;\n");

      await expect(normalizeTarget(repo, [stream])).rejects.toThrow(
        "unsupported colon component",
      );
    },
  );

  test.skipIf(process.platform === "win32")(
    "allows colons in POSIX path components",
    async () => {
      const repo = await repository();
      const path = join(repo, "src", "app.ts:fixture");
      await writeFile(path, "export const fixture = true;\n");

      await expect(normalizeTarget(repo, [path])).resolves.toEqual({
        kind: "paths",
        paths: ["src/app.ts:fixture"],
      });
    },
  );

  test.each(
    process.platform === "win32"
      ? ["removed"]
      : ["removed", "retargeted", "replaced after resolution"],
  )("rejects a path %s during canonical resolution", async (change) => {
    const repo = await repository();
    const target = join(repo, "src", "app.ts");
    if (change === "retargeted") {
      const pending = join(repo, "pending");
      execFileSync("mkfifo", [pending]);
      if (process.platform === "linux") {
        const raw = Buffer.concat([Buffer.from(pending), Buffer.from([0xff])]);
        await rename(pending, raw);
        await symlink(raw, pending);
        await writeFile(raw.toString(), "regular sibling");
      }
    }
    if (change === "replaced after resolution")
      await writeFile(join(repo, "..", "outside-file"), "outside");
    const script = `
      import { mockFs } from ${JSON.stringify(fileURLToPath(new URL("./support/module-mocks.ts", import.meta.url)))};
      import { rmSync, symlinkSync } from "node:fs";
      import * as original from "node:fs/promises";
      import { join } from "node:path";
      const [repo, targets, target, change] = process.argv.slice(1);
      const actualRealpath = original.realpath;
      mockFs(() => ({
        realpath: async (path, ...args) => {
          if (path === target && change === "replaced after resolution") {
            const canonical = await actualRealpath(path, ...args);
            rmSync(target);
            symlinkSync(join(repo, "..", "outside-file"), target);
            return canonical;
          }
          if (path === target) {
            rmSync(target);
            if (change === "retargeted") symlinkSync(join(repo, "pending"), target);
          }
          return await actualRealpath(path, ...args);
        },
      }));
      const { normalizeTarget } = await import(targets);
      try {
        await normalizeTarget(repo, [target]);
        console.log("ACCEPTED");
        process.exitCode = 2;
      } catch (error) {
        console.log(
          "REJECTED",
          error instanceof Error && error.name === "InvalidTargetError",
          error instanceof Error ? error.message : String(error),
        );
      }
    `;
    const result = spawnSync(
      process.execPath,
      [
        "-e",
        script,
        repo,
        fileURLToPath(new URL("../src/targets.ts", import.meta.url)),
        target,
        change,
      ],
      { encoding: "utf8" },
    );
    expect(result.status).toBe(0);
    expect(result.stdout).toContain(
      change === "removed"
        ? "REJECTED true Path target does not exist"
        : "REJECTED true Path target is not a regular file or directory",
    );
  });

  test("binds ref and working-tree targets to commit IDs", async () => {
    const repo = await repository();
    const revision = git(repo, "rev-parse", "HEAD");
    const refs = await normalizeTarget(repo, DiffTarget.refs({ base: "HEAD" }));
    expect(refs).toMatchObject({
      kind: "refs",
      base: revision,
      head: revision,
      baseRef: "HEAD",
      headRef: "HEAD",
    });
    const worktree = await normalizeTarget(repo, DiffTarget.workingTree());
    expect(worktree).toMatchObject({
      kind: "working_tree",
      base: revision,
      head: revision,
    });
    await expect(
      normalizeTarget(repo, DiffTarget.refs({ base: "missing", head: "HEAD" })),
    ).rejects.toThrow("unknown Git ref");
  });

  test("preserves user Git settings while removing repository overrides", async () => {
    const repo = await repository();
    const root = join(repo, "..");
    const trace = join(root, "git-events.jsonl");
    await writeFile(
      join(repo, "src", "app.ts"),
      "export const updated = true;\n",
    );
    git(repo, "add", ".");
    git(repo, "commit", "-m", "updated");
    const revision = git(repo, "rev-parse", "HEAD");
    const parent = git(repo, "rev-parse", "HEAD^");
    const shallow = join(root, "shallow");
    await writeFile(shallow, `${revision}\n`);
    const repositoryOverrides = {
      GIT_DIR: join(root, "missing-git-dir"),
      GIT_WORK_TREE: join(root, "missing-work-tree"),
      GIT_INDEX_FILE: join(root, "missing-index"),
      GIT_OBJECT_DIRECTORY: join(root, "missing-objects"),
      GIT_ALTERNATE_OBJECT_DIRECTORIES: join(root, "missing-alternates"),
      GIT_COMMON_DIR: join(root, "missing-common"),
      GIT_REPLACE_REF_BASE: "refs/unsafe/",
      GIT_CEILING_DIRECTORIES: root,
      GIT_DISCOVERY_ACROSS_FILESYSTEM: "1",
      GIT_GRAFT_FILE: join(root, "missing-grafts"),
      GIT_IMPLICIT_WORK_TREE: "0",
      GIT_NAMESPACE: "unsafe",
      GIT_NO_REPLACE_OBJECTS: "1",
      GIT_PREFIX: "unsafe/",
      GIT_SHALLOW_FILE: shallow,
    };
    const result = spawnSync(
      process.execPath,
      [
        "-e",
        "const { DiffTarget, normalizeTarget } = await import(process.argv[1]); console.log(JSON.stringify(await normalizeTarget(process.argv[2], DiffTarget.refs({ base: 'HEAD^' }))));",
        fileURLToPath(new URL("../src/targets.ts", import.meta.url)),
        repo,
      ],
      {
        encoding: "utf8",
        env: {
          ...process.env,
          GIT_CONFIG_COUNT: "1",
          GIT_CONFIG_KEY_0: "codex.security",
          GIT_CONFIG_VALUE_0: "SYNTHETIC_GIT_SETTING",
          GIT_TRACE2_EVENT: trace,
          GIT_TRACE2_CONFIG_PARAMS: "codex.security",
          GIT_TRACE2_ENV_VARS: [
            "GIT_SSL_CAINFO",
            "GIT_SSH_COMMAND",
            ...Object.keys(repositoryOverrides),
          ].join(","),
          GIT_SSL_CAINFO: join(root, "ca.pem"),
          GIT_SSH_COMMAND: "ssh -o BatchMode=yes",
          ...repositoryOverrides,
        },
      },
    );

    expect(result.status).toBe(0);
    expect(JSON.parse(result.stdout)).toMatchObject({
      kind: "refs",
      base: parent,
      head: revision,
    });
    const events = (await readFile(trace, "utf8"))
      .trim()
      .split(/\r?\n/u)
      .map((line) => JSON.parse(line) as { param?: string; value?: string });
    expect(events).toContainEqual(
      expect.objectContaining({
        param: "codex.security",
        value: "SYNTHETIC_GIT_SETTING",
      }),
    );
    for (const name of ["GIT_SSL_CAINFO", "GIT_SSH_COMMAND"]) {
      expect(events.some(({ param }) => param === name)).toBe(true);
    }
    for (const name of Object.keys(repositoryOverrides)) {
      expect(events.some(({ param }) => param === name)).toBe(false);
    }
  });

  test("checks assumed-unchanged files against a committed diff without changing index flags", async () => {
    const repo = await repository();
    const name = "src/app.ts";
    const file = join(repo, name);
    const original = await readFile(file);
    const target = await normalizeTarget(
      repo,
      DiffTarget.refs({ base: "HEAD" }),
    );
    git(repo, "update-index", "--assume-unchanged", "--", name);
    const hook = join(repo, ".git", "hooks", "post-index-change");
    await writeFile(
      hook,
      '#!/bin/sh\nif test -n "$GIT_INDEX_FILE"; then echo ran >.git/refresh-hook-ran; fi\n',
      { mode: 0o755 },
    );
    await validateCommittedDiffCheckout(repo, target);

    await writeFile(file, "export const changed = true;\n");
    expect(git(repo, "status", "--porcelain")).toBe("");
    await expect(validateCommittedDiffCheckout(repo, target)).rejects.toThrow(
      "clean repository checkout",
    );
    if (process.platform !== "win32") {
      const child = validateCommittedDiffWithCredentialConfig(repo, {
        TMPDIR: relative(process.cwd(), join(repo, "..")),
      });
      expect(child.status).toBe(1);
      expect(child.stderr).toContain("clean repository checkout");
    }
    expect(git(repo, "ls-files", "-v", "--", name)).toBe(`h ${name}`);
    await writeFile(file, original);
    await validateCommittedDiffCheckout(repo, target);
    expect(existsSync(join(repo, ".git", "refresh-hook-ran"))).toBe(false);
  });

  test("does not expose Git configuration to repository fsmonitor hooks", async () => {
    const repo = await repository();
    const root = join(repo, "..");
    const hook = join(root, "fsmonitor-hook");
    const leaked = join(root, "leaked-credential");
    await writeFile(
      hook,
      `#!/bin/sh\nprintf '%s' "$GIT_CONFIG_VALUE_0" > ${JSON.stringify(leaked)}\nprintf '\\0'\n`,
    );
    await chmod(hook, 0o700);
    git(repo, "config", "core.fsmonitor", hook);

    const result = validateCommittedDiffWithCredentialConfig(repo);

    expect(result.status).toBe(0);
    expect(existsSync(leaked)).toBe(false);
  });

  test("does not expose Git configuration to repository clean filters", async () => {
    const repo = await repository();
    const root = join(repo, "..");
    const filter = join(root, "clean-filter.js");
    const executed = join(root, "filter-executed");
    const leaked = join(root, "leaked-credential");
    await writeFile(
      join(repo, ".gitattributes"),
      "src/app.ts filter=capture\n",
    );
    git(repo, "add", ".gitattributes");
    git(repo, "commit", "-m", "configure attributes");
    await writeFile(
      filter,
      [
        'import { readFileSync, writeFileSync } from "node:fs";',
        `writeFileSync(${JSON.stringify(executed)}, "executed");`,
        `if (process.env.GIT_CONFIG_VALUE_0) writeFileSync(${JSON.stringify(leaked)}, process.env.GIT_CONFIG_VALUE_0);`,
        "process.stdout.write(readFileSync(0));",
      ].join("\n"),
    );
    git(
      repo,
      "config",
      "filter.capture.clean",
      `${JSON.stringify(process.execPath.replaceAll("\\", "/"))} ${JSON.stringify(filter.replaceAll("\\", "/"))}`,
    );
    await utimes(join(repo, "src", "app.ts"), new Date(0), new Date(0));

    const result = validateCommittedDiffWithCredentialConfig(repo);

    expect(result.status).toBe(0);
    expect(existsSync(executed)).toBe(true);
    expect(existsSync(leaked)).toBe(false);
  });

  test("does not expose Git configuration to repository promisor helpers", async () => {
    const repo = await repository();
    const root = join(repo, "..");
    const helper = join(root, "promisor-helper.js");
    const executed = join(root, "promisor-executed");
    const leaked = join(root, "leaked-credential");
    const revision = git(repo, "rev-parse", "HEAD");
    await writeFile(
      helper,
      [
        'import { writeFileSync } from "node:fs";',
        `writeFileSync(${JSON.stringify(executed)}, "executed");`,
        `if (process.env.GIT_CONFIG_VALUE_0) writeFileSync(${JSON.stringify(leaked)}, process.env.GIT_CONFIG_VALUE_0);`,
        "process.exit(1);",
      ].join("\n"),
    );
    git(repo, "config", "extensions.partialClone", "unsafe");
    git(repo, "config", "remote.unsafe.promisor", "true");
    git(repo, "config", "protocol.ext.allow", "always");
    git(
      repo,
      "config",
      "remote.unsafe.url",
      `ext::${process.execPath.replaceAll("\\", "/")} ${helper.replaceAll("\\", "/")}`,
    );
    await rm(
      join(repo, ".git", "objects", revision.slice(0, 2), revision.slice(2)),
    );

    const result = spawnSync(
      process.execPath,
      [
        "-e",
        "const { repositoryRevision } = await import(process.argv[1]); console.log(await repositoryRevision(process.argv[2]));",
        fileURLToPath(new URL("../src/targets.ts", import.meta.url)),
        repo,
      ],
      {
        encoding: "utf8",
        env: {
          ...process.env,
          GIT_CONFIG_COUNT: "1",
          GIT_CONFIG_KEY_0: "http.extraHeader",
          GIT_CONFIG_VALUE_0: "SYNTHETIC_GIT_CREDENTIAL",
          GIT_ALLOW_PROTOCOL: "ext",
        },
      },
    );

    expect(result.status).toBe(0);
    expect(result.stdout.trim()).toBe("null");
    expect(existsSync(executed)).toBe(false);
    expect(existsSync(leaked)).toBe(false);
  });

  test("does not execute repository-local Git shims from PATH", async () => {
    const repo = await repository();
    const root = join(repo, "..");
    const unsafeBin = join(repo, "node_modules", ".bin");
    const linkedBin = join(root, "linked-bin");
    const marker = join(root, "git-executed");
    const revision = git(repo, "rev-parse", "HEAD");
    await createRepositoryGitShim(unsafeBin, marker);
    await symlink(
      unsafeBin,
      linkedBin,
      process.platform === "win32" ? "junction" : "dir",
    );

    const script = `
        const { repositoryRevision } = await import(process.argv[1]);
        console.log(await repositoryRevision(process.argv[2]));
      `;
    const result = spawnSync(
      process.execPath,
      [
        "-e",
        script,
        fileURLToPath(new URL("../src/targets.ts", import.meta.url)),
        repo,
      ],
      {
        cwd: repo,
        encoding: "utf8",
        env: environmentWithPath([
          unsafeBin,
          linkedBin,
          "node_modules/.bin",
          "",
        ]),
      },
    );
    expect(result.status).toBe(0);
    expect(result.stdout.trim()).toBe(revision);
    expect(existsSync(marker)).toBe(false);
  });

  test("does not execute worktree-local Git shims when scanning a subdirectory", async () => {
    const repo = await repository();
    const target = join(repo, "src");
    const unsafeBin = join(repo, "node_modules", ".bin");
    const marker = join(repo, "git-executed");
    const revision = git(repo, "rev-parse", "HEAD");
    await createRepositoryGitShim(unsafeBin, marker);

    const script = `
        const { enclosingGitWorktreeRoot, repositoryRevision } = await import(process.argv[1]);
        console.log(await enclosingGitWorktreeRoot(process.argv[2]));
        console.log(await repositoryRevision(process.argv[2]));
      `;
    const result = spawnSync(
      process.execPath,
      [
        "-e",
        script,
        fileURLToPath(new URL("../src/targets.ts", import.meta.url)),
        target,
      ],
      {
        cwd: target,
        encoding: "utf8",
        env: environmentWithPath([unsafeBin]),
      },
    );
    expect(result.status).toBe(0);
    expect(result.stdout.trim().split(/\r?\n/u)).toEqual([
      await realpath(repo),
      revision,
    ]);
    expect(existsSync(marker)).toBe(false);
  });

  test("keeps the requested base and head when refs diverge", async () => {
    const repo = await repository();
    git(repo, "checkout", "-b", "feature");
    await writeFile(
      join(repo, "src", "feature.ts"),
      "export const feature = true;\n",
    );
    git(repo, "add", ".");
    git(repo, "commit", "-m", "feature");
    const head = git(repo, "rev-parse", "HEAD");
    git(repo, "checkout", "main");
    await writeFile(
      join(repo, "src", "upstream.ts"),
      "export const upstream = true;\n",
    );
    git(repo, "add", ".");
    git(repo, "commit", "-m", "upstream");
    const base = git(repo, "rev-parse", "HEAD");

    expect(
      await normalizeTarget(
        repo,
        DiffTarget.refs({ base: "main", head: "feature" }),
      ),
    ).toMatchObject({
      kind: "refs",
      base,
      head,
      baseRef: "main",
      headRef: "feature",
    });
  });

  test("requires the Git worktree root", async () => {
    const repo = await repository();
    await expect(
      normalizeTarget(join(repo, "src"), DiffTarget.refs({ base: "HEAD" })),
    ).rejects.toThrow("Git worktree root");
  });

  test("rejects invalid public DiffTarget states", () => {
    expect(
      () =>
        new DiffTarget({
          kind: "typo" as "refs",
          base: "HEAD",
        }),
    ).toThrow(InvalidTargetError);
    expect(() => new DiffTarget({ kind: "refs", base: "HEAD" })).toThrow(
      "head ref",
    );
    expect(
      () =>
        new DiffTarget({ kind: "working_tree", base: "HEAD", head: "HEAD" }),
    ).toThrow("cannot specify a head");
  });

  test("keeps DiffTarget immutable and revalidates forged states", async () => {
    const refs = DiffTarget.refs({ base: "HEAD", head: "HEAD" });
    expect(Object.isFrozen(refs)).toBe(true);
    expect(() =>
      Object.assign(refs, { kind: "typo", head: undefined }),
    ).toThrow();

    const repo = await repository();
    const forged = (kind: string, base: unknown, head: unknown): DiffTarget =>
      Object.assign(Object.create(DiffTarget.prototype), { kind, base, head });
    await expect(
      normalizeTarget(repo, forged("typo", "HEAD", undefined)),
    ).rejects.toThrow("Unsupported diff target kind");
    await expect(
      normalizeTarget(repo, forged("refs", "", "HEAD")),
    ).rejects.toThrow("base ref");
    await expect(
      normalizeTarget(repo, forged("refs", "HEAD", undefined)),
    ).rejects.toThrow("head ref");
    await expect(
      normalizeTarget(repo, forged("working_tree", "HEAD", "HEAD")),
    ).rejects.toThrow("cannot specify a head");
  });

  test("revalidates a forged diff head after resolving the base", async () => {
    const repo = await repository();
    let headReads = 0;
    const forged: DiffTarget = Object.assign(
      Object.create(DiffTarget.prototype),
      { kind: "refs", base: "HEAD" },
    );
    Object.defineProperty(forged, "head", {
      get: () => (++headReads <= 2 ? "HEAD" : undefined),
    });

    const normalized = normalizeTarget(repo, forged);
    await expect(normalized).rejects.toThrow(InvalidTargetError);
    await expect(normalized).rejects.toThrow(
      "Git diff refs must include a non-empty head ref.",
    );
  });

  test("honors cancellation before repository and Git validation", async () => {
    const repo = await repository();
    const controller = new AbortController();
    const reason = new DOMException("canceled", "AbortError");
    controller.abort(reason);
    await expect(normalizeRepository(repo, controller.signal)).rejects.toBe(
      reason,
    );
    await expect(
      normalizeTarget(
        repo,
        DiffTarget.refs({ base: "HEAD" }),
        controller.signal,
      ),
    ).rejects.toBe(reason);
    await expect(repositoryRevision(repo, controller.signal)).rejects.toBe(
      reason,
    );
  });

  test("resolves home-relative scan paths using native separators", async () => {
    const root = await mkdtemp(join(tmpdir(), "codex-security-home-"));
    temporaryDirectories.track(root);
    const home = await realpath(root);
    const names = ["project"];
    if (process.platform !== "win32") names.push("\\project");
    for (const name of names) await mkdir(join(home, name));
    const inputs = names.flatMap((name) =>
      ["~/", "~//", "~///"].map((prefix) => prefix + name),
    );
    const script = `
      const { normalizeRepository } = await import(process.argv[1]);
      for (const value of process.argv.slice(2)) {
        console.log(await normalizeRepository(value));
      }
    `;
    const result = spawnSync(
      process.execPath,
      [
        "-e",
        script,
        fileURLToPath(new URL("../src/targets.ts", import.meta.url)),
        ...inputs,
      ],
      {
        encoding: "utf8",
        env: { ...process.env, HOME: root, USERPROFILE: root },
      },
    );
    expect(result.status).toBe(0);
    expect(result.stdout.trim().split(/\r?\n/)).toEqual(
      inputs.map((value) => join(home, value.slice(2))),
    );
  });
});

test("finds Git boundaries through directory aliases and file inputs", async () => {
  const repo = await repository();
  const nested = join(repo, "nested");
  await mkdir(join(nested, ".git"), { recursive: true });
  const document = join(nested, "context.md");
  await writeFile(document, "Synthetic context.\n");
  const alias = join(repo, "..", "nested-alias");
  await symlink(
    nested,
    alias,
    process.platform === "win32" ? "junction" : "dir",
  );
  expect(await gitMarkerRoot(alias, undefined, "nearest")).toBe(nested);
  expect(await gitMarkerRoot(alias, undefined, "outermost")).toBe(repo);
  expect(
    await gitMarkerRoot(
      join(alias, "removed", "child"),
      undefined,
      "outermost",
    ),
  ).toBe(repo);
  expect(
    await gitMarkerRoot(
      join(alias, "context.md", "child"),
      undefined,
      "outermost",
    ),
  ).toBe(repo);
  expect(
    await gitMarkerRoot(join(alias, "context.md"), undefined, "outermost"),
  ).toBe(repo);
});

test.skipIf(process.platform === "win32")(
  "protects the enclosing checkout when a saved component becomes a symlink loop",
  async () => {
    const repo = await repository();
    const component = join(repo, "component");
    await symlink("component", component);
    expect(await gitProtectionRoots(component)).toContain(repo);
    await expect(
      gitMarkerRoot(component, undefined, "nearest"),
    ).rejects.toMatchObject({
      code: "ELOOP",
    });
  },
);

test("ordinary storage folders with malformed config are not Git metadata", async () => {
  const root = await temporaryDirectory();
  await mkdir(join(root, "objects"));
  await mkdir(join(root, "refs"));
  await writeFile(join(root, "config"), "ordinary application configuration\n");
  expect(await isGitMetadataDirectory(root)).toBe(false);
  expect(await normalizeRepository(root)).toBe(await realpath(root));
});

test("invalid diff refs retain the Git diagnostic", async () => {
  const repo = await repository();
  const original = spawnSync(
    "git",
    [
      "-C",
      repo,
      "rev-parse",
      "--verify",
      "--end-of-options",
      "missing-fixture-ref^{commit}",
    ],
    { encoding: "utf8" },
  );
  expect(original.status).not.toBe(0);
  await expect(
    normalizeTarget(repo, DiffTarget.refs({ base: "missing-fixture-ref" })),
  ).rejects.toThrow(original.stderr.trim());
});

test("executable protection retains lexical and canonical checkout roots", async () => {
  const lexical = await repository();
  const canonical = await repository("destination");
  const alias = join(lexical, "linked-target");
  await symlink(
    canonical,
    alias,
    process.platform === "win32" ? "junction" : "dir",
  );
  expect(await gitProtectionRoots(alias)).toEqual(
    expect.arrayContaining([lexical, canonical]),
  );
  expect(await gitProtectionRoots(join(alias, "missing", "child"))).toEqual(
    expect.arrayContaining([lexical, canonical]),
  );
});

test("executable protection follows native parent traversal before finding Git roots", async () => {
  const stored = await repository("stored");
  const physical = await repository("physical");
  const link = join(stored, "child");
  await symlink(
    join(physical, "src"),
    link,
    process.platform === "win32" ? "junction" : "dir",
  );
  const expected = process.platform === "win32" ? [stored] : [physical, stored];
  for (const suffix of [".git", "missing/child"]) {
    expect((await gitProtectionRoots(`${link}/../${suffix}`)).sort()).toEqual(
      expected.toSorted(),
    );
  }
});