mirror of
https://github.com/openai/codex-security.git
synced 2026-12-03 10:53:23 +08:00
Merge remote-tracking branch 'origin/main' into codex/simplify-scanner-base-20261110
This commit is contained in:
@@ -8,7 +8,7 @@ runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Install Trivy
|
||||
uses: taiki-e/install-action@682ce6c3c696a4cd5168a05f98e51aa02b877941 # v2.89.1
|
||||
uses: taiki-e/install-action@b80e2bb2635f28eb98b9fce1e2f0887e1535c6b2 # v2.90.0
|
||||
with:
|
||||
tool: trivy@0.76.1
|
||||
- name: Check for high and critical vulnerabilities
|
||||
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Install ShellCheck and zizmor
|
||||
uses: taiki-e/install-action@682ce6c3c696a4cd5168a05f98e51aa02b877941 # v2.89.1
|
||||
uses: taiki-e/install-action@b80e2bb2635f28eb98b9fce1e2f0887e1535c6b2 # v2.90.0
|
||||
with:
|
||||
tool: shellcheck@0.11.0,zizmor@1.30.1
|
||||
- name: Install actionlint
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"wolfi_key_sha256": "f0031424cf46f7db780ce63a45f0fd6aa6f85f601e6bb3b7a91fe3d4d5b7d2cc",
|
||||
"repository": "https://packages.wolfi.dev/os",
|
||||
"local_package": "codex-security=0.7.0-r1",
|
||||
"payload_sha256": "db42f7b5b4d0bfc79975e38778ece88d02d31887a262f8a5c0e5bdfdbbe3563d",
|
||||
"payload_sha256": "3e8c94eb8ff8ff4d041722d133e059aeffd9084a73fc63a1f3b1670e879c9ab9",
|
||||
"image_revision": 0,
|
||||
"snapshots": {
|
||||
"builder": {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"@openai/codex@0.165.0-linux-x64": "https://github.com/openai/codex/tree/360319d8dee62d87e2d59fc0c21805d79519cfed",
|
||||
"@napi-rs/canvas-linux-x64-gnu@1.0.10": "https://github.com/Brooooooklyn/canvas/tree/7d19abed029287e7c26b14eaa6e67d560a37d853",
|
||||
"@napi-rs/canvas-linux-x64-gnu@1.0.13": "https://github.com/Brooooooklyn/canvas/tree/00a115d9903647f116daf86eccd2c6ba36128371",
|
||||
"@napi-rs/canvas-linux-x64-gnu@1.1.0": "https://github.com/Brooooooklyn/canvas/tree/5246bbf5573fdf53b5672a4d096d4d8fa660a406",
|
||||
"@openai/codex@0.166.0-linux-x64": "https://github.com/openai/codex/tree/6ff1e1ca3b30fc8b914720681fcf5fe62e95f856",
|
||||
"@openai/codex@0.167.0-linux-x64": "https://github.com/openai/codex/tree/086ccc833bc9cf01024ad2dd6af7dbd421b6bf9a"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
Copyright (c) 2011 Google Inc. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in
|
||||
the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
|
||||
* Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -23,6 +23,10 @@
|
||||
"source": "https://raw.githubusercontent.com/scalar/scalar/71c72fbc1c3860ac741812617057141db2033fcd/LICENSE",
|
||||
"sha256": "380cd0a6ad700e1f821f2a509f0dd9ff835041cee2d43daf5dedc1adb2bcc620"
|
||||
},
|
||||
"SKIA-LICENSE": {
|
||||
"source": "https://raw.githubusercontent.com/google/skia/b94213a11b3a2edadfae89f0c57a7f4ab72772c9/LICENSE",
|
||||
"sha256": "5f787c1dee3c56547f09ccc2906ab5f5293c4d8dd6c8654e573216c38e908dbd"
|
||||
},
|
||||
"YOGA-LICENSE": {
|
||||
"source": "https://raw.githubusercontent.com/react/yoga/042f5013152eb81c1552dec945b88f7b95ca350f/LICENSE",
|
||||
"sha256": "52412d7bc7ce4157ea628bbaacb8829e0a9cb3c58f57f99176126bc8cf2bfc85"
|
||||
|
||||
Generated
+4
-4
@@ -1753,8 +1753,8 @@ packages:
|
||||
seedrandom@3.0.5:
|
||||
resolution: {integrity: sha512-8OwmbklUNzwezjGInmZ+2clQmExQPvomqjL7LFqOYqtmuxRgQYqOD3mHaU+MvZn5FLUeVxVfQjwLZW/n/JFuqg==}
|
||||
|
||||
semver@7.8.5:
|
||||
resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==}
|
||||
semver@7.8.6:
|
||||
resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==}
|
||||
engines: {node: '>=10'}
|
||||
hasBin: true
|
||||
|
||||
@@ -3549,7 +3549,7 @@ snapshots:
|
||||
python-shell: 5.0.0
|
||||
rfdc: 1.4.1
|
||||
saxes: 6.0.0
|
||||
semver: 7.8.5
|
||||
semver: 7.8.6
|
||||
signal-exit: 4.1.0
|
||||
simple-git: 4.0.2
|
||||
socket.io: 4.8.4
|
||||
@@ -3699,7 +3699,7 @@ snapshots:
|
||||
|
||||
seedrandom@3.0.5: {}
|
||||
|
||||
semver@7.8.5: {}
|
||||
semver@7.8.6: {}
|
||||
|
||||
send@1.2.1:
|
||||
dependencies:
|
||||
|
||||
@@ -48,6 +48,7 @@
|
||||
"CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",
|
||||
"CODEX_SECURITY_SCAN_DIR",
|
||||
"CODEX_SECURITY_PLUGIN_ROOT",
|
||||
"CODEX_SECURITY_REPOSITORY",
|
||||
"CODEX_SECURITY_SCAN_ROOT",
|
||||
"CODEX_SECURITY_STATE_DIR",
|
||||
"CODEX_SECURITY_SURFACE",
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import {
|
||||
accessSync,
|
||||
type BigIntStats,
|
||||
constants as fsConstants,
|
||||
createReadStream,
|
||||
existsSync,
|
||||
promises as fs,
|
||||
readdirSync,
|
||||
@@ -33,7 +32,11 @@ import {
|
||||
profileConfigOverrides,
|
||||
} from "../../../scripts/codex_profile.mjs";
|
||||
import { DEEP_SCAN_SETTINGS } from "../deep-scan-settings.js";
|
||||
import { executablePathForSpawn } from "../executable-path.js";
|
||||
import {
|
||||
configuredExecutableValue,
|
||||
executablePathForSpawn,
|
||||
isExecutableFile,
|
||||
} from "../executable-path.js";
|
||||
import { writePrivateFile } from "./artifacts.js";
|
||||
import { workerTokenUsage } from "./usage-receipt.js";
|
||||
import {
|
||||
@@ -82,6 +85,7 @@ export interface CodexSdkWorkerArtifactContext {
|
||||
interface BoundCodexExecutable {
|
||||
readonly path: string;
|
||||
readonly identity: BigIntStats;
|
||||
readonly sha256?: string;
|
||||
}
|
||||
|
||||
interface CodexSdkWorkerRuntimeSettings {
|
||||
@@ -97,7 +101,10 @@ interface CodexSdkWorkerRuntimeSettings {
|
||||
export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
|
||||
private runtimeSettings?: Promise<CodexSdkWorkerRuntimeSettings>;
|
||||
// Each live coordinator keeps the executable selected for its first worker.
|
||||
private codexExecutable?: Promise<BoundCodexExecutable>;
|
||||
private codexExecutable?: {
|
||||
signal: AbortSignal;
|
||||
promise: Promise<BoundCodexExecutable>;
|
||||
};
|
||||
private parentCyberAccessProgram?: Promise<CyberAccessProgram | undefined>;
|
||||
private pluginVersion?: Promise<string | undefined>;
|
||||
|
||||
@@ -129,6 +136,49 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
|
||||
return turn.finalResponse;
|
||||
}
|
||||
|
||||
private async getCodexExecutable(
|
||||
environment: NodeJS.ProcessEnv,
|
||||
cwd: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<BoundCodexExecutable> {
|
||||
while (true) {
|
||||
signal.throwIfAborted();
|
||||
let binding = this.codexExecutable;
|
||||
if (!binding) {
|
||||
binding = {
|
||||
signal,
|
||||
promise: bindCodexExecutable(environment, cwd, signal).catch(
|
||||
(error) => {
|
||||
// An unsuccessful snapshot has not pinned an executable yet.
|
||||
if (this.codexExecutable === binding)
|
||||
this.codexExecutable = undefined;
|
||||
throw error;
|
||||
},
|
||||
),
|
||||
};
|
||||
this.codexExecutable = binding;
|
||||
}
|
||||
const aborted = Promise.withResolvers<never>();
|
||||
const onAbort = () => aborted.reject(signal.reason);
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal.aborted) onAbort();
|
||||
try {
|
||||
const executable = await Promise.race([
|
||||
binding.promise,
|
||||
aborted.promise,
|
||||
]);
|
||||
signal.throwIfAborted();
|
||||
return executable;
|
||||
} catch (error) {
|
||||
signal.throwIfAborted();
|
||||
// Another worker's cancellation does not cancel this caller's first lookup.
|
||||
if (!binding.signal.aborted) throw error;
|
||||
} finally {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async runTurn(
|
||||
request:
|
||||
| CodexWorkerRequest
|
||||
@@ -151,6 +201,7 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
|
||||
? undefined
|
||||
: resolve(dirname(discovery.promptPath), `limits-${randomUUID()}.toml`);
|
||||
try {
|
||||
request.signal.throwIfAborted();
|
||||
const parentSandbox = this.modelSettings.parentSandbox;
|
||||
if (!parentSandbox) {
|
||||
throw new DeepScanNonRetryableError(
|
||||
@@ -329,15 +380,12 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
|
||||
"CODEX_API_KEY",
|
||||
process.platform,
|
||||
)?.trim();
|
||||
const executable = await (this.codexExecutable ??= bindCodexExecutable(
|
||||
const executable = await this.getCodexExecutable(
|
||||
childEnv,
|
||||
originalCwd,
|
||||
).catch((error) => {
|
||||
// A failed first lookup has not pinned an executable yet; allow startup retries.
|
||||
this.codexExecutable = undefined;
|
||||
throw error;
|
||||
}));
|
||||
await verifyBoundCodexExecutable(executable);
|
||||
request.signal,
|
||||
);
|
||||
await verifyBoundCodexExecutable(executable, request.signal);
|
||||
const preflightOptions = {
|
||||
codexPath: executable.path,
|
||||
cwd: request.workingDirectory,
|
||||
@@ -444,7 +492,7 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
|
||||
|
||||
try {
|
||||
// Detect updates during preflight before starting a fresh or resumed worker.
|
||||
await verifyBoundCodexExecutable(executable);
|
||||
await verifyBoundCodexExecutable(executable, controller.signal);
|
||||
const { events } = await thread.runStreamed(input, {
|
||||
signal: controller.signal,
|
||||
...(request.kind === "compare" && { outputSchema: request.schema }),
|
||||
@@ -518,6 +566,9 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
|
||||
request.signal.removeEventListener("abort", forwardAbort);
|
||||
}
|
||||
} catch (error) {
|
||||
// Pin checks throw the caller's reason directly; keep SDK worker errors intact.
|
||||
if (request.signal.aborted && error === request.signal.reason)
|
||||
throw error;
|
||||
throw classifyCodexWorkerError(error);
|
||||
} finally {
|
||||
if (includePathsFile !== undefined)
|
||||
@@ -610,6 +661,8 @@ function workerPermissionProfile(
|
||||
]);
|
||||
if (sandbox.pluginReadRoot !== undefined)
|
||||
filesystem.set(sandbox.pluginReadRoot, { ".": "read" });
|
||||
if (sandbox.sourceReadRoot !== undefined)
|
||||
filesystem.set(sandbox.sourceReadRoot, { ".": "read" });
|
||||
for (const path of [...sandbox.filesystemDenies, ...literalDenies])
|
||||
filesystem.set(path, "deny");
|
||||
const pointDenies = literalDenies.filter((path) => /[*?[\]]/u.test(path));
|
||||
@@ -777,34 +830,101 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
async function bindCodexExecutable(
|
||||
env: NodeJS.ProcessEnv,
|
||||
originalCwd: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<BoundCodexExecutable> {
|
||||
signal?.throwIfAborted();
|
||||
const path = resolveCodexPath(
|
||||
env,
|
||||
process.platform,
|
||||
process.arch,
|
||||
originalCwd,
|
||||
);
|
||||
return { path, identity: await codexExecutableIdentity(path) };
|
||||
const identity = await codexExecutableIdentity(path);
|
||||
signal?.throwIfAborted();
|
||||
if (process.platform !== "win32") return { path, identity };
|
||||
const sha256 = await codexExecutableDigest(path, signal);
|
||||
const after = await codexExecutableIdentity(path);
|
||||
signal?.throwIfAborted();
|
||||
if (
|
||||
!sameCodexExecutableFile(after, identity) ||
|
||||
after.ctimeNs !== identity.ctimeNs
|
||||
)
|
||||
throw codexExecutableChangedError(path);
|
||||
return { path, identity, sha256 };
|
||||
}
|
||||
|
||||
async function verifyBoundCodexExecutable(
|
||||
executable: BoundCodexExecutable,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
signal?.throwIfAborted();
|
||||
let identity: BigIntStats;
|
||||
try {
|
||||
identity = await codexExecutableIdentity(executable.path);
|
||||
signal?.throwIfAborted();
|
||||
} catch (error) {
|
||||
signal?.throwIfAborted();
|
||||
throw codexExecutableChangedError(executable.path, error);
|
||||
}
|
||||
if (
|
||||
identity.dev !== executable.identity.dev ||
|
||||
identity.ino !== executable.identity.ino ||
|
||||
identity.size !== executable.identity.size ||
|
||||
identity.mtimeNs !== executable.identity.mtimeNs ||
|
||||
identity.ctimeNs !== executable.identity.ctimeNs
|
||||
) {
|
||||
if (!sameCodexExecutableFile(identity, executable.identity)) {
|
||||
throw codexExecutableChangedError(executable.path);
|
||||
}
|
||||
if (identity.ctimeNs !== executable.identity.ctimeNs) {
|
||||
if (process.platform === "win32" && executable.sha256 !== undefined) {
|
||||
// Windows can advance change time on first execution without changing bytes.
|
||||
try {
|
||||
while (true) {
|
||||
signal?.throwIfAborted();
|
||||
const sha256 = await codexExecutableDigest(executable.path, signal);
|
||||
const after = await codexExecutableIdentity(executable.path);
|
||||
signal?.throwIfAborted();
|
||||
if (
|
||||
!sameCodexExecutableFile(after, executable.identity) ||
|
||||
sha256 !== executable.sha256
|
||||
)
|
||||
break;
|
||||
if (after.ctimeNs === identity.ctimeNs) return;
|
||||
// Confirm a stable content snapshot if change time advanced during the read.
|
||||
identity = after;
|
||||
}
|
||||
} catch (error) {
|
||||
signal?.throwIfAborted();
|
||||
throw codexExecutableChangedError(executable.path, error);
|
||||
}
|
||||
}
|
||||
throw codexExecutableChangedError(executable.path);
|
||||
}
|
||||
}
|
||||
|
||||
async function codexExecutableDigest(
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
signal?.throwIfAborted();
|
||||
const digest = createHash("sha256");
|
||||
try {
|
||||
for await (const bytes of createReadStream(path, { signal })) {
|
||||
signal?.throwIfAborted();
|
||||
digest.update(bytes);
|
||||
}
|
||||
} catch (error) {
|
||||
signal?.throwIfAborted();
|
||||
throw error;
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
return digest.digest("hex");
|
||||
}
|
||||
|
||||
function sameCodexExecutableFile(
|
||||
actual: BigIntStats,
|
||||
expected: BigIntStats,
|
||||
): boolean {
|
||||
return (
|
||||
actual.dev === expected.dev &&
|
||||
actual.ino === expected.ino &&
|
||||
actual.size === expected.size &&
|
||||
actual.mtimeNs === expected.mtimeNs
|
||||
);
|
||||
}
|
||||
|
||||
async function codexExecutableIdentity(path: string): Promise<BigIntStats> {
|
||||
@@ -1053,11 +1173,12 @@ export function resolveCodexPath(
|
||||
originalCwd: string = process.cwd(),
|
||||
): string {
|
||||
const searchPath = searchPathForPlatform(env, platform);
|
||||
const configured = environmentVariable(
|
||||
env,
|
||||
"CODEX_CLI_PATH",
|
||||
const configured = configuredExecutableValue(
|
||||
environmentVariable(env, "CODEX_CLI_PATH", platform),
|
||||
platform,
|
||||
)?.trim();
|
||||
(value) =>
|
||||
isExecutableFile(absoluteCodexPath(value, platform, originalCwd)),
|
||||
);
|
||||
if (configured && (platform !== "win32" || !isWindowsAppsPath(configured))) {
|
||||
if (isBareCommandName(configured)) {
|
||||
const executableName =
|
||||
@@ -1256,16 +1377,6 @@ function resolveWindowsCachedBinary(
|
||||
return selected?.path;
|
||||
}
|
||||
|
||||
function isExecutableFile(value: string): boolean {
|
||||
try {
|
||||
if (!statSync(value).isFile()) return false;
|
||||
accessSync(value, fsConstants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function absoluteCodexPath(
|
||||
value: string,
|
||||
platform: NodeJS.Platform,
|
||||
|
||||
@@ -15,6 +15,8 @@ export type DeepWorkerParentSandbox = {
|
||||
readonly literalFilesystemDenies?: readonly string[];
|
||||
/** Windows needs the parent's named read root for the selected plugin. */
|
||||
readonly pluginReadRoot?: string;
|
||||
/** Preserve the selected source's named read root for Windows ACL setup. */
|
||||
readonly sourceReadRoot?: string;
|
||||
readonly globScanMaxDepth?: number;
|
||||
};
|
||||
|
||||
@@ -24,6 +26,9 @@ export function resolveDeepWorkerParentSandbox(
|
||||
pluginRoot = process.platform === "win32"
|
||||
? process.env.CODEX_SECURITY_PLUGIN_ROOT
|
||||
: undefined,
|
||||
sourceRoot = process.platform === "win32"
|
||||
? process.env.CODEX_SECURITY_REPOSITORY
|
||||
: undefined,
|
||||
): DeepWorkerParentSandbox {
|
||||
const state = trustedSandboxState(extra);
|
||||
|
||||
@@ -57,6 +62,7 @@ export function resolveDeepWorkerParentSandbox(
|
||||
const filesystemDenies: string[] = [];
|
||||
const literalFilesystemDenies: string[] = [];
|
||||
let pluginReadRoot: string | undefined;
|
||||
let sourceReadRoot: string | undefined;
|
||||
for (const value of filesystem.entries) {
|
||||
const entry = record(value);
|
||||
if (!entry || !isKnownFilesystemAccess(entry.access)) {
|
||||
@@ -103,14 +109,23 @@ export function resolveDeepWorkerParentSandbox(
|
||||
);
|
||||
}
|
||||
literalFilesystemDenies.push(path.path);
|
||||
} else if (
|
||||
entry.access === "read" &&
|
||||
pluginRoot !== undefined &&
|
||||
isAbsolute(path.path) &&
|
||||
relative(toNamespacedPath(path.path), toNamespacedPath(pluginRoot)) ===
|
||||
""
|
||||
) {
|
||||
pluginReadRoot = path.path;
|
||||
} else if (entry.access === "read" && isAbsolute(path.path)) {
|
||||
if (
|
||||
pluginRoot !== undefined &&
|
||||
relative(
|
||||
toNamespacedPath(path.path),
|
||||
toNamespacedPath(pluginRoot),
|
||||
) === ""
|
||||
)
|
||||
pluginReadRoot = path.path;
|
||||
if (
|
||||
sourceRoot !== undefined &&
|
||||
relative(
|
||||
toNamespacedPath(path.path),
|
||||
toNamespacedPath(sourceRoot),
|
||||
) === ""
|
||||
)
|
||||
sourceReadRoot = path.path;
|
||||
}
|
||||
} else if (path.type === "glob_pattern") {
|
||||
if (!isNonEmptyString(path.pattern)) {
|
||||
@@ -150,6 +165,7 @@ export function resolveDeepWorkerParentSandbox(
|
||||
return {
|
||||
filesystemDenies,
|
||||
...(pluginReadRoot === undefined ? {} : { pluginReadRoot }),
|
||||
...(sourceReadRoot === undefined ? {} : { sourceReadRoot }),
|
||||
...(literalFilesystemDenies.length ? { literalFilesystemDenies } : {}),
|
||||
...(globScanMaxDepth !== undefined ? { globScanMaxDepth } : {}),
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { accessSync, constants, statSync } from "node:fs";
|
||||
import { win32 } from "node:path";
|
||||
|
||||
export function executablePathForSpawn(command: string): string {
|
||||
@@ -9,3 +10,38 @@ export function executablePathForSpawn(command: string): string {
|
||||
? command
|
||||
: win32.toNamespacedPath(command);
|
||||
}
|
||||
|
||||
export function isExecutableFile(value: string): boolean {
|
||||
try {
|
||||
if (!statSync(value).isFile()) return false;
|
||||
accessSync(value, constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isExplicitPathWithTrailingWhitespace(
|
||||
value: string,
|
||||
platform: NodeJS.Platform,
|
||||
): boolean {
|
||||
// Bare names keep their usual PATH precedence. Leading padding can change the path's root.
|
||||
return (
|
||||
platform !== "win32" &&
|
||||
value.includes("/") &&
|
||||
value.trimStart() === value &&
|
||||
value.trimEnd() !== value
|
||||
);
|
||||
}
|
||||
|
||||
export function configuredExecutableValue(
|
||||
value: string | undefined,
|
||||
platform: NodeJS.Platform,
|
||||
literalIsExecutable: (value: string) => boolean,
|
||||
): string | undefined {
|
||||
return value &&
|
||||
isExplicitPathWithTrailingWhitespace(value, platform) &&
|
||||
literalIsExecutable(value)
|
||||
? value
|
||||
: value?.trim();
|
||||
}
|
||||
|
||||
@@ -54,6 +54,8 @@ const repositoryEnvironment = [
|
||||
"GIT_COMMON_DIR",
|
||||
"GIT_DIR",
|
||||
"GIT_DISCOVERY_ACROSS_FILESYSTEM",
|
||||
"GIT_GLOB_PATHSPECS",
|
||||
"GIT_ICASE_PATHSPECS",
|
||||
"GIT_INDEX_FILE",
|
||||
"GIT_LITERAL_PATHSPECS",
|
||||
"GIT_NAMESPACE",
|
||||
|
||||
@@ -2,6 +2,10 @@ import { spawn } from "node:child_process";
|
||||
import { constants, promises as fs } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import path from "node:path";
|
||||
import {
|
||||
configuredExecutableValue,
|
||||
isExecutableFile,
|
||||
} from "./executable-path.ts";
|
||||
|
||||
type PythonPlatform = NodeJS.Platform;
|
||||
|
||||
@@ -11,6 +15,7 @@ interface ResolvePythonCommandOptions {
|
||||
homeDirectory?: string;
|
||||
isUsableExecutable?: (candidate: string) => Promise<boolean>;
|
||||
platform?: PythonPlatform;
|
||||
workingDirectory?: string;
|
||||
}
|
||||
|
||||
const MISSING_PYTHON_HELPER_MESSAGE =
|
||||
@@ -29,12 +34,19 @@ export async function resolvePythonCommand(
|
||||
) {
|
||||
return process.env.CODEX_SECURITY_PYTHON_COMMAND;
|
||||
}
|
||||
const configuredPython = options.configuredPython ?? process.env.PYTHON;
|
||||
if (configuredPython?.trim()) {
|
||||
return configuredPython.trim();
|
||||
}
|
||||
|
||||
const platform = options.platform ?? process.platform;
|
||||
const configuredPython = configuredExecutableValue(
|
||||
options.configuredPython ?? process.env.PYTHON,
|
||||
platform,
|
||||
(value) =>
|
||||
isExecutableFile(
|
||||
value.startsWith("/")
|
||||
? value
|
||||
: `${options.workingDirectory ?? process.cwd()}/${value}`,
|
||||
),
|
||||
);
|
||||
if (configuredPython) return configuredPython;
|
||||
|
||||
const pathImplementation = platform === "win32" ? path.win32 : path.posix;
|
||||
const systemPython = platform === "win32" ? "python" : "python3";
|
||||
let cacheDirectory = options.cacheDirectory ?? process.env.XDG_CACHE_HOME;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
export const WORKBENCH_PYTHON = `
|
||||
import json, sys
|
||||
from pathlib import Path
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors=sys.stdout.errors)
|
||||
sys.stderr.reconfigure(encoding="utf-8", errors=sys.stderr.errors)
|
||||
script = Path(sys.argv.pop(1)).resolve()
|
||||
sys.path.insert(0, str(script.parent))
|
||||
args = json.loads(sys.stdin.buffer.readline())
|
||||
|
||||
@@ -10,7 +10,13 @@ import {
|
||||
import { WORKBENCH_PYTHON } from "./server/workbench-process.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const CONFIGURED_SCAN_ROOT = process.env.CODEX_SECURITY_SCAN_ROOT?.trim();
|
||||
const configuredScanRoot = process.env.CODEX_SECURITY_SCAN_ROOT;
|
||||
// A padded absolute or home-relative override must keep its original base.
|
||||
const CONFIGURED_SCAN_ROOT =
|
||||
process.platform !== "win32" &&
|
||||
configuredScanRoot?.trimStart() === configuredScanRoot
|
||||
? configuredScanRoot
|
||||
: configuredScanRoot?.trim();
|
||||
export const PLUGIN_ROOT =
|
||||
process.env.CODEX_SECURITY_PLUGIN_ROOT || resolve(__dirname, "..");
|
||||
|
||||
@@ -35,7 +41,9 @@ export async function runWorkbench(
|
||||
): Promise<JsonObject> {
|
||||
let pythonCommand: string | undefined;
|
||||
try {
|
||||
pythonCommand = await resolvePythonCommand();
|
||||
pythonCommand = await resolvePythonCommand({
|
||||
workingDirectory: PLUGIN_ROOT,
|
||||
});
|
||||
return await executeWorkbench(pythonCommand, args, input, options);
|
||||
} catch (error) {
|
||||
const launchError = pythonCommand
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { existsSync, promises as fs } from "node:fs";
|
||||
import childProcess, { type SpawnOptions } from "node:child_process";
|
||||
import {
|
||||
copyFile,
|
||||
@@ -7,6 +8,7 @@ import {
|
||||
realpath,
|
||||
rename,
|
||||
rm,
|
||||
symlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { syncBuiltinESMExports } from "node:module";
|
||||
@@ -64,6 +66,8 @@ export async function testExecutorExecutablePinning({
|
||||
await testExecutorPinsCodexExecutableAcrossWorkers();
|
||||
await testExecutorRejectsChangedPinnedExecutable();
|
||||
await testExecutorRejectsReplacementAfterPreflight();
|
||||
await testExecutorPinCancellation();
|
||||
await testConcurrentPinCancellation();
|
||||
} finally {
|
||||
childProcess.spawn = originalSpawn;
|
||||
syncBuiltinESMExports();
|
||||
@@ -177,6 +181,35 @@ export async function testExecutorExecutablePinning({
|
||||
() => new CodexSdkWorkerExecutor({ parentSandbox }),
|
||||
);
|
||||
try {
|
||||
const configuredPaths = fixtures.map((fixture) => fixture.executablePath);
|
||||
if (process.platform !== "win32") {
|
||||
const alias = path.join(
|
||||
fixtures[0]!.root,
|
||||
"codex with trailing space ",
|
||||
);
|
||||
await symlink(fixtures[0]!.executablePath, alias);
|
||||
configuredPaths[0] = alias;
|
||||
const other = fixtures[1]!.executablePath;
|
||||
const bare = path.basename(other) + " ";
|
||||
await symlink(
|
||||
fixtures[0]!.executablePath,
|
||||
path.join(fixtures[0]!.root, bare),
|
||||
);
|
||||
assert.equal(
|
||||
resolveCodexPath(
|
||||
{
|
||||
PATH: [path.dirname(other), fixtures[0]!.root].join(
|
||||
path.delimiter,
|
||||
),
|
||||
CODEX_CLI_PATH: bare,
|
||||
},
|
||||
process.platform,
|
||||
process.arch,
|
||||
fixtures[0]!.root,
|
||||
),
|
||||
other,
|
||||
);
|
||||
}
|
||||
for (const fixture of fixtures) {
|
||||
await writeFile(
|
||||
path.join(fixture.root, "prompt.md"),
|
||||
@@ -188,7 +221,7 @@ export async function testExecutorExecutablePinning({
|
||||
await Promise.all(
|
||||
fixtures.map((fixture, index) => {
|
||||
process.env.CODEX_CLI_PATH =
|
||||
fixtures[firstLaunch ? index : 1 - index]!.executablePath;
|
||||
configuredPaths[firstLaunch ? index : 1 - index]!;
|
||||
process.env.FAKE_CODEX_MARKER = fixture.markerPath;
|
||||
return runTurn(
|
||||
executors[index]!,
|
||||
@@ -303,6 +336,121 @@ export async function testExecutorExecutablePinning({
|
||||
}
|
||||
}
|
||||
|
||||
async function testExecutorPinCancellation() {
|
||||
for (const phase of ["binding", "after-preflight"]) {
|
||||
await withWorkerFixture(async (fixture, promptPath, workingDirectory) => {
|
||||
await writeFile(promptPath, "fixture executable pin cancellation\n");
|
||||
const controller = new AbortController();
|
||||
const reason = { message: "synthetic worker cancellation", phase };
|
||||
const originalStat = fs.stat;
|
||||
fs.stat = (async (...args: Parameters<typeof fs.stat>) => {
|
||||
const result = await originalStat(...args);
|
||||
if (
|
||||
args[0] === fixture.executablePath &&
|
||||
(phase === "binding" || existsSync(fixture.preflightMarkerPath))
|
||||
) {
|
||||
controller.abort(reason);
|
||||
}
|
||||
return result;
|
||||
}) as typeof fs.stat;
|
||||
try {
|
||||
await assert.rejects(
|
||||
new CodexSdkWorkerExecutor({ parentSandbox }).run(
|
||||
workerRequest(promptPath, workingDirectory, {
|
||||
signal: controller.signal,
|
||||
}),
|
||||
),
|
||||
(error) => error === reason,
|
||||
);
|
||||
} finally {
|
||||
fs.stat = originalStat;
|
||||
}
|
||||
assert.equal(
|
||||
existsSync(fixture.preflightMarkerPath),
|
||||
phase === "after-preflight",
|
||||
);
|
||||
assert.equal(existsSync(fixture.markerPath), false);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function testConcurrentPinCancellation() {
|
||||
for (const canceled of ["owner", "waiter"]) {
|
||||
await withWorkerFixture(async (fixture, promptPath, workingDirectory) => {
|
||||
await writeFile(
|
||||
promptPath,
|
||||
"fixture shared executable pin cancellation\n",
|
||||
);
|
||||
const owner = new AbortController();
|
||||
const waiter = new AbortController();
|
||||
const reason = new Error(`synthetic ${canceled} cancellation`);
|
||||
const entered = Promise.withResolvers<void>();
|
||||
const release = Promise.withResolvers<void>();
|
||||
const waiting = Promise.withResolvers<void>();
|
||||
const originalStat = fs.stat;
|
||||
const originalAdd = waiter.signal.addEventListener;
|
||||
let held = false;
|
||||
fs.stat = (async (...args: Parameters<typeof fs.stat>) => {
|
||||
const result = await originalStat(...args);
|
||||
if (args[0] === fixture.executablePath && !held) {
|
||||
held = true;
|
||||
entered.resolve();
|
||||
await release.promise;
|
||||
}
|
||||
return result;
|
||||
}) as typeof fs.stat;
|
||||
waiter.signal.addEventListener = function (
|
||||
...args: Parameters<AbortSignal["addEventListener"]>
|
||||
) {
|
||||
const result = originalAdd.apply(this, args);
|
||||
if (args[0] === "abort") waiting.resolve();
|
||||
return result;
|
||||
};
|
||||
const executor = new CodexSdkWorkerExecutor({ parentSandbox });
|
||||
const first = executor.run(
|
||||
workerRequest(promptPath, workingDirectory, { signal: owner.signal }),
|
||||
);
|
||||
let second: ReturnType<typeof executor.run> | undefined;
|
||||
try {
|
||||
await entered.promise;
|
||||
second = executor.run(
|
||||
workerRequest(promptPath, workingDirectory, {
|
||||
signal: waiter.signal,
|
||||
}),
|
||||
);
|
||||
const completed = Promise.allSettled([first, second]);
|
||||
await waiting.promise;
|
||||
(canceled === "owner" ? owner : waiter).abort(reason);
|
||||
release.resolve();
|
||||
const results = await completed;
|
||||
const rejected = results[canceled === "owner" ? 0 : 1]!;
|
||||
const fulfilled = results[canceled === "owner" ? 1 : 0]!;
|
||||
assert.equal(rejected.status, "rejected");
|
||||
if (rejected.status === "rejected")
|
||||
assert.equal(rejected.reason, reason);
|
||||
assert.equal(fulfilled.status, "fulfilled");
|
||||
if (fulfilled.status === "fulfilled")
|
||||
assert.equal(fulfilled.value.threadId, "fixture-thread-id");
|
||||
// A successful pin survives its original caller's later cancellation.
|
||||
(canceled === "owner" ? waiter : owner).abort(
|
||||
new Error("fixture completed"),
|
||||
);
|
||||
const next = await executor.run(
|
||||
workerRequest(promptPath, workingDirectory),
|
||||
);
|
||||
assert.equal(next.threadId, "fixture-thread-id");
|
||||
} finally {
|
||||
release.resolve();
|
||||
owner.abort(reason);
|
||||
waiter.abort(reason);
|
||||
fs.stat = originalStat;
|
||||
waiter.signal.addEventListener = originalAdd;
|
||||
await Promise.allSettled([first, ...(second ? [second] : [])]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function withWorkerFixture(
|
||||
action: (
|
||||
fixture: Fixture,
|
||||
|
||||
@@ -14,7 +14,7 @@ export const executor = await importModule({
|
||||
stdin: {
|
||||
// Expose internal worker checks only to the test fixtures.
|
||||
contents: `${await readFile(executorSource, "utf8")}
|
||||
export { snapshotWorkerEnvironment, appendItemDiagnostic, verifyBoundCodexExecutable };
|
||||
export { snapshotWorkerEnvironment, appendItemDiagnostic, bindCodexExecutable, verifyBoundCodexExecutable };
|
||||
export { parseDeepScan } from "./response.js";`,
|
||||
loader: "ts",
|
||||
resolveDir: path.dirname(fileURLToPath(executorSource)),
|
||||
@@ -22,7 +22,18 @@ export { parseDeepScan } from "./response.js";`,
|
||||
},
|
||||
});
|
||||
|
||||
export const verifyBoundCodexExecutable: (executable: {
|
||||
path: string;
|
||||
identity: import("node:fs").BigIntStats;
|
||||
}) => Promise<void> = executor.verifyBoundCodexExecutable;
|
||||
export const verifyBoundCodexExecutable: (
|
||||
executable: {
|
||||
path: string;
|
||||
identity: import("node:fs").BigIntStats;
|
||||
sha256?: string;
|
||||
},
|
||||
signal?: AbortSignal,
|
||||
) => Promise<void> = executor.verifyBoundCodexExecutable;
|
||||
|
||||
export const bindCodexExecutable: (
|
||||
environment: NodeJS.ProcessEnv,
|
||||
cwd: string,
|
||||
signal?: AbortSignal,
|
||||
) => Promise<Parameters<typeof verifyBoundCodexExecutable>[0]> =
|
||||
executor.bindCodexExecutable;
|
||||
|
||||
@@ -21,7 +21,7 @@ const accountResult = ${JSON.stringify(accountResult)};
|
||||
const preflightMarkerPath = process.env.FAKE_CODEX_PREFLIGHT_MARKER ?? ${JSON.stringify(preflightMarkerPath)};
|
||||
const temporaryEnvironment = Object.fromEntries(['TEMP', 'TMP'].map(name => [name, process.env[name]]));
|
||||
if (process.argv.includes('app-server')) {
|
||||
const preflight = { executablePath: process.argv[1], argv: process.argv.slice(2), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, stateDirectory: process.env.CODEX_SECURITY_STATE_DIR, temporaryEnvironment, runnerTrackingId: process.env.RUNNER_TRACKING_ID, libraryPath: process.env["LD_LIBRARY_PATH"], cwd: process.cwd(), codexHome: process.env.CODEX_HOME, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerHeader: process.env.SYNTHETIC_HEADER_VALUE, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL'].map(name => [name, process.env[name]])), requests: [] };
|
||||
const preflight = { executablePath: process.argv[1], argv: process.argv.slice(2), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, stateDirectory: process.env.CODEX_SECURITY_STATE_DIR, temporaryEnvironment, runnerTrackingId: process.env.RUNNER_TRACKING_ID, libraryPath: process.env["LD_LIBRARY_PATH"], cwd: process.cwd(), codexHome: process.env.CODEX_HOME, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerHeader: process.env.SYNTHETIC_HEADER_VALUE, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL', 'GIT_DIFF_OPTS', 'GIT_GLOB_PATHSPECS', 'GIT_ICASE_PATHSPECS'].map(name => [name, process.env[name]])), requests: [] };
|
||||
writeFileSync(preflightMarkerPath, JSON.stringify(preflight));
|
||||
${jsonLineInputSource(` if (message.method === 'initialized') continue;
|
||||
if (message.method === 'config/read' || message.method === 'permissionProfile/list') {
|
||||
@@ -71,7 +71,7 @@ const profileContents = profileIndex === -1 ? undefined : readFileSync(join(proc
|
||||
const openaiAuthentication = stdin.includes('CAPTURE_SYNTHETIC_OPENAI_AUTH') ? { OPENAI_API_KEY: process.env.OPENAI_API_KEY, CODEX_API_KEY: process.env.CODEX_API_KEY } : undefined;
|
||||
const bedrockAuthentication = stdin.includes('CAPTURE_SYNTHETIC_BEDROCK_AUTH') ? Object.fromEntries(JSON.parse(process.env.FAKE_CODEX_BEDROCK_ENV_KEYS).map((name) => [name, process.env[name]])) : undefined;
|
||||
const codexConfig = stdin.includes('CAPTURE_SYNTHETIC_CODEX_CONFIG') ? readFileSync(join(process.env.CODEX_HOME, 'config.toml'), 'utf8') : undefined;
|
||||
const runtimeEnvironment = Object.fromEntries(['PATH', 'HOME', 'PYTHON', 'PYTHONUTF8', 'CODEX_MCP_NODE_PATH', 'CODEX_BROWSER_USE_NODE_PATH', 'CODEX_ELECTRON_RESOURCES_PATH', 'LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'DYLD_FALLBACK_LIBRARY_PATH', 'CODEX_SECURITY_STATE_DIR', 'RUNNER_TRACKING_ID'].map(name => [name, process.env[name]]));
|
||||
const runtimeEnvironment = Object.fromEntries(['PATH', 'HOME', 'PYTHON', 'PYTHONUTF8', 'PYTHONIOENCODING', 'CODEX_MCP_NODE_PATH', 'CODEX_BROWSER_USE_NODE_PATH', 'CODEX_ELECTRON_RESOURCES_PATH', 'LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'DYLD_FALLBACK_LIBRARY_PATH', 'CODEX_SECURITY_STATE_DIR', 'RUNNER_TRACKING_ID'].map(name => [name, process.env[name]]));
|
||||
const toolProbe = stdin.includes('CAPTURE_SYNTHETIC_RG') ? spawnSync('rg', ['--version'], { encoding: 'utf8' }) : undefined;
|
||||
if (toolProbe && toolProbe.status !== 0) throw toolProbe.error ?? new Error(toolProbe.stderr);
|
||||
const pythonProbe = stdin.includes('CAPTURE_SYNTHETIC_PYTHON') ? spawnSync(process.env.PYTHON, ['-I', '-c', 'import json,os,sys; print(json.dumps([sys.prefix,os.environ.get("LD_LIBRARY_PATH")]))'], { encoding: 'utf8' }) : undefined;
|
||||
@@ -80,7 +80,7 @@ const pythonRuntime = pythonProbe ? JSON.parse(pythonProbe.stdout) : undefined;
|
||||
const knowledgePath = stdin.includes('synthetic worker configuration fixture') ? process.env.CODEX_SECURITY_KNOWLEDGE_BASE : undefined;
|
||||
const knowledgeDocuments = knowledgePath === undefined ? undefined : Object.fromEntries(readdirSync(knowledgePath).map(name => [name, readFileSync(join(knowledgePath, name), 'utf8')]));
|
||||
const deepConfig = process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH ? readFileSync(process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, 'utf8') : undefined;
|
||||
writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ executablePath: process.argv[1], ...(scopeInput === undefined ? {} : { scopeInput }), argv: process.argv.slice(2), stdin, cwd: process.cwd(), knowledgePath, knowledgeDocuments, deepConfig, codexHome: process.env.CODEX_HOME, temporaryEnvironment, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL'].map(name => [name, process.env[name]])), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, deepConfigPath: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, python: process.env.PYTHON, mcpNodePath: process.env.CODEX_MCP_NODE_PATH, bundledTool: toolProbe?.stdout.trim(), pythonPrefix: pythonRuntime?.[0], pythonLibraryPath: pythonRuntime?.[1], runtimeEnvironment, codexConfig, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(profileContents === undefined ? {} : { profileContents }), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) }));
|
||||
writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ executablePath: process.argv[1], ...(scopeInput === undefined ? {} : { scopeInput }), argv: process.argv.slice(2), stdin, cwd: process.cwd(), knowledgePath, knowledgeDocuments, deepConfig, codexHome: process.env.CODEX_HOME, temporaryEnvironment, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL', 'GIT_DIFF_OPTS', 'GIT_GLOB_PATHSPECS', 'GIT_ICASE_PATHSPECS'].map(name => [name, process.env[name]])), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, deepConfigPath: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, python: process.env.PYTHON, mcpNodePath: process.env.CODEX_MCP_NODE_PATH, bundledTool: toolProbe?.stdout.trim(), pythonPrefix: pythonRuntime?.[0], pythonLibraryPath: pythonRuntime?.[1], runtimeEnvironment, codexConfig, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(profileContents === undefined ? {} : { profileContents }), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) }));
|
||||
if (stdin.includes('COMPLETE_THEN_HANG')) process.on('SIGTERM', () => { if (!stdin.includes('IGNORE_TERMINATION')) setTimeout(() => process.exit(0), 100); });
|
||||
|
||||
if (stdin.includes('THREAD_START_CONFIG_ERROR')) { console.error('Error: thread/start: thread/start failed: agents.max_threads cannot be set when features.multi_agent_v2 is enabled (code -32600)'); process.exit(1); }
|
||||
@@ -140,6 +140,9 @@ export function workerGitEnvironment(root: string) {
|
||||
),
|
||||
CODEX_SECURITY_GIT: path.join(root, "selected tools", "git"),
|
||||
GIT_SSH_COMMAND: "synthetic-ssh --fixture",
|
||||
GIT_DIFF_OPTS: "--unified=0",
|
||||
GIT_GLOB_PATHSPECS: "1",
|
||||
GIT_ICASE_PATHSPECS: "1",
|
||||
GIT_CONFIG_GLOBAL: path.join(root, "operator.gitconfig"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -236,6 +236,25 @@ test(async function testPrepareWithIgnoredTrackedFiles() {
|
||||
{ items: [{ path: "-generated/b.ts" }] },
|
||||
);
|
||||
|
||||
// Git pathspec defaults cannot override the literal scope selected by the helper.
|
||||
for (const mode of ["GIT_GLOB_PATHSPECS", "GIT_ICASE_PATHSPECS"]) {
|
||||
await execFile(
|
||||
process.execPath,
|
||||
[
|
||||
path.join(fixture.scan.pluginRoot, "mcp", "helpers.mjs"),
|
||||
"generate-in-scope-files",
|
||||
`--repo=${fixture.repoRoot}`,
|
||||
"--scope=-generated",
|
||||
`--out=${fixture.scanInventory}`,
|
||||
],
|
||||
{ env: { ...process.env, [mode]: "1" } },
|
||||
);
|
||||
assert.equal(
|
||||
await readFile(fixture.scanInventory, "utf8"),
|
||||
"-generated/a.ts\n-generated/b.ts\n",
|
||||
);
|
||||
}
|
||||
|
||||
const previous = await readFile(fixture.scanInventory);
|
||||
await fixture.writeRepositoryFile(".git/index", "invalid");
|
||||
await assert.rejects(
|
||||
|
||||
@@ -365,18 +365,33 @@ try {
|
||||
content,
|
||||
);
|
||||
|
||||
await client.close();
|
||||
client = await connect({
|
||||
CODEX_SECURITY_SCAN_ROOT: path.join(stateAlias, "missing", "scans"),
|
||||
});
|
||||
const relocated = await save({
|
||||
targetPath: repository,
|
||||
storage: "persistent",
|
||||
});
|
||||
assert.ok(
|
||||
relocated.directory.startsWith(
|
||||
path.join(stateRoot, "missing", "scans") + path.sep,
|
||||
),
|
||||
const rootName = process.platform === "win32" ? "scans" : "scans ";
|
||||
for (const [configured, expected] of [
|
||||
[
|
||||
path.join(stateAlias, "missing", rootName),
|
||||
path.join(stateRoot, "missing", rootName),
|
||||
],
|
||||
[
|
||||
` ${path.join(stateAlias, "padded", "scans")} `,
|
||||
path.join(stateRoot, "padded", "scans"),
|
||||
],
|
||||
]) {
|
||||
await client.close();
|
||||
client = await connect({ CODEX_SECURITY_SCAN_ROOT: configured });
|
||||
const relocated = await save({
|
||||
targetPath: repository,
|
||||
storage: "persistent",
|
||||
});
|
||||
assert.ok(relocated.directory.startsWith(expected + path.sep));
|
||||
}
|
||||
if (process.platform !== "win32")
|
||||
await assert.rejects(stat(path.join(stateRoot, "missing", "scans")), {
|
||||
code: "ENOENT",
|
||||
});
|
||||
assert.equal(
|
||||
(await read({ ...identity, storage: "persistent", path: relativePath }))
|
||||
.content,
|
||||
content,
|
||||
);
|
||||
|
||||
const linkedScanRoot = path.join(fixture, "linked-scans");
|
||||
|
||||
@@ -95,9 +95,9 @@ try {
|
||||
);
|
||||
await check(t, testWorkerTerminalEvents);
|
||||
await check(t, testCompletedWorkerSettlesWithoutWaitingForProcessExit);
|
||||
await check(t, testAbortPropagation);
|
||||
if (process.platform !== "win32") {
|
||||
await check(t, testStreamTerminationWithoutTerminalEventFails);
|
||||
await check(t, testAbortPropagation);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1446,6 +1446,7 @@ async function testWorkerRuntimeSettings() {
|
||||
];
|
||||
const saved = [
|
||||
"PYTHON",
|
||||
"PYTHONIOENCODING",
|
||||
"CODEX_SECURITY_PYTHON_COMMAND",
|
||||
"PATH",
|
||||
"HOME",
|
||||
@@ -1456,6 +1457,9 @@ async function testWorkerRuntimeSettings() {
|
||||
"CODEX_SECURITY_GIT",
|
||||
"GIT_SSH_COMMAND",
|
||||
"GIT_CONFIG_GLOBAL",
|
||||
"GIT_DIFF_OPTS",
|
||||
"GIT_GLOB_PATHSPECS",
|
||||
"GIT_ICASE_PATHSPECS",
|
||||
"CODEX_CLI_PATH",
|
||||
"CODEX_BROWSER_USE_NODE_PATH",
|
||||
"CODEX_HOME",
|
||||
@@ -1500,14 +1504,17 @@ async function testWorkerRuntimeSettings() {
|
||||
);
|
||||
const browserNode = path.join(fixture.root, "browser node");
|
||||
process.env.CODEX_BROWSER_USE_NODE_PATH = browserNode;
|
||||
const python = path.join(fixture.root, "selected venv", "bin", "python");
|
||||
const systemPython = process.platform === "win32" ? "python" : "python3";
|
||||
const python =
|
||||
configuration === "" && process.platform !== "win32"
|
||||
? systemPython
|
||||
: path.join(fixture.root, "selected venv", "bin", "python");
|
||||
const helperPython = path.join(
|
||||
fixture.root,
|
||||
"helper venv",
|
||||
"bin",
|
||||
"python",
|
||||
);
|
||||
const systemPython = process.platform === "win32" ? "python" : "python3";
|
||||
const workerPython = (index: number) =>
|
||||
index === 0 ? systemPython : `${helperPython}-${index} `;
|
||||
process.env.PYTHON = python;
|
||||
@@ -1655,8 +1662,13 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
|
||||
index === 0
|
||||
? path.join(fixture.root, `plugin-${index}`)
|
||||
: undefined;
|
||||
const sourceReadRoot = path.join(
|
||||
fixture.root,
|
||||
`private source [${index}]`,
|
||||
);
|
||||
const parentSandbox = {
|
||||
pluginReadRoot,
|
||||
sourceReadRoot,
|
||||
filesystemDenies: [
|
||||
...trustedParentSandboxWithDenials.filesystemDenies,
|
||||
...(nestedReceipts ? [] : [workerUsageDirectory]),
|
||||
@@ -1710,6 +1722,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
|
||||
};
|
||||
return {
|
||||
nativePaths,
|
||||
pythonIoEncoding: index % 2 === 0 ? "utf-16-le" : "utf-8-sig",
|
||||
knowledgePath: path.join(fixture.root, `knowledge-${index}`),
|
||||
knowledgeDocuments: {
|
||||
"1-architecture.md.txt": `Synthetic architecture for scan ${index}.`,
|
||||
@@ -1725,6 +1738,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
|
||||
...deniedWorkerPermissionProfile,
|
||||
filesystem: {
|
||||
...deniedWorkerPermissionProfile.filesystem,
|
||||
[sourceReadRoot]: { ".": "read" },
|
||||
...(pluginReadRoot === undefined
|
||||
? {}
|
||||
: { [pluginReadRoot]: { ".": "read" } }),
|
||||
@@ -2117,6 +2131,8 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
|
||||
]) {
|
||||
process.env[name] = path.join(fixture.root, `libraries-${index}`);
|
||||
}
|
||||
process.env.PYTHONIOENCODING =
|
||||
workerConfigurations[index].pythonIoEncoding;
|
||||
restoreEnv(
|
||||
"CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",
|
||||
workerConfigurations[index].workerConfigPath,
|
||||
@@ -2240,6 +2256,10 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
|
||||
workerLaunch.environment![name],
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
invocation.runtimeEnvironment.PYTHONIOENCODING,
|
||||
workerConfigurations[index].pythonIoEncoding,
|
||||
);
|
||||
assert.equal(
|
||||
invocation.knowledgePath,
|
||||
workerConfigurations[index].knowledgePath,
|
||||
|
||||
@@ -18,6 +18,35 @@ const pinnedReadOnly = {
|
||||
};
|
||||
|
||||
const stagedPlugin = path.resolve("bundled plugin [fixture]");
|
||||
const selectedSource = path.resolve("private source [fixture]");
|
||||
for (const access of ["read", "write"] as const) {
|
||||
assert.deepEqual(
|
||||
resolveDeepWorkerParentSandbox(
|
||||
restricted([
|
||||
rootRead,
|
||||
{ path: { type: "path", path: selectedSource }, access },
|
||||
{
|
||||
path: { type: "path", path: path.dirname(selectedSource) },
|
||||
access: "read",
|
||||
},
|
||||
{
|
||||
path: {
|
||||
type: "path",
|
||||
path: path.join(selectedSource, "config.toml"),
|
||||
},
|
||||
access: "deny",
|
||||
},
|
||||
]),
|
||||
stagedPlugin,
|
||||
selectedSource,
|
||||
),
|
||||
{
|
||||
filesystemDenies: [],
|
||||
literalFilesystemDenies: [path.join(selectedSource, "config.toml")],
|
||||
...(access === "read" ? { sourceReadRoot: selectedSource } : {}),
|
||||
},
|
||||
);
|
||||
}
|
||||
assert.deepEqual(
|
||||
resolveDeepWorkerParentSandbox(
|
||||
restricted([
|
||||
|
||||
@@ -56,6 +56,7 @@ async function testDeepScanStdioLifecycle() {
|
||||
const failedTargetPath = path.join(fixtureRoot, "failed-target");
|
||||
const expiredTargetPath = path.join(fixtureRoot, "expired-target");
|
||||
const stateDir = path.join(fixtureRoot, "state]");
|
||||
const scanRoot = path.join(await realpath(fixtureRoot), "scans ");
|
||||
const codexHome = path.join(fixtureRoot, "codex [home]");
|
||||
const installedPluginRoot = path.join(codexHome, "plugins", "installed");
|
||||
const runtimeConfigPath = path.join(fixtureRoot, "active-config.toml");
|
||||
@@ -192,7 +193,7 @@ service_tier = "ultrafast"
|
||||
CODEX_HOME: codexHome,
|
||||
CODEX_SECURITY_CONFIG_PATH: runtimeConfigPath,
|
||||
CODEX_SECURITY_PLUGIN_ROOT: pluginRoot,
|
||||
CODEX_SECURITY_SCAN_ROOT: path.join(fixtureRoot, "scans"),
|
||||
CODEX_SECURITY_SCAN_ROOT: scanRoot,
|
||||
CODEX_SECURITY_STATE_DIR: stateDir,
|
||||
PYTHON: pythonWrapperPath,
|
||||
CODEX_SECURITY_PYTHON_COMMAND: pythonWrapperPath,
|
||||
@@ -343,6 +344,7 @@ service_tier = "ultrafast"
|
||||
assert.match(startedWorker.stdin, /record_codex_security_scan_draft/);
|
||||
const startedState = await getDeepScan({ environment, scanId, threadId });
|
||||
assert.equal(startedState.config.maxTimeHours, 0.5);
|
||||
assert.ok(startedState.scanDir.startsWith(scanRoot + path.sep));
|
||||
await rm(projectConfigPath);
|
||||
const startedArtifactRoot = startedState.workers.find(
|
||||
(worker: PersistedDeepScanWorker) => worker.kind === "discovery",
|
||||
@@ -774,6 +776,7 @@ service_tier = "ultrafast"
|
||||
);
|
||||
const resumedScan = started.structuredContent.workspace.results;
|
||||
const resumedScanId = resumedScan.scanId;
|
||||
assert.ok(resumedScan.scanDir.startsWith(scanRoot + path.sep));
|
||||
await chmod(resumedScan.scanDir, 0o755);
|
||||
const handoffClaimToken = randomUUID();
|
||||
for (const [id, name, arguments_] of [
|
||||
|
||||
@@ -9,6 +9,7 @@ import { after, test } from "node:test";
|
||||
import { importModule, importSource } from "./import-module.ts";
|
||||
import { createTemporaryDirectories } from "./support/temporary-directories.ts";
|
||||
import { registerWorkerExecutableFirstLaunchTests } from "./windows_executable_first_launch_cases.ts";
|
||||
import { registerWorkerExecutableCancellationTests } from "./windows_executable_cancellation_cases.ts";
|
||||
|
||||
const packagedHelper = new URL(
|
||||
"../../../../sdk/typescript/_bundled_plugin/mcp/helpers.mjs",
|
||||
@@ -307,3 +308,4 @@ test(
|
||||
|
||||
// The Windows CI job runs this entry point directly and retains native TAP results.
|
||||
registerWorkerExecutableFirstLaunchTests();
|
||||
registerWorkerExecutableCancellationTests();
|
||||
|
||||
@@ -119,6 +119,7 @@ assert.deepEqual(
|
||||
"CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",
|
||||
"CODEX_SECURITY_SCAN_DIR",
|
||||
"CODEX_SECURITY_PLUGIN_ROOT",
|
||||
"CODEX_SECURITY_REPOSITORY",
|
||||
"CODEX_SECURITY_SCAN_ROOT",
|
||||
"CODEX_SECURITY_STATE_DIR",
|
||||
"CODEX_SECURITY_SURFACE",
|
||||
|
||||
@@ -177,8 +177,54 @@ try {
|
||||
);
|
||||
const resolvedPython =
|
||||
process.platform === "win32" ? process.execPath : `${fileCandidate} `;
|
||||
if (process.platform !== "win32")
|
||||
if (process.platform !== "win32") {
|
||||
await symlink(process.execPath, resolvedPython);
|
||||
assert.equal(
|
||||
await resolvePythonCommand({ configuredPython: resolvedPython }),
|
||||
resolvedPython,
|
||||
);
|
||||
assert.equal(
|
||||
await resolvePythonCommand({
|
||||
configuredPython: "./python3 ",
|
||||
workingDirectory: executableFixtureRoot,
|
||||
}),
|
||||
"./python3 ",
|
||||
);
|
||||
const paddedAbsolute = ` ${fileCandidate} `;
|
||||
const shadow = path.join(executableFixtureRoot, paddedAbsolute);
|
||||
await mkdir(path.dirname(shadow), { recursive: true });
|
||||
await symlink(process.execPath, shadow);
|
||||
assert.equal(
|
||||
await resolvePythonCommand({
|
||||
configuredPython: paddedAbsolute,
|
||||
workingDirectory: executableFixtureRoot,
|
||||
}),
|
||||
fileCandidate,
|
||||
);
|
||||
const trusted = path.join(executableFixtureRoot, "tools");
|
||||
await mkdir(trusted);
|
||||
await writeFile(
|
||||
path.join(trusted, "python3"),
|
||||
"#!/bin/sh\n/bin/cat >/dev/null\nprintf trusted",
|
||||
{
|
||||
mode: 0o700,
|
||||
},
|
||||
);
|
||||
const previousPath = process.env.PATH;
|
||||
try {
|
||||
process.env.PATH = [trusted, executableFixtureRoot].join(path.delimiter);
|
||||
const command = await resolvePythonCommand({
|
||||
configuredPython: "python3 ",
|
||||
});
|
||||
assert.equal(
|
||||
await runPythonWithInput(command, [], "", "fixture"),
|
||||
"trusted",
|
||||
);
|
||||
} finally {
|
||||
if (previousPath === undefined) delete process.env.PATH;
|
||||
else process.env.PATH = previousPath;
|
||||
}
|
||||
}
|
||||
process.env.PYTHON = ` ${fileCandidate} `;
|
||||
process.env.CODEX_SECURITY_PYTHON_COMMAND = resolvedPython;
|
||||
assert.equal(await resolvePythonCommand(), resolvedPython);
|
||||
|
||||
@@ -97,7 +97,10 @@ try {
|
||||
const diagnostic = direct.stderr.trim().split("\n").at(-1)!;
|
||||
assert.match(diagnostic, /FileExistsError/);
|
||||
assert.equal(wrapped.stderr.trim().split("\n").at(-1), diagnostic);
|
||||
const failure = await openWorkspace(environment);
|
||||
const failure = await openWorkspace({
|
||||
...environment,
|
||||
PYTHONIOENCODING: "utf-16-le",
|
||||
});
|
||||
assert.equal(failure.error, undefined);
|
||||
assert.equal(failure.result.isError, true);
|
||||
assert.ok(
|
||||
@@ -111,7 +114,12 @@ try {
|
||||
...environment,
|
||||
CODEX_SECURITY_STATE_DIR: explicitState,
|
||||
};
|
||||
assertNoError(await openWorkspace(explicitEnvironment));
|
||||
assertNoError(
|
||||
await openWorkspace({
|
||||
...explicitEnvironment,
|
||||
PYTHONIOENCODING: "utf-8-sig",
|
||||
}),
|
||||
);
|
||||
assert.equal(
|
||||
(await stat(path.join(explicitState, "workbench.sqlite3"))).isFile(),
|
||||
true,
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import assert from "node:assert/strict";
|
||||
import fs, { promises } from "node:fs";
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { syncBuiltinESMExports } from "node:module";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { temporaryDirectory } from "./support/temporary-directories.ts";
|
||||
import {
|
||||
bindCodexExecutable,
|
||||
verifyBoundCodexExecutable,
|
||||
} from "./support/deep-scan-executor-module.ts";
|
||||
|
||||
export function registerWorkerExecutableCancellationTests(): void {
|
||||
for (const phase of ["binding", "verification"]) {
|
||||
test(`the worker pin preserves cancellation before ${phase}`, async (t) => {
|
||||
const root = await temporaryDirectory("worker-cancelled-pin-", true);
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const executable = path.join(root, "content-fixture.exe");
|
||||
await writeFile(executable, "fixture original bytes\n");
|
||||
const bound = await bindCodexExecutable(
|
||||
{ CODEX_CLI_PATH: executable },
|
||||
root,
|
||||
);
|
||||
const controller = new AbortController();
|
||||
const reason = { message: "synthetic caller cancellation", phase };
|
||||
controller.abort(reason);
|
||||
const inspect = t.mock.method(promises, "stat", () => {
|
||||
throw new Error("An aborted pin operation must not inspect the file.");
|
||||
});
|
||||
await assert.rejects(
|
||||
phase === "binding"
|
||||
? bindCodexExecutable(
|
||||
{ CODEX_CLI_PATH: executable },
|
||||
root,
|
||||
controller.signal,
|
||||
)
|
||||
: verifyBoundCodexExecutable(bound, controller.signal),
|
||||
(error) => error === reason,
|
||||
);
|
||||
assert.equal(inspect.mock.callCount(), 0);
|
||||
});
|
||||
}
|
||||
|
||||
test(
|
||||
"the worker pin cancels an active binding content stream",
|
||||
{
|
||||
skip: process.platform !== "win32",
|
||||
},
|
||||
async (t) => {
|
||||
const root = await temporaryDirectory("worker-cancelled-stream-", true);
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const executable = path.join(root, "content-fixture.exe");
|
||||
await writeFile(executable, "fixture original bytes\n".repeat(8192));
|
||||
const controller = new AbortController();
|
||||
const reason = new Error("synthetic cancellation during binding read");
|
||||
const originalRead = fs.createReadStream;
|
||||
let observed: fs.ReadStream | undefined;
|
||||
const reading = t.mock.method(
|
||||
fs,
|
||||
"createReadStream",
|
||||
(...args: Parameters<typeof fs.createReadStream>) => {
|
||||
const stream = originalRead(...args);
|
||||
if (args[0] === executable) {
|
||||
observed = stream;
|
||||
stream.once("data", () => controller.abort(reason));
|
||||
}
|
||||
return stream;
|
||||
},
|
||||
);
|
||||
syncBuiltinESMExports();
|
||||
try {
|
||||
await assert.rejects(
|
||||
bindCodexExecutable(
|
||||
{ CODEX_CLI_PATH: executable },
|
||||
root,
|
||||
controller.signal,
|
||||
),
|
||||
(error) => error === reason,
|
||||
);
|
||||
} finally {
|
||||
reading.mock.restore();
|
||||
syncBuiltinESMExports();
|
||||
}
|
||||
assert.ok(observed);
|
||||
if (!observed.closed)
|
||||
await new Promise<void>((resolve) => observed!.once("close", resolve));
|
||||
assert.equal(observed.destroyed, true);
|
||||
assert.equal(observed.closed, true);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
"the worker pin cancels metadata churn with the caller's reason",
|
||||
{
|
||||
skip: process.platform !== "win32",
|
||||
},
|
||||
async (t) => {
|
||||
const root = await temporaryDirectory("worker-cancelled-churn-", true);
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const executable = path.join(root, "content-fixture.exe");
|
||||
await writeFile(executable, "fixture original bytes\n");
|
||||
const bound = await bindCodexExecutable(
|
||||
{ CODEX_CLI_PATH: executable },
|
||||
root,
|
||||
);
|
||||
const controller = new AbortController();
|
||||
const reason = new Error("synthetic cancellation during metadata churn");
|
||||
const originalStat = promises.stat;
|
||||
let observations = 0;
|
||||
t.mock.method(
|
||||
promises,
|
||||
"stat",
|
||||
async (...args: Parameters<typeof promises.stat>) => {
|
||||
if (args[0] !== executable) return originalStat(...args);
|
||||
observations++;
|
||||
if (observations === 3) controller.abort(reason);
|
||||
const identity = await originalStat(args[0], { bigint: true });
|
||||
// Keep the real file and content stream while deterministically advancing
|
||||
// the metadata observation, independent of filesystem chmod timestamps.
|
||||
return Object.assign(identity, {
|
||||
ctimeNs: bound.identity.ctimeNs + BigInt(observations),
|
||||
});
|
||||
},
|
||||
);
|
||||
await assert.rejects(
|
||||
verifyBoundCodexExecutable(bound, controller.signal),
|
||||
(error) => error === reason,
|
||||
);
|
||||
assert.equal(observations, 3);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,16 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { copyFile, rm, stat, utimes, writeFile } from "node:fs/promises";
|
||||
import { createReadStream, promises as fs } from "node:fs";
|
||||
import {
|
||||
copyFile,
|
||||
mkdir,
|
||||
rename,
|
||||
rm,
|
||||
stat,
|
||||
utimes,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
@@ -21,49 +29,47 @@ export function registerWorkerExecutableFirstLaunchTests(): void {
|
||||
"the first Windows version launch preserves the executable pin",
|
||||
{ skip: process.platform !== "win32" },
|
||||
async (t) => {
|
||||
const { verifyBoundCodexExecutable } =
|
||||
const { bindCodexExecutable, verifyBoundCodexExecutable } =
|
||||
await import("./support/deep-scan-executor-module.ts");
|
||||
const root = await temporaryDirectory("worker-first-launch-", true);
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const executable = path.join(root, "version-fixture.exe");
|
||||
await copyFile(process.execPath, executable);
|
||||
const beforeDigest = await digest(executable);
|
||||
const identity = await stat(executable, { bigint: true });
|
||||
await verifyBoundCodexExecutable({ path: executable, identity });
|
||||
const { stdout } = await promisify(execFile)(
|
||||
executablePathForSpawn(executable),
|
||||
["--version"],
|
||||
{
|
||||
windowsHide: true,
|
||||
},
|
||||
);
|
||||
assert.equal(stdout.trim(), process.version);
|
||||
const after = await stat(executable, { bigint: true });
|
||||
assert.equal(await digest(executable), beforeDigest);
|
||||
assert.equal(after.dev, identity.dev);
|
||||
assert.equal(after.ino, identity.ino);
|
||||
assert.equal(after.size, identity.size);
|
||||
assert.equal(after.mtimeNs, identity.mtimeNs);
|
||||
try {
|
||||
await verifyBoundCodexExecutable({ path: executable, identity });
|
||||
} catch (error) {
|
||||
if (
|
||||
after.ctimeNs !== identity.ctimeNs &&
|
||||
error instanceof Error &&
|
||||
error.name === "DeepScanNonRetryableError" &&
|
||||
error.cause === undefined
|
||||
) {
|
||||
t.todo(
|
||||
"The current worker pin rejects an ordinary launch when only Windows change time advances.",
|
||||
for (const name of [
|
||||
"version-fixture.exe",
|
||||
path.join(...Array(10).fill("nested executable directory"), "node.exe"),
|
||||
]) {
|
||||
const executable = path.join(root, name);
|
||||
await mkdir(path.dirname(executable), { recursive: true });
|
||||
await copyFile(process.execPath, executable);
|
||||
const beforeDigest = await digest(executable);
|
||||
const bound = await bindCodexExecutable(
|
||||
{ CODEX_CLI_PATH: executable },
|
||||
root,
|
||||
);
|
||||
const { identity } = bound;
|
||||
await verifyBoundCodexExecutable(bound);
|
||||
for (let launch = 0; launch < 2; launch++) {
|
||||
const { stdout } = await promisify(execFile)(
|
||||
executablePathForSpawn(executable),
|
||||
["--version"],
|
||||
{
|
||||
windowsHide: true,
|
||||
},
|
||||
);
|
||||
assert.equal(stdout.trim(), process.version);
|
||||
const after = await stat(executable, { bigint: true });
|
||||
assert.equal(await digest(executable), beforeDigest);
|
||||
assert.equal(after.dev, identity.dev);
|
||||
assert.equal(after.ino, identity.ino);
|
||||
assert.equal(after.size, identity.size);
|
||||
assert.equal(after.mtimeNs, identity.mtimeNs);
|
||||
await verifyBoundCodexExecutable(bound);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("the worker pin rejects a changed synthetic file of the same size", async (t) => {
|
||||
const { verifyBoundCodexExecutable } =
|
||||
const { bindCodexExecutable, verifyBoundCodexExecutable } =
|
||||
await import("./support/deep-scan-executor-module.ts");
|
||||
const root = await temporaryDirectory("worker-changed-pin-", true);
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
@@ -72,8 +78,12 @@ export function registerWorkerExecutableFirstLaunchTests(): void {
|
||||
const fixedTime = new Date("2025-01-01T00:00:00Z");
|
||||
await writeFile(executable, "fixture revision A\n");
|
||||
await utimes(executable, fixedTime, fixedTime);
|
||||
const identity = await stat(executable, { bigint: true });
|
||||
await verifyBoundCodexExecutable({ path: executable, identity });
|
||||
const bound = await bindCodexExecutable(
|
||||
{ CODEX_CLI_PATH: executable },
|
||||
root,
|
||||
);
|
||||
const { identity } = bound;
|
||||
await verifyBoundCodexExecutable(bound);
|
||||
// Retry a real equal-length revision on a later tick if the first write is too fast.
|
||||
for (const [wait, revision] of [
|
||||
[0, "B"],
|
||||
@@ -86,10 +96,9 @@ export function registerWorkerExecutableFirstLaunchTests(): void {
|
||||
assert.equal(updated.size, identity.size);
|
||||
assert.equal(updated.mtimeNs, identity.mtimeNs);
|
||||
if (updated.ctimeNs !== identity.ctimeNs) {
|
||||
await assert.rejects(
|
||||
verifyBoundCodexExecutable({ path: executable, identity }),
|
||||
{ name: "DeepScanNonRetryableError" },
|
||||
);
|
||||
await assert.rejects(verifyBoundCodexExecutable(bound), {
|
||||
name: "DeepScanNonRetryableError",
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -97,4 +106,150 @@ export function registerWorkerExecutableFirstLaunchTests(): void {
|
||||
"The fixture filesystem reported the same change time across two separately timed content revisions.",
|
||||
);
|
||||
});
|
||||
|
||||
test("the worker pin rejects a same-content file replacement", async (t) => {
|
||||
const { bindCodexExecutable, verifyBoundCodexExecutable } =
|
||||
await import("./support/deep-scan-executor-module.ts");
|
||||
const root = await temporaryDirectory("worker-replaced-pin-", true);
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const executable = path.join(root, "content-fixture.exe");
|
||||
const replacement = path.join(root, "replacement.exe");
|
||||
const fixedTime = new Date("2025-01-01T00:00:00Z");
|
||||
await writeFile(executable, "fixture original bytes\n");
|
||||
await utimes(executable, fixedTime, fixedTime);
|
||||
const bound = await bindCodexExecutable(
|
||||
{ CODEX_CLI_PATH: executable },
|
||||
root,
|
||||
);
|
||||
await copyFile(executable, replacement);
|
||||
await utimes(replacement, fixedTime, fixedTime);
|
||||
assert.equal(await digest(replacement), await digest(executable));
|
||||
await rename(replacement, executable);
|
||||
const replaced = await stat(executable, { bigint: true });
|
||||
assert.notEqual(replaced.ino, bound.identity.ino);
|
||||
assert.equal(replaced.size, bound.identity.size);
|
||||
assert.equal(replaced.mtimeNs, bound.identity.mtimeNs);
|
||||
await assert.rejects(verifyBoundCodexExecutable(bound), {
|
||||
name: "DeepScanNonRetryableError",
|
||||
});
|
||||
});
|
||||
|
||||
test("the worker pin rejects a changed modification time with identical content", async (t) => {
|
||||
const { bindCodexExecutable, verifyBoundCodexExecutable } =
|
||||
await import("./support/deep-scan-executor-module.ts");
|
||||
const root = await temporaryDirectory("worker-modified-pin-", true);
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const executable = path.join(root, "content-fixture.exe");
|
||||
await writeFile(executable, "fixture original bytes\n");
|
||||
const bound = await bindCodexExecutable(
|
||||
{ CODEX_CLI_PATH: executable },
|
||||
root,
|
||||
);
|
||||
const beforeDigest = await digest(executable);
|
||||
const changedTime = new Date("2025-01-01T00:00:00Z");
|
||||
await utimes(executable, changedTime, changedTime);
|
||||
assert.equal(await digest(executable), beforeDigest);
|
||||
assert.notEqual(
|
||||
(await stat(executable, { bigint: true })).mtimeNs,
|
||||
bound.identity.mtimeNs,
|
||||
);
|
||||
await assert.rejects(verifyBoundCodexExecutable(bound), {
|
||||
name: "DeepScanNonRetryableError",
|
||||
});
|
||||
});
|
||||
|
||||
for (const phase of ["binding", "verification"]) {
|
||||
test(
|
||||
`the worker pin rejects a revision during content ${phase}`,
|
||||
{
|
||||
skip: process.platform !== "win32",
|
||||
},
|
||||
async (t) => {
|
||||
const { bindCodexExecutable, verifyBoundCodexExecutable } =
|
||||
await import("./support/deep-scan-executor-module.ts");
|
||||
const root = await temporaryDirectory("worker-streamed-pin-", true);
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const executable = path.join(root, "content-fixture.exe");
|
||||
const fixedTime = new Date("2025-01-01T00:00:00Z");
|
||||
await writeFile(executable, "fixture revision A\n");
|
||||
await utimes(executable, fixedTime, fixedTime);
|
||||
const bind = () =>
|
||||
bindCodexExecutable({ CODEX_CLI_PATH: executable }, root);
|
||||
const bound = phase === "verification" ? await bind() : undefined;
|
||||
const originalStat = fs.stat;
|
||||
let observations = 0;
|
||||
let revised = false;
|
||||
let changeTime = bound?.identity.ctimeNs;
|
||||
t.mock.method(
|
||||
fs,
|
||||
"stat",
|
||||
async (...args: Parameters<typeof fs.stat>) => {
|
||||
if (args[0] !== executable) return originalStat(...args);
|
||||
observations++;
|
||||
if (observations === 2) {
|
||||
await writeFile(executable, "fixture revision B\n");
|
||||
await utimes(executable, fixedTime, fixedTime);
|
||||
revised = true;
|
||||
}
|
||||
const identity = await originalStat(args[0], { bigint: true });
|
||||
// chmod does not advance change time on every Windows filesystem.
|
||||
// Inject only that observation while reading and revising real bytes.
|
||||
changeTime ??= identity.ctimeNs;
|
||||
return Object.assign(identity, {
|
||||
ctimeNs: changeTime + BigInt(observations),
|
||||
});
|
||||
},
|
||||
);
|
||||
await assert.rejects(
|
||||
bound ? verifyBoundCodexExecutable(bound) : bind(),
|
||||
{
|
||||
name: "DeepScanNonRetryableError",
|
||||
},
|
||||
);
|
||||
assert.equal(revised, true);
|
||||
assert.equal(observations, phase === "verification" ? 3 : 2);
|
||||
assert.equal(
|
||||
await fs.readFile(executable, "utf8"),
|
||||
"fixture revision B\n",
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test(
|
||||
"the worker pin accepts a metadata-only change during content verification",
|
||||
{
|
||||
skip: process.platform !== "win32",
|
||||
},
|
||||
async (t) => {
|
||||
const { bindCodexExecutable, verifyBoundCodexExecutable } =
|
||||
await import("./support/deep-scan-executor-module.ts");
|
||||
const root = await temporaryDirectory("worker-metadata-pin-", true);
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const executable = path.join(root, "content-fixture.exe");
|
||||
await writeFile(executable, "fixture original bytes\n");
|
||||
const bound = await bindCodexExecutable(
|
||||
{ CODEX_CLI_PATH: executable },
|
||||
root,
|
||||
);
|
||||
const beforeDigest = await digest(executable);
|
||||
const originalStat = fs.stat;
|
||||
let observations = 0;
|
||||
let changedMetadata = false;
|
||||
t.mock.method(fs, "stat", async (...args: Parameters<typeof fs.stat>) => {
|
||||
if (args[0] !== executable) return originalStat(...args);
|
||||
observations++;
|
||||
if (observations === 2) changedMetadata = true;
|
||||
const identity = await originalStat(args[0], { bigint: true });
|
||||
// Report one metadata transition during the real content read, then stability.
|
||||
return Object.assign(identity, {
|
||||
ctimeNs: bound.identity.ctimeNs + BigInt(Math.min(observations, 2)),
|
||||
});
|
||||
});
|
||||
await verifyBoundCodexExecutable(bound);
|
||||
assert.equal(changedMetadata, true);
|
||||
assert.equal(observations, 3);
|
||||
assert.equal(await digest(executable), beforeDigest);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import {
|
||||
chmodSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
realpathSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
unlinkSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -65,6 +67,20 @@ export function scanReadProof(): Record<string, boolean> {
|
||||
renameSync(scan, moved);
|
||||
renameSync(moved, scan);
|
||||
}
|
||||
if (process.platform === "linux") {
|
||||
chmodSync(artifacts, 0o100);
|
||||
chmodSync(scan, 0o100);
|
||||
try {
|
||||
const searchable = openRoot(scan);
|
||||
assert.deepEqual(
|
||||
chunks(openFile(searchable, "artifacts/receipt.json")),
|
||||
payload,
|
||||
);
|
||||
} finally {
|
||||
chmodSync(scan, 0o700);
|
||||
chmodSync(artifacts, 0o700);
|
||||
}
|
||||
}
|
||||
const root = openRoot(scan);
|
||||
assert.deepEqual(chunks(openFile(root, "artifacts/receipt.json")), payload);
|
||||
assert.equal(root.openFile("missing.json"), null);
|
||||
@@ -97,7 +113,7 @@ export function scanReadProof(): Record<string, boolean> {
|
||||
assert.deepEqual(chunks(held), payload);
|
||||
assert.throws(() => root.openFile("artifacts/receipt.json"));
|
||||
held.close();
|
||||
rmSync(artifacts);
|
||||
unlinkSync(artifacts);
|
||||
renameSync(moved, artifacts);
|
||||
}
|
||||
assert.throws(() => held.read(1), /closed/i);
|
||||
|
||||
@@ -11,6 +11,12 @@ use std::{
|
||||
path::PathBuf,
|
||||
};
|
||||
|
||||
// These descriptors anchor named lookups and metadata checks without listing the directory.
|
||||
#[cfg(target_os = "linux")]
|
||||
const DIRECTORY_ACCESS: i32 = libc::O_PATH;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
const DIRECTORY_ACCESS: i32 = libc::O_RDONLY;
|
||||
|
||||
pub(crate) struct ScanReadRootBackend {
|
||||
path: PathBuf,
|
||||
directory: Option<File>,
|
||||
@@ -38,6 +44,52 @@ fn open_at(parent: RawFd, path: &OsStr, flags: i32) -> io::Result<File> {
|
||||
Ok(unsafe { File::from_raw_fd(descriptor) })
|
||||
}
|
||||
|
||||
// Retry a deep lookup from the held root when keeping every ancestor open exhausted
|
||||
// the process descriptor limit. openat2 enforces the boundary and rejects symlinks
|
||||
// throughout the parent path in a single kernel lookup.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn open_beneath_root(root: &File, relative_path: &str) -> Result<File, OpenError> {
|
||||
let (parent_path, name) = relative_path
|
||||
.rsplit_once('/')
|
||||
.unwrap_or((".", relative_path));
|
||||
let parent_path = CString::new(parent_path).map_err(|error| OpenError::Parent(error.into()))?;
|
||||
// The kernel requires unused and future open_how fields to be zero.
|
||||
let mut how: libc::open_how = unsafe { std::mem::zeroed() };
|
||||
how.flags = (libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC) as u64;
|
||||
how.resolve = libc::RESOLVE_BENEATH | libc::RESOLVE_NO_SYMLINKS;
|
||||
let open_parent = || -> io::Result<File> {
|
||||
let descriptor = unsafe {
|
||||
libc::syscall(
|
||||
libc::SYS_openat2,
|
||||
root.as_raw_fd(),
|
||||
parent_path.as_ptr(),
|
||||
&how,
|
||||
std::mem::size_of_val(&how),
|
||||
)
|
||||
};
|
||||
if descriptor < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(unsafe { File::from_raw_fd(descriptor as RawFd) })
|
||||
};
|
||||
|
||||
let parent = open_parent().map_err(OpenError::Parent)?;
|
||||
let file = open_at(
|
||||
parent.as_raw_fd(),
|
||||
OsStr::new(name),
|
||||
libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK,
|
||||
)
|
||||
.map_err(OpenError::Leaf)?;
|
||||
let verify = || {
|
||||
if !same_file(&parent.metadata()?, &open_parent()?.metadata()?) {
|
||||
return Err(io::Error::other("Scan path changed while opening the file"));
|
||||
}
|
||||
verify_components(&parent, &[name], &[], &file)
|
||||
};
|
||||
verify().map_err(OpenError::Verify)?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
// Check the names against their held descriptors before returning the opened file.
|
||||
fn verify_components(
|
||||
root: &File,
|
||||
@@ -73,6 +125,58 @@ fn verify_components(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum OpenError {
|
||||
Parent(io::Error),
|
||||
Leaf(io::Error),
|
||||
Verify(io::Error),
|
||||
}
|
||||
|
||||
fn open_by_components(root: &File, parts: &[&str]) -> Result<File, OpenError> {
|
||||
let mut directories = Vec::new();
|
||||
let mut parent = root.as_raw_fd();
|
||||
for part in &parts[..parts.len() - 1] {
|
||||
let directory = open_at(
|
||||
parent,
|
||||
OsStr::new(part),
|
||||
DIRECTORY_ACCESS | libc::O_DIRECTORY | libc::O_NOFOLLOW,
|
||||
)
|
||||
.map_err(OpenError::Parent)?;
|
||||
parent = directory.as_raw_fd();
|
||||
directories.push(directory);
|
||||
}
|
||||
let file = open_at(
|
||||
parent,
|
||||
OsStr::new(parts[parts.len() - 1]),
|
||||
libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK,
|
||||
)
|
||||
.map_err(OpenError::Leaf)?;
|
||||
verify_components(root, parts, &directories, &file).map_err(OpenError::Verify)?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
fn open_relative_file(root: &File, parts: &[&str]) -> Result<File, OpenError> {
|
||||
let result = open_by_components(root, parts);
|
||||
#[cfg(target_os = "linux")]
|
||||
if matches!(
|
||||
&result,
|
||||
Err(OpenError::Parent(error) | OpenError::Leaf(error))
|
||||
if error.raw_os_error() == Some(libc::EMFILE)
|
||||
) {
|
||||
// The unsuccessful walk has released its descriptors. Preserve its error
|
||||
// when the kernel or sandbox cannot perform the bounded lookup.
|
||||
let retry = open_beneath_root(root, &parts.join("/"));
|
||||
if !matches!(
|
||||
&retry,
|
||||
Err(OpenError::Parent(error))
|
||||
if matches!(error.raw_os_error(), Some(libc::ENOSYS | libc::EPERM | libc::ENAMETOOLONG))
|
||||
) {
|
||||
return retry;
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
impl ScanReadRootBackend {
|
||||
pub(crate) fn open(path: Buffer) -> napi::Result<Self> {
|
||||
let path = PathBuf::from(OsStr::from_bytes(path.as_ref()));
|
||||
@@ -93,7 +197,7 @@ impl ScanReadRootBackend {
|
||||
let directory = open_at(
|
||||
libc::AT_FDCWD,
|
||||
path.as_os_str(),
|
||||
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW,
|
||||
DIRECTORY_ACCESS | libc::O_DIRECTORY | libc::O_NOFOLLOW,
|
||||
)
|
||||
.map_err(|error| failure("Cannot open scan directory", error))?;
|
||||
let opened = directory
|
||||
@@ -133,32 +237,23 @@ impl ScanReadRootBackend {
|
||||
.directory
|
||||
.as_ref()
|
||||
.ok_or_else(|| napi::Error::from_reason("Scan directory is closed"))?;
|
||||
let mut directories = Vec::new();
|
||||
let mut parent = root.as_raw_fd();
|
||||
for part in &parts[..parts.len() - 1] {
|
||||
let directory = match open_at(
|
||||
parent,
|
||||
OsStr::new(part),
|
||||
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW,
|
||||
) {
|
||||
Ok(directory) => directory,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(failure("Cannot open scan file parent", error)),
|
||||
};
|
||||
parent = directory.as_raw_fd();
|
||||
directories.push(directory);
|
||||
}
|
||||
let file = match open_at(
|
||||
parent,
|
||||
OsStr::new(parts[parts.len() - 1]),
|
||||
libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK,
|
||||
) {
|
||||
let file = match open_relative_file(root, &parts) {
|
||||
Ok(file) => file,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) if error.raw_os_error() == Some(libc::EACCES) => {
|
||||
return Err(crate::scan_read::access_denied(env, error))
|
||||
Err(OpenError::Parent(error) | OpenError::Leaf(error))
|
||||
if error.kind() == io::ErrorKind::NotFound =>
|
||||
{
|
||||
return Ok(None)
|
||||
}
|
||||
Err(OpenError::Parent(error)) => {
|
||||
return Err(failure("Cannot open scan file parent", error))
|
||||
}
|
||||
Err(OpenError::Leaf(error)) if error.raw_os_error() == Some(libc::EACCES) => {
|
||||
return Err(crate::scan_read::access_denied(env, error));
|
||||
}
|
||||
Err(OpenError::Leaf(error)) => return Err(failure("Cannot open scan file", error)),
|
||||
Err(OpenError::Verify(error)) => {
|
||||
return Err(failure("Cannot verify opened scan file", error))
|
||||
}
|
||||
Err(error) => return Err(failure("Cannot open scan file", error)),
|
||||
};
|
||||
if !file
|
||||
.metadata()
|
||||
@@ -169,8 +264,6 @@ impl ScanReadRootBackend {
|
||||
"Expected a regular non-symlink scan file",
|
||||
));
|
||||
}
|
||||
verify_components(root, &parts, &directories, &file)
|
||||
.map_err(|error| failure("Cannot verify opened scan file", error))?;
|
||||
self.verify()?;
|
||||
Ok(Some(ScanReadFileBackend { file }))
|
||||
}
|
||||
@@ -210,6 +303,88 @@ impl ScanReadFileBackend {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn reads_deep_artifacts_with_a_low_descriptor_limit() -> io::Result<()> {
|
||||
use std::{os::unix::process::CommandExt, process::Command};
|
||||
|
||||
const CHILD_ROOT: &str = "CODEX_SECURITY_TEST_FD_LIMIT_ROOT";
|
||||
let mut parts = vec!["tier"; 48];
|
||||
parts.push("receipt");
|
||||
if let Some(path) = std::env::var_os(CHILD_ROOT) {
|
||||
let root = File::open(path)?;
|
||||
assert!(matches!(
|
||||
open_by_components(&root, &parts),
|
||||
Err(OpenError::Parent(error) | OpenError::Leaf(error))
|
||||
if error.raw_os_error() == Some(libc::EMFILE)
|
||||
));
|
||||
let mut file = open_relative_file(&root, &parts).unwrap();
|
||||
let mut value = String::new();
|
||||
file.read_to_string(&mut value)?;
|
||||
assert_eq!(value, "sealed");
|
||||
*parts.last_mut().unwrap() = "missing";
|
||||
assert!(matches!(
|
||||
open_relative_file(&root, &parts),
|
||||
Err(OpenError::Leaf(error)) if error.kind() == io::ErrorKind::NotFound
|
||||
));
|
||||
parts.pop();
|
||||
parts.extend(["link", "receipt"]);
|
||||
assert!(open_relative_file(&root, &parts).is_err());
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let fixture =
|
||||
std::env::temp_dir().join(format!("codex-security-fd-limit-{}", std::process::id()));
|
||||
fs::create_dir(&fixture)?;
|
||||
let result = (|| {
|
||||
let scan = fixture.join("scan");
|
||||
let path = scan.join(parts.join("/"));
|
||||
let parent = path.parent().unwrap();
|
||||
fs::create_dir_all(parent)?;
|
||||
fs::write(&path, "sealed")?;
|
||||
fs::write(fixture.join("receipt"), "outside")?;
|
||||
std::os::unix::fs::symlink(&fixture, parent.join("link"))?;
|
||||
let root = File::open(&scan)?;
|
||||
// Older kernels and sandboxes can disable openat2 entirely.
|
||||
match open_beneath_root(&root, &parts.join("/")) {
|
||||
Err(OpenError::Parent(error))
|
||||
if matches!(error.raw_os_error(), Some(libc::ENOSYS | libc::EPERM)) =>
|
||||
{
|
||||
return Ok(())
|
||||
}
|
||||
other => drop(other.unwrap()),
|
||||
}
|
||||
let mut child = Command::new(std::env::current_exe()?);
|
||||
child.args([
|
||||
"--exact",
|
||||
"scan_read_unix::tests::reads_deep_artifacts_with_a_low_descriptor_limit",
|
||||
]);
|
||||
child.env(CHILD_ROOT, scan);
|
||||
// Only the isolated test child receives the lower process limit.
|
||||
unsafe {
|
||||
child.pre_exec(|| {
|
||||
let limit = libc::rlimit {
|
||||
rlim_cur: 32,
|
||||
rlim_max: 32,
|
||||
};
|
||||
if libc::setrlimit(libc::RLIMIT_NOFILE, &limit) != 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let output = child.output()?;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
);
|
||||
Ok(())
|
||||
})();
|
||||
fs::remove_dir_all(fixture)?;
|
||||
result
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verifies_every_opened_component_including_the_leaf() -> io::Result<()> {
|
||||
let scan =
|
||||
|
||||
@@ -22,7 +22,7 @@ Select `storage` explicitly:
|
||||
- `persistent`: retained documents/evidence under the authoritative scan directory or standalone collection. The default root is `$CODEX_SECURITY_STATE_DIR/scans`, or `$CODEX_HOME/state/plugins/codex-security/scans` when no state override is set; `CODEX_HOME` defaults to `~/.codex`. The existing `CODEX_SECURITY_SCAN_ROOT` override still takes precedence for plugin-created output. The workbench state directory must be writable; set `CODEX_SECURITY_STATE_DIR` explicitly on hosts with an unwritable default. Preserve an existing scan's saved path, including older temporary paths.
|
||||
- `temporary`: disposable staging and execution output in a context-specific OS temporary directory. Standalone temporary saves and reads do not create or require the persistent collection. It is not part of the completed result and must not be referenced from canonical findings or coverage. It can disappear independently of retained files.
|
||||
|
||||
Relative storage overrides resolve from the plugin directory, matching the workbench, regardless of the MCP launch directory.
|
||||
Relative storage overrides resolve from the plugin directory, matching the workbench, regardless of the MCP launch directory. On POSIX, `CODEX_SECURITY_SCAN_ROOT` preserves trailing whitespace. A value with leading padding is trimmed. Use an absolute path or a `./` prefix for a relative directory name that begins with whitespace.
|
||||
|
||||
Omit `path`, `content` and `sourcePath` to prepare the selected directory. Use the returned `directory`; never construct or guess the physical path. A save with a file requires `path` plus exactly one of `content` or `sourcePath`.
|
||||
|
||||
|
||||
@@ -4,11 +4,18 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
|
||||
def readonly_sqlite_uri(path: Path) -> str:
|
||||
"""Escape the native filename, including separators, without introducing a URI authority."""
|
||||
filename = os.fsencode(path) if os.name == "posix" else str(path)
|
||||
return f"file:{quote(filename, safe='')}?mode=ro"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Back up the read-only source database into a separate destination using SQLite’s backup API."""
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
@@ -21,8 +28,7 @@ def main() -> None:
|
||||
if destination.exists() and destination.samefile(source):
|
||||
parser.error(f"Destination must not be the same file as source: {destination}")
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
source_uri = f"file:{quote(str(source), safe='')}?mode=ro"
|
||||
with sqlite3.connect(source_uri, uri=True) as source_connection:
|
||||
with sqlite3.connect(readonly_sqlite_uri(source), uri=True) as source_connection:
|
||||
creation_destination = destination.resolve()
|
||||
try:
|
||||
creation_destination.touch(mode=0o600, exist_ok=False)
|
||||
|
||||
@@ -1044,11 +1044,12 @@ def pinned_root_git_marker(
|
||||
not cwd.is_absolute()
|
||||
or not metadata.is_absolute()
|
||||
or len(cwd.drive) != 2
|
||||
or cwd.drive != metadata.drive
|
||||
or len(metadata.drive) != 2
|
||||
or len(work_tree.parts) < 2
|
||||
or cwd.parts[: len(work_tree.parts)] != work_tree.parts
|
||||
or len(metadata.parts) < 2
|
||||
or _GetDriveTypeW(cwd.anchor) != _DRIVE_FIXED
|
||||
or _GetDriveTypeW(metadata.anchor) != _DRIVE_FIXED
|
||||
):
|
||||
yield None
|
||||
return
|
||||
@@ -1087,6 +1088,55 @@ def pinned_root_git_marker(
|
||||
yield marker
|
||||
|
||||
|
||||
def pin_replay_metadata(
|
||||
pins: contextlib.ExitStack, metadata: Path | None, scratch: Path
|
||||
) -> Path | None:
|
||||
"""Bind the selected metadata and fresh private Windows scratch before copying into it."""
|
||||
if os.name != "nt" or metadata is None:
|
||||
return None
|
||||
try:
|
||||
with contextlib.ExitStack() as checked:
|
||||
checked.enter_context(_locked_parent(metadata, "HEAD", create=False))
|
||||
checked.enter_context(_locked_parent(scratch.parent, scratch.name, create=False))
|
||||
directory = _create_file(
|
||||
scratch,
|
||||
access=_FILE_TRAVERSE | _FILE_READ_ATTRIBUTES | _READ_CONTROL,
|
||||
share=_FILE_SHARE_READ | _FILE_SHARE_WRITE,
|
||||
disposition=_OPEN_EXISTING,
|
||||
flags=_FILE_FLAG_BACKUP_SEMANTICS | _FILE_FLAG_OPEN_REPARSE_POINT,
|
||||
)
|
||||
assert directory is not None and directory.value is not None
|
||||
checked.enter_context(directory)
|
||||
_verify_directory(directory.value, scratch)
|
||||
if _output_directory_grants(directory.value, scratch):
|
||||
return None
|
||||
pins.enter_context(checked.pop_all())
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return metadata
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def pinned_replay_gitfile(checkout: Path, metadata: Path) -> Iterator[Path]:
|
||||
"""Keep Git's short metadata pointer outside the replay and immutable while Git uses it."""
|
||||
with _locked_parent(checkout, ".git", create=False):
|
||||
# Git reads this path relative to its unchanged worktree cwd. Both volumes'
|
||||
# literal ancestors are pinned, including the temporary directory above checkout.
|
||||
marker = checkout.parent / "reviewed.git"
|
||||
handle = _create_file(
|
||||
marker,
|
||||
access=_GENERIC_WRITE | _FILE_READ_ATTRIBUTES,
|
||||
share=_FILE_SHARE_READ,
|
||||
disposition=_CREATE_NEW,
|
||||
flags=_FILE_ATTRIBUTE_NORMAL | _FILE_FLAG_OPEN_REPARSE_POINT,
|
||||
)
|
||||
assert handle is not None and handle.value is not None
|
||||
with handle:
|
||||
_verify_regular_file(handle.value, marker)
|
||||
_write_all(handle.value, f"gitdir: {metadata.as_posix()}\n".encode("utf-8"))
|
||||
yield Path("..") / marker.name
|
||||
|
||||
|
||||
def open_read_fd(scan_dir: Path, relative_path: str, context: str) -> int:
|
||||
"""Open a verified regular file and return an owned binary read descriptor."""
|
||||
|
||||
|
||||
@@ -58,6 +58,8 @@ GIT_REPOSITORY_ENVIRONMENT = (
|
||||
"GIT_COMMON_DIR",
|
||||
"GIT_DIR",
|
||||
"GIT_DISCOVERY_ACROSS_FILESYSTEM",
|
||||
"GIT_GLOB_PATHSPECS",
|
||||
"GIT_ICASE_PATHSPECS",
|
||||
"GIT_INDEX_FILE",
|
||||
"GIT_NAMESPACE",
|
||||
"GIT_OBJECT_DIRECTORY",
|
||||
|
||||
@@ -54,6 +54,7 @@ from finalize_scan_contract import (
|
||||
open_scan_local_file_descriptor,
|
||||
)
|
||||
from finding_preview import bounded_finding_details
|
||||
from windows_scan_local_files import pin_replay_metadata
|
||||
from workbench import handoff
|
||||
from workbench.storage import (
|
||||
create_private_directory,
|
||||
@@ -668,7 +669,8 @@ def require_working_tree_unchanged(target: Path, diff_target: dict[str, str] | N
|
||||
and diff_target["kind"] == "working_tree"
|
||||
and (
|
||||
git_revision(target) != diff_target["headRevision"]
|
||||
or worktree_content_digest(target) != diff_target["contentDigest"]
|
||||
or worktree_content_digest(target, expected_digest=diff_target["contentDigest"])
|
||||
!= diff_target["contentDigest"]
|
||||
)
|
||||
):
|
||||
raise SystemExit("The selected scan target changed while the scan was starting. Try again.")
|
||||
@@ -2361,7 +2363,9 @@ def require_reviewed_patch_applied(
|
||||
) -> str | None:
|
||||
target = require_scan_target_identity(scan)
|
||||
_, content_digest = remediation_checkout_snapshot(
|
||||
scan, expected_revision=remediation["base_revision"]
|
||||
scan,
|
||||
expected_revision=remediation["base_revision"],
|
||||
expected_digest=remediation["base_content_digest"],
|
||||
)
|
||||
if content_digest == remediation["base_content_digest"]:
|
||||
raise SystemExit(
|
||||
@@ -2371,12 +2375,17 @@ def require_reviewed_patch_applied(
|
||||
excluded = (Path(scan["scan_dir"]),)
|
||||
# Unborn repositories still need their config while metadata junctions are deferred.
|
||||
git_dir = git_output(target, "rev-parse", "--absolute-git-dir")
|
||||
metadata = Path(git_dir) if git_dir is not None else None
|
||||
if not unversioned:
|
||||
repository, pathspec = git_worktree_context(target)
|
||||
if git_dir is None:
|
||||
raise SystemExit("Could not inspect the selected Git working tree.")
|
||||
excluded += tuple(path for path, _ in git_submodule_entries(target))
|
||||
with tempfile.TemporaryDirectory(prefix="codex-security-remediation-") as temporary:
|
||||
with (
|
||||
tempfile.TemporaryDirectory(prefix="codex-security-remediation-") as temporary,
|
||||
ExitStack() as pins,
|
||||
):
|
||||
pinned_metadata = pin_replay_metadata(pins, metadata, Path(temporary))
|
||||
reviewed_patch = Path(temporary) / "reviewed.patch"
|
||||
digest = hashlib.sha256()
|
||||
with open_scan_local_file(Path(scan["scan_dir"]), patch_path) as source:
|
||||
@@ -2392,36 +2401,30 @@ def require_reviewed_patch_applied(
|
||||
junctions = copy_directory_excluding(target, checkout, excluded)
|
||||
else:
|
||||
_, junctions = copy_git_worktree_files(target, checkout_root, excluded)
|
||||
arguments = ["apply", "--reverse", "--whitespace=nowarn"]
|
||||
if unversioned:
|
||||
arguments.append("--no-index")
|
||||
elif pathspec != ".":
|
||||
arguments.append(f"--directory={pathspec}")
|
||||
arguments.append(str(reviewed_patch))
|
||||
applied = git_command(
|
||||
checkout if unversioned else checkout_root,
|
||||
*arguments,
|
||||
text=False,
|
||||
git_dir=Path(git_dir) if git_dir is not None else None,
|
||||
work_tree=checkout_root if git_dir is not None else None,
|
||||
short, replay_root = remediation_state.reverse_reviewed_patch(
|
||||
target,
|
||||
checkout_root,
|
||||
metadata,
|
||||
pinned_metadata,
|
||||
remediation["patch_digest"],
|
||||
pins,
|
||||
reviewed_patch,
|
||||
None if unversioned else pathspec,
|
||||
)
|
||||
if applied.returncode != 0:
|
||||
raise SystemExit(
|
||||
"The selected checkout does not contain the reviewed remediation patch. Apply exactly that patch before recording it as applied."
|
||||
)
|
||||
restore_directory_junctions(
|
||||
target if unversioned else repository,
|
||||
checkout if unversioned else checkout_root,
|
||||
junctions,
|
||||
)
|
||||
reverted_digest = (
|
||||
directory_content_digest(checkout)
|
||||
directory_content_digest(checkout, replay_git_dir=replay_root)
|
||||
if unversioned
|
||||
else worktree_content_digest_for_context(
|
||||
checkout_root,
|
||||
pathspec or ".",
|
||||
git_dir=Path(git_dir),
|
||||
git_dir=short or metadata,
|
||||
work_tree=checkout_root,
|
||||
expected_digest=remediation["base_content_digest"],
|
||||
)
|
||||
)
|
||||
if reverted_digest != remediation["base_content_digest"] and unversioned:
|
||||
@@ -2431,12 +2434,16 @@ def require_reviewed_patch_applied(
|
||||
checkout,
|
||||
"-c",
|
||||
"core.autocrlf=input",
|
||||
*arguments,
|
||||
"apply",
|
||||
"--reverse",
|
||||
"--whitespace=nowarn",
|
||||
"--no-index",
|
||||
str(reviewed_patch),
|
||||
text=True,
|
||||
)
|
||||
if applied_without_conversion.returncode == 0:
|
||||
restore_directory_junctions(target, checkout, junctions)
|
||||
reverted_digest = directory_content_digest(checkout)
|
||||
reverted_digest = directory_content_digest(checkout, replay_git_dir=replay_root)
|
||||
if reverted_digest != remediation["base_content_digest"]:
|
||||
raise SystemExit(
|
||||
"The selected checkout contains changes outside the reviewed patch. Remove them before recording the patch as applied."
|
||||
@@ -2451,9 +2458,6 @@ def require_remediation_checkout_unchanged(
|
||||
require_applied_content: bool = False,
|
||||
require_base_content: bool = False,
|
||||
) -> None:
|
||||
_, content_digest = remediation_checkout_snapshot(
|
||||
scan, expected_revision=remediation["base_revision"]
|
||||
)
|
||||
expected_digest = (
|
||||
remediation["applied_content_digest"]
|
||||
if require_applied_content
|
||||
@@ -2461,6 +2465,9 @@ def require_remediation_checkout_unchanged(
|
||||
if require_base_content
|
||||
else None
|
||||
)
|
||||
_, content_digest = remediation_checkout_snapshot(
|
||||
scan, expected_revision=remediation["base_revision"], expected_digest=expected_digest
|
||||
)
|
||||
if expected_digest is not None and content_digest != expected_digest:
|
||||
raise SystemExit(
|
||||
"Working-tree contents changed. Regenerate the remediation patch against the current checkout."
|
||||
|
||||
@@ -12,7 +12,6 @@ import sys
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
|
||||
# Some plugin hosts launch Python with safe-path isolation enabled.
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
@@ -27,6 +26,7 @@ from finalize_scan_contract import (
|
||||
write_export_output,
|
||||
write_sarif_projection,
|
||||
)
|
||||
from snapshot_sqlite import readonly_sqlite_uri
|
||||
from validate_scan_contract import validate_contract
|
||||
from workbench_constants import PRIMARY_FINDING_LOCATION_SQL
|
||||
|
||||
@@ -226,9 +226,8 @@ def finding_issues(db: Any, payload: Any) -> dict[str, Any]:
|
||||
except PermissionError:
|
||||
pass # Let SQLite report the open failure used by the host's state fallback.
|
||||
if payload["action"] == "inspect":
|
||||
database_uri = f"file:{quote(str(path), safe='')}?mode=ro"
|
||||
try:
|
||||
connection = sqlite3.connect(database_uri, uri=True, timeout=5)
|
||||
connection = sqlite3.connect(readonly_sqlite_uri(path), uri=True, timeout=5)
|
||||
except sqlite3.OperationalError as exc:
|
||||
if str(exc) == "unable to open database file":
|
||||
exc._codex_security_state_unavailable = True
|
||||
|
||||
@@ -46,6 +46,92 @@ COMMANDS = {
|
||||
SCAN_STATUS_ERROR = "Remediation is available only for successfully completed scans."
|
||||
|
||||
|
||||
def reverse_reviewed_patch(
|
||||
target: Path,
|
||||
checkout: Path,
|
||||
metadata: Path | None,
|
||||
pinned_metadata: Path | None,
|
||||
patch_digest: str,
|
||||
pins: ExitStack,
|
||||
patch: Path,
|
||||
pathspec: str | None,
|
||||
) -> tuple[Path | None, Path | None]:
|
||||
"""Reverse reviewed bytes and select the Git references for subsequent content snapshots."""
|
||||
|
||||
arguments = ["--reverse", "--whitespace=nowarn"]
|
||||
if pathspec is None:
|
||||
arguments.append("--no-index")
|
||||
elif pathspec != ".":
|
||||
arguments.append(f"--directory={pathspec}")
|
||||
arguments.append(str(patch))
|
||||
|
||||
def reverse(*, git_dir: Path | None, check: bool = False):
|
||||
return git_command(
|
||||
checkout,
|
||||
"apply",
|
||||
*(["--check"] if check else []),
|
||||
*arguments,
|
||||
text=False,
|
||||
git_dir=git_dir,
|
||||
work_tree=checkout if git_dir else None,
|
||||
environment_overrides={"LC_ALL": "C", "LANGUAGE": "C"} if check else None,
|
||||
)
|
||||
|
||||
applied = reverse(git_dir=metadata)
|
||||
short = None
|
||||
diagnostic = b"fatal: '$GIT_DIR' too big"
|
||||
if (
|
||||
os.name == "nt"
|
||||
and metadata is not None
|
||||
and applied.returncode == 128
|
||||
and not applied.stdout
|
||||
and b"GIT_DIR" in applied.stderr
|
||||
):
|
||||
# Confirm translated messages without applying the reverse patch twice.
|
||||
failure = (
|
||||
applied
|
||||
if diagnostic in applied.stderr.splitlines()
|
||||
else reverse(git_dir=metadata, check=True)
|
||||
)
|
||||
if (
|
||||
failure.returncode == 128
|
||||
and not failure.stdout
|
||||
and diagnostic in failure.stderr.splitlines()
|
||||
):
|
||||
short = prepare_replay_gitfile(checkout, pinned_metadata, patch_digest, pins)
|
||||
applied = reverse(git_dir=short)
|
||||
if applied.returncode != 0:
|
||||
raise SystemExit(
|
||||
"The selected checkout does not contain the reviewed remediation patch. Apply exactly that patch before recording it as applied."
|
||||
)
|
||||
replay_root = None
|
||||
if pathspec is None and short is not None:
|
||||
selected_root = git_output(target, "rev-parse", "--show-toplevel")
|
||||
if selected_root and Path(selected_root).samefile(target):
|
||||
replay_root = short
|
||||
return short, replay_root
|
||||
|
||||
|
||||
def prepare_replay_gitfile(
|
||||
checkout: Path, pinned_metadata: Path | None, patch_digest: str, pins: ExitStack
|
||||
) -> Path:
|
||||
"""Retain the verified patch and short metadata reference through the final snapshot."""
|
||||
if pinned_metadata is None:
|
||||
raise SystemExit(
|
||||
"Could not bind the selected Windows Git directory and private patch replay directory."
|
||||
)
|
||||
from windows_scan_local_files import open_read_fd, pinned_replay_gitfile
|
||||
|
||||
try:
|
||||
short = pins.enter_context(pinned_replay_gitfile(checkout, pinned_metadata))
|
||||
fd = open_read_fd(checkout.parent, "reviewed.patch", "reviewed remediation patch")
|
||||
patch = pins.enter_context(os.fdopen(fd, "rb"))
|
||||
matching_patch_metadata(patch, patch_digest)
|
||||
except (OSError, ValueError) as exc:
|
||||
raise SystemExit(f"Could not verify the reviewed patch replay: {exc}") from exc
|
||||
return short
|
||||
|
||||
|
||||
def require_available(connection: sqlite3.Connection, args: Any, require_scan: Any) -> None:
|
||||
"""Require a successfully completed scan for commands that act on a remediation request."""
|
||||
if args.command not in COMMANDS:
|
||||
|
||||
@@ -80,8 +80,11 @@ def _windows_resume_checkout(scan: sqlite3.Row) -> Path:
|
||||
except SystemExit as exc:
|
||||
raise SystemExit(replaced) from exc
|
||||
with verified_windows_checkout(scan, repository, replaced_message=replaced):
|
||||
snapshot = (scan["target_revision"], scan["target_snapshot_digest"])
|
||||
if scan_target_identity(repository, None)[:2] != snapshot:
|
||||
expected = (scan["target_revision"], scan["target_snapshot_digest"])
|
||||
current = scan_target_identity(
|
||||
repository, None, expected_digest=scan["target_snapshot_digest"]
|
||||
)
|
||||
if current[:2] != expected:
|
||||
raise SystemExit("Cannot resume: the original checkout revision or contents changed.")
|
||||
return repository
|
||||
|
||||
@@ -127,7 +130,9 @@ def cli_scan_resume(
|
||||
raise SystemExit(
|
||||
"Cannot resume: the original checkout is missing or was replaced."
|
||||
) from exc
|
||||
if scan_target_identity(repository, None) != (
|
||||
if scan_target_identity(
|
||||
repository, None, expected_digest=scan["target_snapshot_digest"]
|
||||
) != (
|
||||
scan["target_revision"],
|
||||
scan["target_snapshot_digest"],
|
||||
scan["target_device"],
|
||||
|
||||
@@ -65,6 +65,7 @@ def scan_target_identity(
|
||||
diff_target: dict[str, str] | None,
|
||||
*,
|
||||
metadata: os.stat_result | None = None,
|
||||
expected_digest: str | None = None,
|
||||
) -> tuple[str, str | None, int | str, int | str]:
|
||||
"""Return revision, content digest, device ID, and inode for scan registration.
|
||||
|
||||
@@ -79,7 +80,7 @@ def scan_target_identity(
|
||||
snapshot_digest = (
|
||||
directory_content_digest(target)
|
||||
if revision == "unversioned"
|
||||
else worktree_content_digest(target)
|
||||
else worktree_content_digest(target, expected_digest=expected_digest)
|
||||
)
|
||||
return (
|
||||
revision,
|
||||
|
||||
@@ -17,9 +17,9 @@ from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from snapshot_sqlite import readonly_sqlite_uri
|
||||
from workbench.storage import archive_source_directory, worker_usage_directory
|
||||
|
||||
TOKEN_FIELDS = {
|
||||
@@ -607,9 +607,9 @@ def _scan_worker_directories(
|
||||
|
||||
|
||||
def _codex_state_database() -> Path | None:
|
||||
configured_database = os.environ.get("CODEX_STATE_DB", "").strip()
|
||||
if configured_database:
|
||||
path = Path(configured_database).expanduser()
|
||||
configured_database = os.environ.get("CODEX_STATE_DB", "")
|
||||
if configured_database.strip():
|
||||
path = Path(os.path.expanduser(configured_database))
|
||||
return path.resolve() if path.is_file() and os.access(path, os.R_OK) else None
|
||||
|
||||
configured_home = os.environ.get("CODEX_HOME", "")
|
||||
@@ -654,7 +654,7 @@ def _discover_rollout_sessions(
|
||||
completed_at: datetime | None,
|
||||
) -> tuple[list[RolloutSession], set[str]]:
|
||||
database = sqlite3.connect(
|
||||
f"file:{quote(str(state_database), safe='')}?mode=ro",
|
||||
readonly_sqlite_uri(state_database),
|
||||
uri=True,
|
||||
timeout=STATE_DATABASE_TIMEOUT_SECONDS,
|
||||
)
|
||||
|
||||
@@ -76,7 +76,7 @@ def require_diff_target(
|
||||
if kind == "working_tree":
|
||||
base = resolve_git_commit(target, base_revision or "HEAD", "Working-tree base")
|
||||
head = resolve_git_commit(target, head_revision or current_head, "Working-tree HEAD")
|
||||
current_digest = worktree_content_digest(target)
|
||||
current_digest = worktree_content_digest(target, expected_digest=content_digest)
|
||||
if base != current_head or head != current_head:
|
||||
raise SystemExit(
|
||||
"Repository HEAD changed after these working-tree changes were selected. "
|
||||
|
||||
@@ -282,6 +282,7 @@ def git_command(
|
||||
work_tree: Path | None = None,
|
||||
stdout_file: BinaryIO | None = None,
|
||||
environment_overrides: dict[str, str] | None = None,
|
||||
inherit_git_environment: bool = True,
|
||||
offline: bool = False,
|
||||
) -> subprocess.CompletedProcess[str] | subprocess.CompletedProcess[bytes]:
|
||||
"""Run Git against target and return the completed process with its exit status.
|
||||
@@ -292,7 +293,13 @@ def git_command(
|
||||
"""
|
||||
if (git_dir is None) != (work_tree is None):
|
||||
raise ValueError("git_dir and work_tree must be provided together")
|
||||
environment = os.environ.copy()
|
||||
environment = (
|
||||
os.environ.copy()
|
||||
if inherit_git_environment
|
||||
else {
|
||||
name: value for name, value in os.environ.items() if not name.upper().startswith("GIT_")
|
||||
}
|
||||
)
|
||||
for name in GIT_REPOSITORY_ENVIRONMENT:
|
||||
environment.pop(name, None)
|
||||
environment["GIT_LITERAL_PATHSPECS"] = "1"
|
||||
@@ -578,6 +585,56 @@ def _visible_git_character(char: str) -> str:
|
||||
return ascii(char)[1:-1]
|
||||
|
||||
|
||||
def _canonical_patch_chunks(output: BinaryIO) -> Iterator[bytes]:
|
||||
"""Drop Git's optional function label while preserving hunk coordinates and content."""
|
||||
line_start = True
|
||||
# Limit each read even when source lines are arbitrarily large.
|
||||
for part in iter(lambda: output.readline(1024 * 1024), b""):
|
||||
next_line_start = part.endswith(b"\n")
|
||||
if line_start and part.startswith(b"@@ "):
|
||||
coordinates, end, _ = part.partition(b" @@")
|
||||
if end:
|
||||
part = coordinates + end + b"\n"
|
||||
yield part
|
||||
line_start = next_line_start
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _diff_driver_config(
|
||||
target: Path, git_dir: Path | None, work_tree: Path | None
|
||||
) -> Iterator[tuple[str, ...]]:
|
||||
names = git_command(
|
||||
target,
|
||||
"config",
|
||||
"--name-only",
|
||||
"--null",
|
||||
"--get-regexp",
|
||||
r"^diff\..+\.binary$",
|
||||
text=False,
|
||||
git_dir=git_dir,
|
||||
work_tree=work_tree,
|
||||
environment_overrides={"LC_ALL": "C"},
|
||||
)
|
||||
if names.returncode == 1: # Git returns 1 when there are no matching keys.
|
||||
yield ()
|
||||
return
|
||||
if names.returncode:
|
||||
raise SystemExit(
|
||||
os.fsdecode(names.stderr) or "Could not inspect Git diff-driver configuration."
|
||||
)
|
||||
# A private command-scope include preserves case and arbitrary driver-name bytes
|
||||
# without putting an unbounded number of keys on the command line.
|
||||
with tempfile.TemporaryDirectory(prefix="codex-security-diff-") as directory:
|
||||
config = Path(directory) / "drivers"
|
||||
with config.open("wb") as stream:
|
||||
for key in names.stdout.split(b"\0"):
|
||||
if key:
|
||||
driver = key.removeprefix(b"diff.").removesuffix(b".binary")
|
||||
escaped = driver.replace(b"\\", b"\\\\").replace(b'"', b'\\"')
|
||||
stream.write(b'[diff "' + escaped + b'"]\n\tbinary = auto\n')
|
||||
yield "-c", f"include.path={config}"
|
||||
|
||||
|
||||
def _update_digest_field_from_git(
|
||||
digest: Any,
|
||||
label: bytes,
|
||||
@@ -585,15 +642,24 @@ def _update_digest_field_from_git(
|
||||
*args: str,
|
||||
git_dir: Path | None = None,
|
||||
work_tree: Path | None = None,
|
||||
environment_overrides: dict[str, str] | None = None,
|
||||
stable_display: bool = False,
|
||||
) -> None:
|
||||
with tempfile.TemporaryFile() as output:
|
||||
with tempfile.TemporaryFile() as output, ExitStack() as stack:
|
||||
driver_config = (
|
||||
stack.enter_context(_diff_driver_config(target, git_dir, work_tree))
|
||||
if stable_display
|
||||
else ()
|
||||
)
|
||||
completed = git_command(
|
||||
target,
|
||||
*driver_config,
|
||||
*args,
|
||||
text=False,
|
||||
git_dir=git_dir,
|
||||
work_tree=work_tree,
|
||||
stdout_file=output,
|
||||
environment_overrides=environment_overrides,
|
||||
)
|
||||
if completed.returncode != 0:
|
||||
detail = completed.stderr.decode("utf-8", errors="backslashreplace").replace(
|
||||
@@ -603,25 +669,36 @@ def _update_digest_field_from_git(
|
||||
raise SystemExit(
|
||||
f"Could not snapshot the selected working-tree changes.\n{detail}".rstrip("\n")
|
||||
)
|
||||
output.seek(0, os.SEEK_END)
|
||||
value_size = output.tell()
|
||||
if stable_display:
|
||||
output.seek(0)
|
||||
value_size = sum(len(part) for part in _canonical_patch_chunks(output))
|
||||
else:
|
||||
value_size = output.seek(0, os.SEEK_END)
|
||||
_update_digest_field_header(digest, label, value_size)
|
||||
output.seek(0)
|
||||
for chunk in iter(lambda: output.read(1024 * 1024), b""):
|
||||
chunks = (
|
||||
_canonical_patch_chunks(output)
|
||||
if stable_display
|
||||
else iter(lambda: output.read(1024 * 1024), b"")
|
||||
)
|
||||
for chunk in chunks:
|
||||
digest.update(chunk)
|
||||
|
||||
|
||||
def worktree_content_digest(target: Path) -> str:
|
||||
def worktree_content_digest(target: Path, *, expected_digest: str | None = None) -> str:
|
||||
"""Return the worktree digest for the selected path after checking the state of its submodules."""
|
||||
require_clean_submodule_worktrees(target)
|
||||
repository, pathspec = git_worktree_context(target)
|
||||
return worktree_content_digest_for_context(repository, pathspec)
|
||||
return worktree_content_digest_for_context(
|
||||
repository, pathspec, expected_digest=expected_digest
|
||||
)
|
||||
|
||||
|
||||
def remediation_checkout_snapshot(
|
||||
scan: sqlite3.Row,
|
||||
*,
|
||||
expected_revision: str | None = None,
|
||||
expected_digest: str | None = None,
|
||||
head_changed_message: str = (
|
||||
"Repository HEAD changed. Regenerate the remediation patch against the current checkout."
|
||||
),
|
||||
@@ -633,7 +710,7 @@ def remediation_checkout_snapshot(
|
||||
if revision != required_revision:
|
||||
raise SystemExit(head_changed_message)
|
||||
content_digest = (
|
||||
worktree_content_digest(target)
|
||||
worktree_content_digest(target, expected_digest=expected_digest)
|
||||
if revision != "unversioned"
|
||||
else directory_content_digest(target, excluded=(Path(scan["scan_dir"]),))
|
||||
)
|
||||
@@ -654,23 +731,28 @@ def require_scan_target_unchanged(scan: sqlite3.Row) -> None:
|
||||
raise SystemExit(head_changed_message)
|
||||
require_clean_submodule_worktrees(target)
|
||||
return
|
||||
_, current_digest = remediation_checkout_snapshot(
|
||||
scan, head_changed_message=head_changed_message
|
||||
)
|
||||
if scan["diff_target_kind"] == "working_tree":
|
||||
expected_digest = scan["diff_content_digest"]
|
||||
elif scan["diff_target_kind"] in {"commit", "range"}:
|
||||
tracked = git_bytes(Path(scan["target_path"]), "ls-files", "-t", "-z")
|
||||
expected_digest = clean_worktree_content_digest()
|
||||
else:
|
||||
expected_digest = scan["target_snapshot_digest"]
|
||||
_, current_digest = remediation_checkout_snapshot(
|
||||
scan, expected_digest=expected_digest, head_changed_message=head_changed_message
|
||||
)
|
||||
if scan["diff_target_kind"] in {"commit", "range"}:
|
||||
target = Path(scan["target_path"])
|
||||
tracked = git_bytes(target, "ls-files", "-v", "-z")
|
||||
if tracked is None:
|
||||
raise SystemExit("Could not inspect tracked files in the scan target.")
|
||||
if any(entry.startswith(b"S ") for entry in tracked.split(b"\0")):
|
||||
entries = tracked.split(b"\0")
|
||||
if any(entry.startswith((b"S ", b"s ")) for entry in entries):
|
||||
raise SystemExit(
|
||||
"Committed-diff scans require a full repository checkout. "
|
||||
"Sparse checkouts are not supported; materialize skipped tracked files and retry."
|
||||
)
|
||||
expected_digest = clean_worktree_content_digest()
|
||||
else:
|
||||
expected_digest = scan["target_snapshot_digest"]
|
||||
if any(entry.startswith(b"h ") for entry in entries):
|
||||
verify_assumed_unchanged_files(target)
|
||||
if current_digest != expected_digest:
|
||||
raise SystemExit(
|
||||
"Scan target contents changed since the scan. "
|
||||
@@ -678,12 +760,67 @@ def require_scan_target_unchanged(scan: sqlite3.Row) -> None:
|
||||
)
|
||||
|
||||
|
||||
def verify_assumed_unchanged_files(target: Path) -> None:
|
||||
index = git_output(target, "rev-parse", "--path-format=absolute", "--git-path", "index")
|
||||
if index is None:
|
||||
raise SystemExit("Could not locate the Git index for the scan target.")
|
||||
with tempfile.TemporaryDirectory(prefix="codex-security-git-index-") as directory:
|
||||
# Refresh a private index without running checkout hooks or updating its shared index.
|
||||
index_copy = Path(directory) / "index"
|
||||
shutil.copyfile(index, index_copy)
|
||||
result = git_command(
|
||||
target,
|
||||
"-c",
|
||||
f"core.hooksPath={directory}",
|
||||
"-c",
|
||||
"core.splitIndex=false",
|
||||
"update-index",
|
||||
"--really-refresh",
|
||||
text=False,
|
||||
environment_overrides={"GIT_INDEX_FILE": str(index_copy)},
|
||||
# A repository's clean filter can run while Git compares working-tree bytes.
|
||||
inherit_git_environment=False,
|
||||
offline=True,
|
||||
)
|
||||
if result.returncode == 1:
|
||||
raise SystemExit(
|
||||
"A tracked file marked assume-unchanged changed since the scan. "
|
||||
"Run a new scan before validating its findings."
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise SystemExit(
|
||||
os.fsdecode(result.stderr) or "Could not refresh the scan target's Git index."
|
||||
)
|
||||
|
||||
|
||||
def worktree_content_digest_for_context(
|
||||
repository: Path,
|
||||
pathspec: str,
|
||||
*,
|
||||
git_dir: Path | None = None,
|
||||
work_tree: Path | None = None,
|
||||
expected_digest: str | None = None,
|
||||
) -> str:
|
||||
def calculate(stable_display: bool) -> str:
|
||||
return _git_content_digest(repository, pathspec, git_dir, work_tree, stable_display)
|
||||
|
||||
current = calculate(True)
|
||||
# Older sealed snapshots may have included the user's Git display settings.
|
||||
if (
|
||||
expected_digest is not None
|
||||
and current != expected_digest
|
||||
and calculate(False) == expected_digest
|
||||
):
|
||||
return expected_digest
|
||||
return current
|
||||
|
||||
|
||||
def _git_content_digest(
|
||||
repository: Path,
|
||||
pathspec: str,
|
||||
git_dir: Path | None,
|
||||
work_tree: Path | None,
|
||||
stable_display: bool,
|
||||
) -> str:
|
||||
digest = hashlib.sha256()
|
||||
update_digest_field(digest, b"format", b"codex-security-snapshot/v1")
|
||||
@@ -692,12 +829,44 @@ def worktree_content_digest_for_context(
|
||||
":(top,glob,exclude)**/.svn",
|
||||
":(top,glob,exclude)**/.svn/**",
|
||||
]
|
||||
config = (
|
||||
(
|
||||
"-c",
|
||||
"core.quotePath=true",
|
||||
"-c",
|
||||
"diff.suppressBlankEmpty=false",
|
||||
"-c",
|
||||
"core.compression=1", # Git uses the fastest zlib level for binary patches by default.
|
||||
)
|
||||
if stable_display
|
||||
else ()
|
||||
)
|
||||
display = (
|
||||
(
|
||||
"--no-color",
|
||||
"--src-prefix=a/",
|
||||
"--dst-prefix=b/",
|
||||
"--unified=3",
|
||||
"--diff-algorithm=myers",
|
||||
"--indent-heuristic",
|
||||
"--inter-hunk-context=0",
|
||||
"--find-renames=50%",
|
||||
"-l1000", # Git's default inexact rename limit.
|
||||
"--submodule=short",
|
||||
"-O",
|
||||
os.devnull,
|
||||
)
|
||||
if stable_display
|
||||
else ()
|
||||
)
|
||||
_update_digest_field_from_git(
|
||||
digest,
|
||||
b"tracked-diff",
|
||||
repository,
|
||||
*config,
|
||||
"--no-literal-pathspecs",
|
||||
"diff",
|
||||
*display,
|
||||
"--binary",
|
||||
"--full-index",
|
||||
"--no-ext-diff",
|
||||
@@ -708,6 +877,9 @@ def worktree_content_digest_for_context(
|
||||
*source_pathspecs,
|
||||
git_dir=git_dir,
|
||||
work_tree=work_tree,
|
||||
# GIT_DIFF_OPTS overrides even an explicit --unified option.
|
||||
environment_overrides={"GIT_DIFF_OPTS": ""} if stable_display else None,
|
||||
stable_display=stable_display,
|
||||
)
|
||||
untracked = git_bytes(
|
||||
repository,
|
||||
@@ -912,11 +1084,16 @@ def _windows_inventory_query(
|
||||
return result
|
||||
|
||||
|
||||
def git_directory_snapshot_paths(target: Path) -> list[Path] | None:
|
||||
repository_root = git_output(target, "rev-parse", "--show-toplevel")
|
||||
if repository_root is None:
|
||||
return None
|
||||
repository, pathspec = git_worktree_context(target)
|
||||
def git_directory_snapshot_paths(
|
||||
target: Path, *, replay_git_dir: Path | None = None
|
||||
) -> list[Path] | None:
|
||||
if replay_git_dir is None:
|
||||
if git_output(target, "rev-parse", "--show-toplevel") is None:
|
||||
return None
|
||||
repository, pathspec = git_worktree_context(target)
|
||||
else:
|
||||
# The temporary copy of an unborn repository uses the selected Git config and index.
|
||||
repository, pathspec = target, "."
|
||||
scope = repository / pathspec
|
||||
scope_depth = len(Path(pathspec).parts)
|
||||
matching_prefixes: dict[str, bool] = {}
|
||||
@@ -944,6 +1121,8 @@ def git_directory_snapshot_paths(target: Path) -> list[Path] | None:
|
||||
"-z",
|
||||
"--",
|
||||
inventory_pathspec,
|
||||
git_dir=replay_git_dir,
|
||||
work_tree=repository if replay_git_dir else None,
|
||||
)
|
||||
if listed is None:
|
||||
raise SystemExit("Could not inspect files in the selected Git working tree.")
|
||||
@@ -1002,7 +1181,7 @@ def git_directory_snapshot_paths(target: Path) -> list[Path] | None:
|
||||
if _WINDOWS:
|
||||
# Git omits empty untracked directories from its file listing. Inventory
|
||||
# junction identities independently of whether their targets contain files.
|
||||
git_directory = git_output(target, "rev-parse", "--absolute-git-dir")
|
||||
git_directory = replay_git_dir or git_output(target, "rev-parse", "--absolute-git-dir")
|
||||
if git_directory is None:
|
||||
raise SystemExit("Could not inspect the selected Git working tree.")
|
||||
directories = _windows_inventory_query(
|
||||
@@ -1119,6 +1298,7 @@ def directory_content_digest(
|
||||
excluded: tuple[Path, ...] = (),
|
||||
include_ignored: bool = False,
|
||||
include_git_metadata: bool = False,
|
||||
replay_git_dir: Path | None = None,
|
||||
) -> str:
|
||||
def raise_walk_error(error: OSError) -> None:
|
||||
raise error
|
||||
@@ -1131,7 +1311,7 @@ def directory_content_digest(
|
||||
target, excluded, include_git_metadata=include_git_metadata, onerror=raise_walk_error
|
||||
)
|
||||
if include_ignored
|
||||
else git_directory_snapshot_paths(target)
|
||||
else git_directory_snapshot_paths(target, replay_git_dir=replay_git_dir)
|
||||
)
|
||||
if paths is None:
|
||||
paths = source_directory_snapshot_paths(target, excluded)
|
||||
@@ -1518,7 +1698,7 @@ def scan_target_warning(scan: sqlite3.Row) -> str | None:
|
||||
expected_digest = (
|
||||
scan["diff_content_digest"] if working_tree else scan["target_snapshot_digest"]
|
||||
)
|
||||
if worktree_content_digest(target) != expected_digest:
|
||||
if worktree_content_digest(target, expected_digest=expected_digest) != expected_digest:
|
||||
return (
|
||||
"Working-tree contents changed while the scan was running; "
|
||||
"results were saved for the original snapshot."
|
||||
|
||||
@@ -6,6 +6,7 @@ import json
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import sys
|
||||
import uuid
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
@@ -127,6 +128,18 @@ def test_inaccessible_state_preserves_sqlite_open_error(tmp_path: Path, action:
|
||||
state.chmod(0o700)
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "linux", reason="requires Linux filename bytes")
|
||||
def test_inspects_recorded_receipt_in_state_path_with_non_utf8_bytes(tmp_path: Path) -> None:
|
||||
state = tmp_path / os.fsdecode(b"state-\xff?#%")
|
||||
scan_dir, validated = source(tmp_path)
|
||||
receipt = receipt_for(validated)
|
||||
issues(state, scan_dir, "record", receipts=[receipt])
|
||||
assert (
|
||||
issues(state, scan_dir, "inspect")["receipts"][0]["issueIdentifier"]
|
||||
== receipt["issueIdentifier"]
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("project", [None, "project-example"])
|
||||
def test_legacy_receipts_are_read_without_migration_and_preserved_on_upgrade(
|
||||
tmp_path: Path, project: str | None
|
||||
|
||||
@@ -4,11 +4,13 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import uuid
|
||||
from contextlib import closing
|
||||
from dataclasses import dataclass, replace
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
@@ -328,7 +330,7 @@ def _state_graph(
|
||||
) -> None:
|
||||
sqlite_home = Path(environment["CODEX_SQLITE_HOME"])
|
||||
sqlite_home.mkdir(parents=True, exist_ok=True)
|
||||
with sqlite3.connect(sqlite_home / "state_5.sqlite") as connection:
|
||||
with closing(sqlite3.connect(sqlite_home / "state_5.sqlite")) as connection, connection:
|
||||
connection.execute(
|
||||
"CREATE TABLE threads "
|
||||
"(id TEXT PRIMARY KEY, rollout_path TEXT NOT NULL, cwd TEXT, created_at INTEGER)"
|
||||
@@ -1307,6 +1309,44 @@ def test_usage_finds_state_database_in_configured_home(
|
||||
assert scan_usage._codex_state_database() == database.resolve()
|
||||
|
||||
|
||||
@pytest.mark.cross_platform
|
||||
@pytest.mark.parametrize(
|
||||
("spelling", "filename"),
|
||||
[
|
||||
("leading-relative", " usage.sqlite"),
|
||||
(
|
||||
"trailing-absolute",
|
||||
"usage.sqlite\N{NO-BREAK SPACE}" if sys.platform == "win32" else "usage.sqlite ",
|
||||
),
|
||||
]
|
||||
+ ([] if sys.platform == "win32" else [("literal-tilde", "~synthetic-usage.sqlite")])
|
||||
+ ([("filesystem-bytes", b"usage-\xff?#%.sqlite")] if sys.platform == "linux" else []),
|
||||
)
|
||||
def test_completion_reads_the_literal_usage_database(
|
||||
tmp_path: Path, spelling: str, filename: str | bytes, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
fixture = _start_scan(tmp_path)
|
||||
counted = fixture.started_at + timedelta(microseconds=1)
|
||||
fixture.write_parent_rollout([_token_event(counted, 18, 2)])
|
||||
original = Path(fixture.environment["CODEX_SQLITE_HOME"]) / "state_5.sqlite"
|
||||
selected = tmp_path / os.fsdecode(filename)
|
||||
original.rename(selected)
|
||||
|
||||
neighbor = tmp_path / "neighbor"
|
||||
neighbor.mkdir()
|
||||
other_rollout = _rollout(neighbor, "scan-parent", [_token_event(counted, 96, 2)])
|
||||
_state_graph(fixture.environment, {"scan-parent": other_rollout}, [])
|
||||
original.rename(tmp_path / "usage.sqlite")
|
||||
monkeypatch.chdir(tmp_path)
|
||||
fixture.environment["CODEX_STATE_DB"] = (
|
||||
str(selected) if spelling == "trailing-absolute" else selected.name
|
||||
)
|
||||
|
||||
usage = _complete_scan(fixture)["scan"]["usage"]
|
||||
assert usage["coverage"] == "complete"
|
||||
assert usage["totalTokens"] == 20
|
||||
|
||||
|
||||
def test_completion_reports_unavailable_without_fabricating_zero(tmp_path: Path) -> None:
|
||||
fixture = _start_scan(tmp_path)
|
||||
usage = _complete_scan(fixture)["scan"]["usage"]
|
||||
|
||||
@@ -10,7 +10,7 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from test_workbench_scan_history import create_cli_scan
|
||||
from workbench_test_support import get_scan, initialize_git_repository
|
||||
from workbench_test_support import configure_git_command, get_scan, initialize_git_repository
|
||||
|
||||
|
||||
def start_validation_scan(
|
||||
@@ -119,6 +119,53 @@ def test_check_scan_target_rejects_changed_revision(
|
||||
workbench_api["remediation_checkout_snapshot"](stored_scan)
|
||||
|
||||
|
||||
def test_check_committed_diff_target_rechecks_assume_unchanged_files(tmp_path: Path) -> None:
|
||||
repository = tmp_path / "repository"
|
||||
initialize_git_repository(repository)
|
||||
state_dir, scan_id = start_validation_scan(
|
||||
tmp_path, repository, target={"kind": "refs", "paths": [], "base": "HEAD", "head": "HEAD"}
|
||||
)
|
||||
source = repository / "README.md"
|
||||
original = source.read_bytes()
|
||||
subprocess.run(
|
||||
["git", "update-index", "--assume-unchanged", "--", source.name], cwd=repository, check=True
|
||||
)
|
||||
assert get_scan(state_dir, scan_id, "--check-target")["scan"]["scanId"] == scan_id
|
||||
|
||||
(repository / ".git" / "info" / "attributes").write_text("README.md filter=fixture\n")
|
||||
clean_filter = tmp_path / "clean_filter.py"
|
||||
clean_filter.write_text(
|
||||
"import os, sys\n"
|
||||
"from pathlib import Path\n"
|
||||
"if os.environ.get('GIT_INDEX_FILE'):\n"
|
||||
" inherited = os.environ.get('GIT_CONFIG_VALUE_0') == 'synthetic-fixture-value'\n"
|
||||
" Path(__file__).with_suffix('.result').write_text('inherited' if inherited else 'isolated')\n"
|
||||
"sys.stdout.buffer.write(sys.stdin.buffer.read())\n"
|
||||
)
|
||||
configure_git_command(repository, "filter.fixture.clean", clean_filter)
|
||||
# Matching sizes force Git to compare the filtered contents.
|
||||
source.write_bytes(b"x" * len(original))
|
||||
os.utime(source, (1, 1))
|
||||
changed = get_scan(
|
||||
state_dir,
|
||||
scan_id,
|
||||
"--check-target",
|
||||
check=False,
|
||||
environment={
|
||||
"GIT_CONFIG_COUNT": "1",
|
||||
"GIT_CONFIG_KEY_0": "http.extraHeader",
|
||||
"GIT_CONFIG_VALUE_0": "synthetic-fixture-value",
|
||||
},
|
||||
)
|
||||
assert changed["returncode"] != 0
|
||||
assert "changed" in changed["stderr"]
|
||||
assert clean_filter.with_suffix(".result").read_text() == "isolated"
|
||||
tracked = subprocess.check_output(["git", "ls-files", "-v", "--", source.name], cwd=repository)
|
||||
assert tracked.split(maxsplit=1)[0] == b"h"
|
||||
source.write_bytes(original)
|
||||
assert get_scan(state_dir, scan_id, "--check-target")["scan"]["scanId"] == scan_id
|
||||
|
||||
|
||||
def test_check_committed_diff_target_rejects_sparse_checkout_after_scan(tmp_path: Path) -> None:
|
||||
repository = tmp_path / "repository"
|
||||
initialize_git_repository(repository)
|
||||
|
||||
@@ -361,8 +361,23 @@ def assert_new_scan_model_is_independent(state_dir: Path, target: Path, scan_roo
|
||||
).fetchone() == (None, None, "gpt-5.6-sol", "high")
|
||||
|
||||
|
||||
def test_sqlite_snapshot_includes_uncheckpointed_wal_rows(tmp_path: Path) -> None:
|
||||
source = tmp_path / "source.sqlite3"
|
||||
@pytest.mark.parametrize(
|
||||
"source_name",
|
||||
[
|
||||
b"source.sqlite3",
|
||||
pytest.param(
|
||||
b"source-\xff?#%.sqlite3",
|
||||
marks=pytest.mark.skipif(
|
||||
sys.platform != "linux", reason="requires Linux filename bytes"
|
||||
),
|
||||
id="linux-filename-bytes",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_sqlite_snapshot_includes_uncheckpointed_wal_rows(
|
||||
tmp_path: Path, source_name: bytes
|
||||
) -> None:
|
||||
source = tmp_path / os.fsdecode(source_name)
|
||||
snapshot = tmp_path / "snapshot.sqlite3"
|
||||
with sqlite3.connect(source) as connection:
|
||||
connection.execute("PRAGMA journal_mode = WAL")
|
||||
|
||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import difflib
|
||||
import errno
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import runpy
|
||||
import shutil
|
||||
@@ -155,12 +156,14 @@ def test_recorded_checkout_distinguishes_a_replaced_parent_from_a_missing_path(
|
||||
def write_reviewed_patch(
|
||||
tmp_path: Path, source: Path, patch: bytes, revision: str = "unversioned"
|
||||
) -> dict[str, object]:
|
||||
from filesystem_identity import serialize_filesystem_identity
|
||||
|
||||
scan_dir = tmp_path / "scan"
|
||||
scan_dir.mkdir(mode=0o700)
|
||||
(scan_dir / "reviewed.patch").write_bytes(patch)
|
||||
return {
|
||||
"target_path": str(source),
|
||||
"target_inode": source.stat().st_ino,
|
||||
"target_inode": serialize_filesystem_identity(source.stat().st_ino),
|
||||
"target_revision": revision,
|
||||
"scan_dir": str(scan_dir),
|
||||
}
|
||||
@@ -174,6 +177,218 @@ def reviewed_remediation(patch: bytes, revision: str, digest: str) -> dict[str,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.cross_platform
|
||||
@pytest.mark.parametrize("layout", ["separate", "linked", "unborn", "unborn-root"])
|
||||
def test_reviewed_patch_uses_long_source_metadata_in_its_private_replay(
|
||||
tmp_path: Path, layout: str, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
import workbench_db
|
||||
|
||||
# The metadata argument is long in UTF-8 even on hosts with short temporary paths.
|
||||
padding = max(1, (230 - len((tmp_path / "metadata-").as_posix().encode("utf-8")) + 2) // 3)
|
||||
metadata = tmp_path / ("metadata-" + "界" * padding)
|
||||
source = tmp_path / "source"
|
||||
if layout == "unborn-root":
|
||||
source, metadata = metadata, metadata / ".git"
|
||||
subprocess.run(["git", "init", "-q", str(source)], check=True)
|
||||
else:
|
||||
subprocess.run(
|
||||
["git", "init", "-q", "--separate-git-dir", str(metadata), str(source)], check=True
|
||||
)
|
||||
subprocess.run(["git", "-C", str(source), "config", "core.autocrlf", "false"], check=True)
|
||||
(source / "file.txt").write_bytes(b"before\n")
|
||||
revision = "unversioned"
|
||||
if layout in {"separate", "linked"}:
|
||||
subprocess.run(["git", "-C", str(source), "add", "file.txt"], check=True)
|
||||
subprocess.run(
|
||||
[
|
||||
"git",
|
||||
"-C",
|
||||
str(source),
|
||||
"-c",
|
||||
"user.name=Fixture",
|
||||
"-c",
|
||||
"user.email=f@example.invalid",
|
||||
"commit",
|
||||
"-qm",
|
||||
"base",
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
if layout == "linked":
|
||||
linked = tmp_path / "linked"
|
||||
subprocess.run(
|
||||
["git", "-C", str(source), "worktree", "add", "--detach", str(linked)], check=True
|
||||
)
|
||||
source = linked
|
||||
revision = subprocess.check_output(
|
||||
["git", "-C", str(source), "rev-parse", "HEAD"], text=True
|
||||
).strip()
|
||||
marker = source / ".git/HEAD" if layout == "unborn-root" else source / ".git"
|
||||
original_marker = marker.read_bytes()
|
||||
(metadata / "info/exclude").write_bytes(b"ignored.fixture\n")
|
||||
(source / "ignored.fixture").write_bytes(b"outside the recorded content\n")
|
||||
if os.name == "nt" and revision == "unversioned":
|
||||
# The private copy keeps the original gitdir-conditional visibility when using the retry.
|
||||
global_config, included, excludes = (
|
||||
tmp_path / name for name in ("global", "include", "excludes")
|
||||
)
|
||||
excludes.write_bytes(b"conditional.fixture\n")
|
||||
subprocess.run(
|
||||
["git", "config", "--file", included, "core.excludesFile", excludes.as_posix()],
|
||||
check=True,
|
||||
)
|
||||
subprocess.run(
|
||||
[
|
||||
"git",
|
||||
"config",
|
||||
"--file",
|
||||
global_config,
|
||||
f"includeIf.gitdir:{metadata.as_posix()}.path",
|
||||
included.as_posix(),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(global_config))
|
||||
(source / "conditional.fixture").write_bytes(b"excluded by the selected Git directory\n")
|
||||
ignored = subprocess.check_output(
|
||||
["git", "-C", source, "check-ignore", "conditional.fixture"]
|
||||
)
|
||||
assert ignored.strip()
|
||||
patch = b"diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-before\n+after\n"
|
||||
scan = write_reviewed_patch(tmp_path, source, patch, revision)
|
||||
_, digest = workbench_db.remediation_checkout_snapshot(scan)
|
||||
remediation = reviewed_remediation(patch, revision, digest)
|
||||
selected_file = source / "file.txt"
|
||||
selected_file.write_bytes(b"after\n")
|
||||
_, applied_digest = workbench_db.remediation_checkout_snapshot(scan)
|
||||
verify = workbench_db.require_reviewed_patch_applied
|
||||
assert verify(scan, remediation, "reviewed.patch") == applied_digest
|
||||
assert selected_file.read_bytes() == b"after\n"
|
||||
selected_file.write_bytes(b"other\n")
|
||||
with pytest.raises(SystemExit, match="does not contain the reviewed remediation patch"):
|
||||
verify(scan, remediation, "reviewed.patch")
|
||||
assert selected_file.read_bytes() == b"other\n"
|
||||
selected_file.write_bytes(b"after\n")
|
||||
(source / "unrelated.txt").write_bytes(b"keep me\n")
|
||||
with pytest.raises(SystemExit, match="changes outside the reviewed patch"):
|
||||
verify(scan, remediation, "reviewed.patch")
|
||||
assert (source / "unrelated.txt").read_bytes() == b"keep me\n"
|
||||
(source / "unrelated.txt").unlink()
|
||||
malformed = b"not a patch\n"
|
||||
(tmp_path / "scan/reviewed.patch").write_bytes(malformed)
|
||||
with pytest.raises(SystemExit, match="does not contain the reviewed remediation patch"):
|
||||
verify(scan, reviewed_remediation(malformed, revision, digest), "reviewed.patch")
|
||||
assert marker.read_bytes() == original_marker
|
||||
assert selected_file.read_bytes() == b"after\n"
|
||||
|
||||
|
||||
@pytest.mark.native_windows
|
||||
@pytest.mark.skipif(os.name != "nt", reason="requires Windows directory and file sharing")
|
||||
def test_replay_gitfile_remains_bound_until_the_private_replay_is_removed(tmp_path: Path) -> None:
|
||||
import tempfile
|
||||
from contextlib import ExitStack
|
||||
|
||||
import windows_scan_local_files as windows
|
||||
import workbench_target
|
||||
|
||||
source = tmp_path / "source"
|
||||
foreign = tmp_path / "foreign"
|
||||
initialize_git_repository(source)
|
||||
initialize_git_repository(foreign)
|
||||
metadata = source / ".git"
|
||||
stages = tmp_path / "replays"
|
||||
stages.mkdir()
|
||||
|
||||
def interrupt_replay():
|
||||
with tempfile.TemporaryDirectory(dir=stages) as temporary, ExitStack() as pins:
|
||||
scratch = Path(temporary)
|
||||
checkout = scratch / "checkout"
|
||||
checkout.mkdir()
|
||||
(checkout / ".git").write_bytes(f"gitdir: {(foreign / '.git').as_posix()}\n".encode())
|
||||
assert windows.pin_replay_metadata(pins, metadata, scratch) == metadata
|
||||
with pytest.raises(PermissionError):
|
||||
scratch.rename(stages / "elsewhere")
|
||||
short = pins.enter_context(windows.pinned_replay_gitfile(checkout, metadata))
|
||||
assert (
|
||||
Path(
|
||||
workbench_target.git_output(
|
||||
checkout,
|
||||
"rev-parse",
|
||||
"--absolute-git-dir",
|
||||
git_dir=short,
|
||||
work_tree=checkout,
|
||||
)
|
||||
)
|
||||
== metadata
|
||||
)
|
||||
with pytest.raises(PermissionError):
|
||||
(checkout / short).write_bytes(b"other")
|
||||
for path in (metadata, checkout, scratch, checkout / short):
|
||||
with pytest.raises(PermissionError):
|
||||
path.rename(path.with_name("replaced"))
|
||||
raise KeyboardInterrupt
|
||||
|
||||
with pytest.raises(KeyboardInterrupt):
|
||||
interrupt_replay()
|
||||
assert not list(stages.iterdir())
|
||||
assert metadata.is_dir() and (foreign / ".git").is_dir()
|
||||
|
||||
|
||||
@pytest.mark.native_windows
|
||||
@pytest.mark.skipif(os.name != "nt", reason="requires Windows regular-file and junction checks")
|
||||
@pytest.mark.parametrize(
|
||||
"change", ["foreign-pointer", "changed-patch", "replaced-parent", "writable-scratch"]
|
||||
)
|
||||
def test_short_git_reference_refuses_changed_replay_inputs(
|
||||
tmp_path: Path, change: str, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from contextlib import ExitStack
|
||||
|
||||
import windows_scan_local_files as windows
|
||||
import workbench_remediation
|
||||
|
||||
metadata, scratch = tmp_path / "metadata", tmp_path / "scratch"
|
||||
metadata.mkdir()
|
||||
scratch.mkdir()
|
||||
worktree = scratch / "checkout"
|
||||
worktree.mkdir()
|
||||
patch = scratch / "reviewed.patch"
|
||||
patch.write_bytes(b"expected")
|
||||
expected = "sha256:" + hashlib.sha256(patch.read_bytes()).hexdigest()
|
||||
marker = scratch / "reviewed.git"
|
||||
if change == "foreign-pointer":
|
||||
marker.write_bytes(b"gitdir: foreign\n")
|
||||
elif change == "changed-patch":
|
||||
patch.write_bytes(b"changed")
|
||||
elif change == "replaced-parent":
|
||||
alias = tmp_path / "alias"
|
||||
subprocess.run(["cmd", "/c", "mklink", "/J", str(alias), str(scratch)], check=True)
|
||||
worktree = alias / "checkout"
|
||||
else:
|
||||
subprocess.run(["icacls.exe", str(scratch), "/grant", "*S-1-1-0:(WD)"], check=True)
|
||||
failed = subprocess.CompletedProcess([], 128, b"", b"fatal: '$GIT_DIR' too big\n")
|
||||
monkeypatch.setattr(workbench_remediation, "git_command", lambda *args, **kwargs: failed)
|
||||
with ExitStack() as pins:
|
||||
selected = windows.pin_replay_metadata(pins, metadata, scratch)
|
||||
if change == "writable-scratch":
|
||||
assert selected is None
|
||||
with pytest.raises(SystemExit, match="Could not bind"):
|
||||
workbench_remediation.reverse_reviewed_patch(
|
||||
tmp_path, worktree, metadata, selected, expected, pins, patch, "."
|
||||
)
|
||||
assert not marker.exists()
|
||||
return
|
||||
with pytest.raises(SystemExit, match="Could not verify|Patch digest does not match"):
|
||||
workbench_remediation.reverse_reviewed_patch(
|
||||
tmp_path, worktree, metadata, selected, expected, pins, patch, "."
|
||||
)
|
||||
if change == "foreign-pointer":
|
||||
assert marker.read_bytes() == b"gitdir: foreign\n"
|
||||
if change == "replaced-parent":
|
||||
assert not marker.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("git_repository", "git_exclusion"),
|
||||
[
|
||||
@@ -310,6 +525,7 @@ def test_versioned_reviewed_patch_preserves_nested_junctions(
|
||||
populated: bool,
|
||||
) -> None:
|
||||
import workbench_db
|
||||
import workbench_remediation
|
||||
|
||||
repository = tmp_path / "repository"
|
||||
initialize_git_repository(repository)
|
||||
@@ -327,7 +543,7 @@ def test_versioned_reviewed_patch_preserves_nested_junctions(
|
||||
junction = nested / "linked"
|
||||
junction_factory(junction, outside)
|
||||
relative_junction = junction.relative_to(repository)
|
||||
original_command = workbench_db.git_command
|
||||
original_command = workbench_remediation.git_command
|
||||
original_restore = workbench_db.restore_directory_junctions
|
||||
reversed_roots: list[Path] = []
|
||||
restored: list[Path] = []
|
||||
@@ -351,7 +567,7 @@ def test_versioned_reviewed_patch_preserves_nested_junctions(
|
||||
original_restore(source, destination, junctions)
|
||||
restored.append(destination)
|
||||
|
||||
monkeypatch.setattr(workbench_db, "git_command", command)
|
||||
monkeypatch.setattr(workbench_remediation, "git_command", command)
|
||||
monkeypatch.setattr(workbench_db, "restore_directory_junctions", restore)
|
||||
assert_reviewed_change(
|
||||
target,
|
||||
@@ -511,10 +727,43 @@ def test_reviewed_patch_restores_junction_git_context(
|
||||
assert (source / patched).read_bytes() == after.replace("\n", newline).encode()
|
||||
|
||||
|
||||
@pytest.mark.cross_platform
|
||||
def test_reviewed_patch_preserves_scoped_unborn_lf_bytes(tmp_path: Path) -> None:
|
||||
@pytest.mark.parametrize(
|
||||
"short_reference",
|
||||
[
|
||||
pytest.param(False, marks=pytest.mark.cross_platform),
|
||||
pytest.param(
|
||||
True,
|
||||
marks=[
|
||||
pytest.mark.native_windows,
|
||||
pytest.mark.skipif(os.name != "nt", reason="requires Windows replay binding"),
|
||||
],
|
||||
),
|
||||
],
|
||||
ids=["ordinary", "short-reference"],
|
||||
)
|
||||
def test_reviewed_patch_preserves_scoped_unborn_lf_bytes(
|
||||
tmp_path: Path, short_reference: bool, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
import workbench_remediation
|
||||
|
||||
repository = tmp_path / "repository"
|
||||
initialize_unborn_git_repository(repository)
|
||||
references = []
|
||||
reverse = workbench_remediation.reverse_reviewed_patch
|
||||
git = workbench_remediation.git_command
|
||||
|
||||
def record_references(*args, **kwargs):
|
||||
selected = reverse(*args, **kwargs)
|
||||
references.append(selected)
|
||||
return selected
|
||||
|
||||
def require_short_reference(target, *args, **kwargs):
|
||||
if short_reference and kwargs.get("git_dir") == repository / ".git":
|
||||
return subprocess.CompletedProcess([], 128, b"", b"fatal: '$GIT_DIR' too big\n")
|
||||
return git(target, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(workbench_remediation, "reverse_reviewed_patch", record_references)
|
||||
monkeypatch.setattr(workbench_remediation, "git_command", require_short_reference)
|
||||
attributes = tmp_path / "attributes"
|
||||
attributes.write_text("*.txt text eol=crlf\n")
|
||||
subprocess.run(
|
||||
@@ -526,6 +775,8 @@ def test_reviewed_patch_preserves_scoped_unborn_lf_bytes(tmp_path: Path) -> None
|
||||
assert_reviewed_change(source, tmp_path, "app.txt", "before\n", "after\n", newline="\n")
|
||||
|
||||
assert (source / "app.txt").read_bytes() == b"after\n"
|
||||
if short_reference:
|
||||
assert references[0][0] is not None
|
||||
|
||||
|
||||
def assert_reviewed_change(
|
||||
@@ -1166,13 +1417,17 @@ def test_windows_directory_query_preserves_exclusions_with_inherited_noglob(
|
||||
assert dict(os.environ) == environment
|
||||
|
||||
|
||||
def test_directory_content_digest_uses_git_file_set(tmp_path: Path) -> None:
|
||||
@pytest.mark.parametrize("pathspec_mode", ["GIT_GLOB_PATHSPECS", "GIT_ICASE_PATHSPECS"])
|
||||
def test_directory_content_digest_uses_git_file_set(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, pathspec_mode: str
|
||||
) -> None:
|
||||
target = tmp_path / "target"
|
||||
initialize_unborn_git_repository(target)
|
||||
(target / ".gitignore").write_text("ignored-cache/\n")
|
||||
source = target / "app.py"
|
||||
source.write_text("print('fixture')\n")
|
||||
original_digest = directory_content_digest(target)
|
||||
monkeypatch.setenv(pathspec_mode, "1")
|
||||
|
||||
source.write_text("print('changed')\n")
|
||||
assert directory_content_digest(target) != original_digest
|
||||
@@ -1316,6 +1571,184 @@ def test_directory_content_digest_skips_missing_cached_paths(tmp_path: Path) ->
|
||||
assert directory_content_digest(target) == original_digest
|
||||
|
||||
|
||||
@pytest.mark.cross_platform
|
||||
@pytest.mark.parametrize(
|
||||
("option", "value"),
|
||||
[
|
||||
("color.ui", "always"),
|
||||
("color.diff", "always"),
|
||||
("diff.noprefix", "true"),
|
||||
("diff.mnemonicPrefix", "true"),
|
||||
("diff.context", "0"),
|
||||
("diff.algorithm", "histogram"),
|
||||
("diff.indentHeuristic", "false"),
|
||||
("diff.interHunkContext", "20"),
|
||||
("diff.suppressBlankEmpty", "true"),
|
||||
("diff.orderFile", "order"),
|
||||
("diff.renames", "false"),
|
||||
("diff.renameLimit", "1"),
|
||||
("core.quotePath", "false"),
|
||||
("GIT_DIFF_OPTS", "--unified=0"),
|
||||
],
|
||||
)
|
||||
def test_git_diff_display_settings_preserve_selected_working_content(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
workbench_api: dict[str, Any],
|
||||
option: str,
|
||||
value: str,
|
||||
) -> None:
|
||||
target = tmp_path / "source"
|
||||
initialize_git_repository(target)
|
||||
path = target / "café.txt"
|
||||
path.write_bytes(b"heading\none\nC\nB\nB\nthree\n")
|
||||
lines = target / "z-lines.txt"
|
||||
original_lines = ["start", "", *(f"line {n}" for n in range(20)), "end"]
|
||||
lines.write_text("\n".join(original_lines) + "\n", encoding="utf-8")
|
||||
indent = target / "indent.txt"
|
||||
indent.write_bytes(b"\ndone()\ndef sample():\n")
|
||||
moved = [("first.txt", "new-first.txt"), ("second.txt", "new-second.txt")]
|
||||
for name, _ in moved:
|
||||
(target / name).write_text(
|
||||
"".join(f"{name} line {n}\n" for n in range(20)), encoding="utf-8"
|
||||
)
|
||||
subprocess.run(["git", "add", "--", "."], cwd=target, check=True)
|
||||
subprocess.run(["git", "commit", "-qm", "Track fixture"], cwd=target, check=True)
|
||||
indent.write_bytes(b"\ndone()\ndone()\ndef sample():\n")
|
||||
for name, destination in moved:
|
||||
subprocess.run(["git", "mv", name, destination], cwd=target, check=True)
|
||||
with (target / destination).open("ab") as stream:
|
||||
stream.write(b"added line\n")
|
||||
subprocess.run(["git", "add", "--", destination], cwd=target, check=True)
|
||||
path.write_bytes(b"heading\none\nB\nC\nC\nthree\n")
|
||||
original_lines[0] = "changed start"
|
||||
original_lines[-1] = "changed end"
|
||||
lines.write_text("\n".join(original_lines) + "\n", encoding="utf-8")
|
||||
if option == "diff.orderFile":
|
||||
order_file = tmp_path / "diff order"
|
||||
order_file.write_text(lines.name + "\n", encoding="utf-8", newline="\n")
|
||||
value = str(order_file)
|
||||
selected = workbench_api["require_diff_target"](target, "working_tree", None, None, None)
|
||||
if option == "GIT_DIFF_OPTS":
|
||||
monkeypatch.setenv(option, value)
|
||||
else:
|
||||
subprocess.run(["git", "config", "--local", option, value], cwd=target, check=True)
|
||||
|
||||
# Reproduce a stored digest generated by a previous version with this setting.
|
||||
old_patch = subprocess.check_output(
|
||||
["git", "diff", "--binary", "--full-index", "--no-ext-diff", "--no-textconv", "HEAD"],
|
||||
cwd=target,
|
||||
)
|
||||
old_hash = hashlib.sha256()
|
||||
update_digest_field(old_hash, b"format", b"codex-security-snapshot/v1")
|
||||
update_digest_field(old_hash, b"tracked-diff", old_patch)
|
||||
legacy = f"codex-security-snapshot/v1:sha256:{old_hash.hexdigest()}"
|
||||
assert legacy != selected["contentDigest"]
|
||||
|
||||
def validate(digest: str | None) -> str:
|
||||
return workbench_api["require_diff_target"](target, "working_tree", None, None, digest)[
|
||||
"contentDigest"
|
||||
]
|
||||
|
||||
assert validate(None) == selected["contentDigest"]
|
||||
assert validate(selected["contentDigest"]) == selected["contentDigest"]
|
||||
assert validate(legacy) == legacy
|
||||
|
||||
path.write_bytes(b"new source content\n")
|
||||
for digest in (selected["contentDigest"], legacy):
|
||||
with pytest.raises(SystemExit, match="contents changed"):
|
||||
validate(digest)
|
||||
|
||||
|
||||
@pytest.mark.cross_platform
|
||||
@pytest.mark.parametrize("display", ["log", "diff"])
|
||||
def test_git_submodule_display_preserves_selected_working_content(
|
||||
tmp_path: Path, workbench_api: dict[str, Any], display: str
|
||||
) -> None:
|
||||
target = tmp_path / "parent"
|
||||
initialize_git_repository(target)
|
||||
child = target / "submodule"
|
||||
initial = initialize_git_repository(child)
|
||||
add_submodule_gitlink(target, initial, ".")
|
||||
subprocess.run(["git", "commit", "-qm", "Pin child"], cwd=target, check=True)
|
||||
|
||||
def advance_child(content: str) -> None:
|
||||
(child / "README.md").write_text(content + "\n", encoding="utf-8")
|
||||
subprocess.run(["git", "commit", "-qam", content], cwd=child, check=True)
|
||||
subprocess.run(["git", "add", "--", "submodule"], cwd=target, check=True)
|
||||
|
||||
advance_child("Selected child")
|
||||
require_target = workbench_api["require_diff_target"]
|
||||
selected = require_target(target, "working_tree", None, None, None)["contentDigest"]
|
||||
diff = ["git", "diff", "HEAD", "--", "submodule"]
|
||||
original = subprocess.check_output(diff, cwd=target)
|
||||
subprocess.run(["git", "config", "--local", "diff.submodule", display], cwd=target, check=True)
|
||||
configured = subprocess.check_output(diff, cwd=target)
|
||||
assert configured != original
|
||||
assert require_target(target, "working_tree", None, None, selected)["contentDigest"] == selected
|
||||
|
||||
advance_child("Changed child")
|
||||
with pytest.raises(SystemExit, match="contents changed"):
|
||||
require_target(target, "working_tree", None, None, selected)
|
||||
|
||||
|
||||
@pytest.mark.cross_platform
|
||||
@pytest.mark.parametrize(
|
||||
("key", "value", "binary"),
|
||||
[
|
||||
("diff.python.xfuncname", "^class.*$", False),
|
||||
("diff.python.binary", "true", False),
|
||||
("diff.Mixed=driver.binary", "true", False),
|
||||
("diff.python.binary", "false", True),
|
||||
("core.compression", "0", True),
|
||||
],
|
||||
)
|
||||
def test_git_driver_settings_preserve_selected_working_content(
|
||||
tmp_path: Path, workbench_api: dict[str, Any], key: str, value: str, binary: bool
|
||||
) -> None:
|
||||
target = tmp_path / "source"
|
||||
initialize_git_repository(target)
|
||||
driver = "Mixed=driver" if key == "diff.Mixed=driver.binary" else "python"
|
||||
(target / ".gitattributes").write_bytes(f"*.py diff={driver}\n".encode())
|
||||
source = target / "example.py"
|
||||
initial = (
|
||||
b"class Example:\n def sample(self):\n"
|
||||
+ b"".join(f" a = {n}\n".encode() for n in range(24))
|
||||
+ (b"\0" + b"abcde" * 4096 if binary else b"")
|
||||
)
|
||||
source.write_bytes(initial)
|
||||
subprocess.run(["git", "add", "--", "."], cwd=target, check=True)
|
||||
subprocess.run(["git", "commit", "-qm", "Track example"], cwd=target, check=True)
|
||||
source.write_bytes(initial.replace(b"a = 15", b"a = 42"))
|
||||
require_target = workbench_api["require_diff_target"]
|
||||
selected = require_target(target, "working_tree", None, None, None)["contentDigest"]
|
||||
args = ["git", "diff", "--binary", "--full-index", "HEAD"]
|
||||
original = subprocess.check_output(args, cwd=target)
|
||||
subprocess.run(["git", "config", "--local", key, value], cwd=target, check=True)
|
||||
configured = subprocess.check_output(args, cwd=target)
|
||||
assert configured != original
|
||||
assert require_target(target, "working_tree", None, None, selected)["contentDigest"] == selected
|
||||
assert require_target(target, "working_tree", None, None, None)["contentDigest"] == selected
|
||||
legacy_hash = hashlib.sha256()
|
||||
update_digest_field(legacy_hash, b"format", b"codex-security-snapshot/v1")
|
||||
update_digest_field(legacy_hash, b"tracked-diff", configured)
|
||||
legacy = f"codex-security-snapshot/v1:sha256:{legacy_hash.hexdigest()}"
|
||||
assert require_target(target, "working_tree", None, None, legacy)["contentDigest"] == legacy
|
||||
source.write_bytes(initial + b"actual change\n")
|
||||
for digest in (selected, legacy):
|
||||
with pytest.raises(SystemExit, match="contents changed"):
|
||||
require_target(target, "working_tree", None, None, digest)
|
||||
|
||||
|
||||
def test_snapshot_keeps_hunk_coordinates_and_long_source_lines() -> None:
|
||||
header = b"@@ -12,4 +12,5 @@"
|
||||
# The next read starts with a header-shaped string in the middle of an added line.
|
||||
long_line = b"+" + b"x" * (1024 * 1024 - 1) + header + b" literal content\n"
|
||||
patch = header + b" def sample():\n" + long_line + header + b"\n"
|
||||
chunks = WORKBENCH_TARGET["_canonical_patch_chunks"](io.BytesIO(patch))
|
||||
assert b"".join(chunks) == header + b"\n" + long_line + header + b"\n"
|
||||
|
||||
|
||||
def test_worktree_content_digest_streams_tracked_binary_patch(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
@@ -1720,7 +2153,9 @@ def test_root_git_marker_declines_unsupported_paths_without_opening_directories(
|
||||
) -> None:
|
||||
import windows_scan_local_files as windows_files
|
||||
|
||||
monkeypatch.setattr(windows_files, "_GetDriveTypeW", lambda _anchor: 3)
|
||||
monkeypatch.setattr(
|
||||
windows_files, "_GetDriveTypeW", lambda anchor: 4 if anchor == "D:\\" else 3
|
||||
)
|
||||
|
||||
def unexpected_open(*_args, **_kwargs):
|
||||
pytest.fail("unsupported paths must be declined before opening directories")
|
||||
@@ -1728,6 +2163,7 @@ def test_root_git_marker_declines_unsupported_paths_without_opening_directories(
|
||||
monkeypatch.setattr(windows_files, "_open_directory", unexpected_open)
|
||||
for target, metadata in (
|
||||
(r"C:\repo", r"D:\metadata"),
|
||||
(r"C:\repo", r"\\server.invalid\share\metadata"),
|
||||
(r"\\?\C:\repo", r"\\?\C:\metadata"),
|
||||
(r"\\server.invalid\share\repo", r"\\server.invalid\share\metadata"),
|
||||
(r"C:checkout", r"C:\metadata"),
|
||||
@@ -1741,6 +2177,52 @@ def test_root_git_marker_declines_unsupported_paths_without_opening_directories(
|
||||
assert selected is None
|
||||
|
||||
|
||||
@pytest.mark.native_windows
|
||||
@pytest.mark.skipif(os.name != "nt", reason="requires Windows drive semantics")
|
||||
def test_root_git_marker_pins_the_checkout_and_metadata_on_independent_fixed_drives(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import windows_scan_local_files as windows_files
|
||||
|
||||
root, metadata = Path(r"C:\worktree"), Path(r"D:\metadata")
|
||||
scope = root / "selected"
|
||||
marker = tmp_path / "gitfile"
|
||||
marker.write_bytes(f"gitdir: {metadata.as_posix()}\n".encode())
|
||||
drives = []
|
||||
opened = []
|
||||
|
||||
def fixed_drive(anchor):
|
||||
drives.append(anchor)
|
||||
return 3
|
||||
|
||||
def open_fixture(path):
|
||||
opened.append(path)
|
||||
return MagicMock(value=path)
|
||||
|
||||
monkeypatch.setattr(windows_files, "_GetDriveTypeW", fixed_drive)
|
||||
monkeypatch.setattr(windows_files, "_open_directory", open_fixture)
|
||||
|
||||
monkeypatch.setattr(windows_files, "_final_path", windows_files._extended_path)
|
||||
|
||||
def open_marker(parent, name, context):
|
||||
assert (parent, name) == (root, ".git")
|
||||
return os.open(marker, os.O_RDONLY | os.O_BINARY), name
|
||||
|
||||
monkeypatch.setattr(windows_files, "open_read_fd_with_path", open_marker)
|
||||
with windows_files.pinned_root_git_marker(scope, metadata, work_tree=root) as selected:
|
||||
assert selected == Path("..", ".git")
|
||||
assert opened == [
|
||||
Path(root.anchor),
|
||||
root,
|
||||
scope,
|
||||
Path(metadata.anchor),
|
||||
metadata,
|
||||
]
|
||||
assert set(drives) == {root.anchor, metadata.anchor}
|
||||
|
||||
|
||||
@pytest.mark.native_windows
|
||||
@pytest.mark.skipif(os.name != "nt", reason="requires Windows directory junctions")
|
||||
@pytest.mark.parametrize("inside_scope", [False, True])
|
||||
|
||||
Generated
+8
-8
@@ -700,8 +700,8 @@ packages:
|
||||
safer-buffer@2.1.2:
|
||||
resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
|
||||
|
||||
semver@7.8.5:
|
||||
resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==}
|
||||
semver@7.8.6:
|
||||
resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==}
|
||||
engines: {node: '>=10'}
|
||||
hasBin: true
|
||||
|
||||
@@ -822,7 +822,7 @@ snapshots:
|
||||
import-meta-resolve: 4.2.0
|
||||
json5: 2.2.3
|
||||
obug: 2.1.4
|
||||
semver: 7.8.5
|
||||
semver: 7.8.6
|
||||
|
||||
'@babel/generator@8.0.0':
|
||||
dependencies:
|
||||
@@ -843,7 +843,7 @@ snapshots:
|
||||
'@babel/helper-validator-option': 8.0.0
|
||||
browserslist: 4.28.9
|
||||
lru-cache: 11.5.2
|
||||
semver: 7.8.5
|
||||
semver: 7.8.6
|
||||
|
||||
'@babel/helper-create-class-features-plugin@8.0.1(@babel/core@8.0.1)':
|
||||
dependencies:
|
||||
@@ -854,7 +854,7 @@ snapshots:
|
||||
'@babel/helper-replace-supers': 8.0.1(@babel/core@8.0.1)
|
||||
'@babel/helper-skip-transparent-expression-wrappers': 8.0.0
|
||||
'@babel/traverse': 8.0.4
|
||||
semver: 7.8.5
|
||||
semver: 7.8.6
|
||||
|
||||
'@babel/helper-globals@8.0.0': {}
|
||||
|
||||
@@ -1210,7 +1210,7 @@ snapshots:
|
||||
npm-run-path: 6.0.0
|
||||
progress: 2.0.3
|
||||
rxjs: 7.8.2
|
||||
semver: 7.8.5
|
||||
semver: 7.8.6
|
||||
source-map: 0.7.6
|
||||
tree-kill: 1.2.2
|
||||
tslib: 2.8.1
|
||||
@@ -1233,7 +1233,7 @@ snapshots:
|
||||
'@stryker-mutator/api': 10.1.1
|
||||
'@stryker-mutator/util': 10.1.1
|
||||
angular-html-parser: 10.11.0
|
||||
semver: 7.8.5
|
||||
semver: 7.8.6
|
||||
tslib: 2.8.1
|
||||
weapon-regex: 2.0.5
|
||||
|
||||
@@ -1493,7 +1493,7 @@ snapshots:
|
||||
|
||||
safer-buffer@2.1.2: {}
|
||||
|
||||
semver@7.8.5: {}
|
||||
semver@7.8.6: {}
|
||||
|
||||
shebang-command@2.0.0:
|
||||
dependencies:
|
||||
|
||||
@@ -509,7 +509,8 @@ be clean and at the commit recorded by the parent.
|
||||
Committed-diff scans require a clean, full checkout at the requested head
|
||||
revision, including when using `--validate`. A different checkout revision or
|
||||
local changes are rejected before scanning; check out the requested head and
|
||||
commit or stash local changes before retrying.
|
||||
commit or stash local changes before retrying. The check also verifies tracked
|
||||
files marked `assume-unchanged` and preserves their Git index flags.
|
||||
|
||||
`--owner-suggestions` writes optional `owner-suggestions.json` after a completed
|
||||
committed Git scan, using the same checkout, model, and reasoning effort. Owner
|
||||
@@ -1113,6 +1114,10 @@ Python lookup: `--python` on commands that expose interpreter selection or SDK
|
||||
`pythonPath`, then
|
||||
`PYTHON`, the managed runtime, and `python3` or `python` on `PATH` (`py` also
|
||||
works on Windows). `CODEX_SECURITY_STATE_DIR` overrides `CODEX_HOME` for storage.
|
||||
On POSIX, `CODEX_CLI_PATH` and `PYTHON` preserve trailing whitespace in an
|
||||
explicit path that selects an executable. Use an absolute path or a `./`
|
||||
prefix for filenames beginning or ending in whitespace. Bare command names
|
||||
are trimmed before lookup.
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
|
||||
@@ -87,7 +87,7 @@
|
||||
"@inquirer/confirm": "6.3.5",
|
||||
"@inquirer/input": "5.1.9",
|
||||
"@inquirer/search": "4.3.6",
|
||||
"@linear/sdk": "100.0.0",
|
||||
"@linear/sdk": "101.0.0",
|
||||
"@octokit/core": "7.0.8",
|
||||
"@openai/codex": "0.167.0",
|
||||
"@openai/codex-sdk": "0.167.0",
|
||||
@@ -99,7 +99,7 @@
|
||||
"pdfjs-dist": "6.5.438",
|
||||
"react": "19.3.1",
|
||||
"saxes": "6.0.0",
|
||||
"semver": "7.8.5",
|
||||
"semver": "7.8.6",
|
||||
"smol-toml": "1.9.1",
|
||||
"string-width": "8.3.0",
|
||||
"strip-ansi": "7.2.0",
|
||||
|
||||
Generated
+10
-10
@@ -21,8 +21,8 @@ importers:
|
||||
specifier: 4.3.6
|
||||
version: 4.3.6(@types/node@26.6.6)
|
||||
'@linear/sdk':
|
||||
specifier: 100.0.0
|
||||
version: 100.0.0(graphql@17.0.2)
|
||||
specifier: 101.0.0
|
||||
version: 101.0.0(graphql@17.0.2)
|
||||
'@octokit/core':
|
||||
specifier: 7.0.8
|
||||
version: 7.0.8
|
||||
@@ -57,8 +57,8 @@ importers:
|
||||
specifier: 6.0.0
|
||||
version: 6.0.0
|
||||
semver:
|
||||
specifier: 7.8.5
|
||||
version: 7.8.5
|
||||
specifier: 7.8.6
|
||||
version: 7.8.6
|
||||
smol-toml:
|
||||
specifier: 1.9.1
|
||||
version: 1.9.1
|
||||
@@ -360,8 +360,8 @@ packages:
|
||||
'@jsdevtools/ono@7.1.3':
|
||||
resolution: {integrity: sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg==}
|
||||
|
||||
'@linear/sdk@100.0.0':
|
||||
resolution: {integrity: sha512-7+n+Xqo6yYtexeDfaFnmT9j7bapkKyjB5cV63STuG8N1Wnjb9vyhpwOpn+t0VE3emGE7ZNEu2Rz1FHSWD84raw==}
|
||||
'@linear/sdk@101.0.0':
|
||||
resolution: {integrity: sha512-pQMaZmh/ewEMR9QmSZDuY+5NQy+xYS3DJDjqLEqlqj35M71Xde9vMHuNijamDZGqG6CojtCSU6YjgIg14pw+1A==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
|
||||
'@modelcontextprotocol/server@2.0.0-alpha.4':
|
||||
@@ -934,8 +934,8 @@ packages:
|
||||
scheduler@0.28.0:
|
||||
resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==}
|
||||
|
||||
semver@7.8.5:
|
||||
resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==}
|
||||
semver@7.8.6:
|
||||
resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==}
|
||||
engines: {node: '>=10'}
|
||||
hasBin: true
|
||||
|
||||
@@ -1172,7 +1172,7 @@ snapshots:
|
||||
|
||||
'@jsdevtools/ono@7.1.3': {}
|
||||
|
||||
'@linear/sdk@100.0.0(graphql@17.0.2)':
|
||||
'@linear/sdk@101.0.0(graphql@17.0.2)':
|
||||
dependencies:
|
||||
'@graphql-typed-document-node/core': 3.2.0(graphql@17.0.2)
|
||||
transitivePeerDependencies:
|
||||
@@ -1641,7 +1641,7 @@ snapshots:
|
||||
|
||||
scheduler@0.28.0: {}
|
||||
|
||||
semver@7.8.5: {}
|
||||
semver@7.8.6: {}
|
||||
|
||||
signal-exit@3.0.7: {}
|
||||
|
||||
|
||||
+57
-13
@@ -281,6 +281,7 @@ import {
|
||||
prepareOutputDir,
|
||||
prepareScanRegistrationOutput,
|
||||
preparePersistentOutputRoot,
|
||||
prepareWindowsScanPluginZip,
|
||||
probeCodexSandbox,
|
||||
requireModelSafeOutputDir,
|
||||
requireOutputOutsideRepositories,
|
||||
@@ -289,11 +290,13 @@ import {
|
||||
preparePolicyOutputDirectory,
|
||||
resolveCodexCommand,
|
||||
resolvePluginPath,
|
||||
resolvePluginSource,
|
||||
resolvePluginPython,
|
||||
runWorkbench,
|
||||
setCodexSecurityCredentialLogout,
|
||||
type CodexCommand,
|
||||
type PluginInstall,
|
||||
type PluginZipSource,
|
||||
type ProcessEnvironment,
|
||||
type ScanArtifactRestorer,
|
||||
type WorkbenchCommandOptions,
|
||||
@@ -340,6 +343,7 @@ interface CodexClientLike {
|
||||
interface PreparedRuntime {
|
||||
codexHome: string;
|
||||
bootstrapWorkspace?: string;
|
||||
pluginZipSource?: PluginZipSource;
|
||||
configPath?: string;
|
||||
deepScanConfigDirectory?: string;
|
||||
deepScanConfigPath?: string;
|
||||
@@ -1341,6 +1345,9 @@ export class CodexSecurity {
|
||||
const validationPermissions = {
|
||||
...scanPermissions,
|
||||
filesystem: {
|
||||
...(process.platform === "win32"
|
||||
? { [inputs.repository]: { ".": "read" } }
|
||||
: {}),
|
||||
...(scanPermissions["filesystem"] as JsonObject),
|
||||
":workspace_roots": "read",
|
||||
...(runtime.deepScanConfigPath === undefined ||
|
||||
@@ -1977,7 +1984,10 @@ export class CodexSecurity {
|
||||
: [runtime.deepScanConfigPath]),
|
||||
...inputs.gitMetadataPaths,
|
||||
],
|
||||
await codexExecutableReadPaths(this.#codexCommand().command),
|
||||
[
|
||||
...(process.platform === "win32" ? policyReadRoots : []),
|
||||
...(await codexExecutableReadPaths(this.#codexCommand().command)),
|
||||
],
|
||||
ambientHome,
|
||||
);
|
||||
const { codex } = await this.#createSessionCodex(
|
||||
@@ -2194,6 +2204,7 @@ export class CodexSecurity {
|
||||
let scanDir = "";
|
||||
let targetPathsFile: string | null = null;
|
||||
let stagedPluginRoot: string | undefined;
|
||||
let stagedPluginDirectory: string | undefined;
|
||||
let knowledgeBase: PreparedKnowledgeBase | null = null;
|
||||
let costTracker: ScanCostTracker | null = null;
|
||||
let scanProgressTracker: ScanProgressTracker | null = null;
|
||||
@@ -2490,14 +2501,14 @@ export class CodexSecurity {
|
||||
);
|
||||
}
|
||||
// Windows grants directory reads to its sandbox account through inheritable
|
||||
// ACLs. Keep those grants on a disposable copy of the SDK's shipped plugin.
|
||||
// ACLs. Grant only disposable plugin content prepared for this scan.
|
||||
if (
|
||||
process.platform === "win32" &&
|
||||
this.config.pluginPath === undefined &&
|
||||
runtime.bootstrapWorkspace !== undefined &&
|
||||
this.#dependencies.hostedScan === undefined
|
||||
) {
|
||||
stagedPluginRoot = await mkdtemp(
|
||||
stagedPluginDirectory = stagedPluginRoot = await mkdtemp(
|
||||
join(runtime.bootstrapWorkspace, "bundled-plugin-"),
|
||||
);
|
||||
await copyPluginTree(
|
||||
@@ -2505,6 +2516,27 @@ export class CodexSecurity {
|
||||
stagedPluginRoot,
|
||||
signal,
|
||||
);
|
||||
} else if (runtime.pluginZipSource !== undefined) {
|
||||
const staged = await prepareWindowsScanPluginZip(
|
||||
runtime.pluginZipSource,
|
||||
scanDir,
|
||||
[
|
||||
runtimeHome,
|
||||
...(runtime.bootstrapWorkspace ? [runtime.bootstrapWorkspace] : []),
|
||||
await canonicalConfigPath(
|
||||
scanCodexHome(this.#dependencies.environment),
|
||||
),
|
||||
],
|
||||
(path) =>
|
||||
requireOutputOutsideRepositories(
|
||||
inputs.protectedRoots,
|
||||
path,
|
||||
"runtime",
|
||||
),
|
||||
signal,
|
||||
);
|
||||
stagedPluginDirectory = staged?.workspace;
|
||||
stagedPluginRoot = staged?.root;
|
||||
}
|
||||
const shellPluginRoot = stagedPluginRoot ?? runtime.plugin.pluginRoot;
|
||||
const skillName = skillNameFor(normalized, mode);
|
||||
@@ -4212,9 +4244,9 @@ export class CodexSecurity {
|
||||
for (const cleanup of await Promise.allSettled([
|
||||
knowledgeBase?.cleanup(),
|
||||
removeTargetPathsFile(targetPathsFile),
|
||||
stagedPluginRoot === undefined
|
||||
stagedPluginDirectory === undefined
|
||||
? undefined
|
||||
: cleanupSdkDirectory(stagedPluginRoot),
|
||||
: cleanupSdkDirectory(stagedPluginDirectory),
|
||||
savedProviderProfile?.cleanup(),
|
||||
])) {
|
||||
if (cleanup.status === "rejected") {
|
||||
@@ -4758,15 +4790,24 @@ export class CodexSecurity {
|
||||
environment[SAFETY_IDENTIFIER_ENV] = session.safetyIdentifier;
|
||||
}
|
||||
const sdkCodexConfig = structuredCodexConfig(config ?? sessionConfig);
|
||||
// Windows configures sandbox ACL access for named roots, including private sources.
|
||||
const sourceReadRoot =
|
||||
process.platform === "win32" && command === "scan"
|
||||
? runtimePaths["CODEX_SECURITY_REPOSITORY"]
|
||||
: undefined;
|
||||
// This snapshot outlives a Deep Scan when the client reuses its runtime.
|
||||
if (
|
||||
runtime.deepScanConfigPath !== undefined ||
|
||||
pluginReadRoot !== undefined
|
||||
pluginReadRoot !== undefined ||
|
||||
sourceReadRoot !== undefined
|
||||
) {
|
||||
configOverrides = [
|
||||
`permissions.${SCAN_PERMISSION_PROFILE}.filesystem=${inlineToml({
|
||||
":root": "read",
|
||||
":workspace_roots": "write",
|
||||
...(sourceReadRoot !== undefined
|
||||
? { [sourceReadRoot]: { ".": "read" } }
|
||||
: {}),
|
||||
...(pluginReadRoot === undefined
|
||||
? {}
|
||||
: { [pluginReadRoot]: { ".": "read" } }),
|
||||
@@ -5655,11 +5696,13 @@ export class CodexSecurity {
|
||||
await lstat(bootstrapWorkspace),
|
||||
bootstrapWorkspace,
|
||||
);
|
||||
const pluginRoot = await resolvePluginPath(
|
||||
this.config.pluginPath,
|
||||
bootstrapWorkspace,
|
||||
signal,
|
||||
);
|
||||
const { root: pluginRoot, zip: pluginZipSource } =
|
||||
await resolvePluginSource(
|
||||
this.config.pluginPath,
|
||||
bootstrapWorkspace,
|
||||
signal,
|
||||
process.platform === "win32",
|
||||
);
|
||||
const ambientHome = scanCodexHome(processEnvironment);
|
||||
const codexConfig = await preserveCodexSecurityPluginRegistration(
|
||||
codexHome,
|
||||
@@ -5702,6 +5745,7 @@ export class CodexSecurity {
|
||||
return {
|
||||
codexHome,
|
||||
bootstrapWorkspace,
|
||||
pluginZipSource,
|
||||
configPath,
|
||||
deepScanConfigDirectory,
|
||||
deepScanConfigPath,
|
||||
@@ -7013,7 +7057,7 @@ export function scanRuntimeCodexConfig(
|
||||
|
||||
function policyFilesystemPermissions(
|
||||
deniedPaths: readonly string[] = [],
|
||||
codexPaths: readonly string[] = [],
|
||||
readPaths: readonly string[] = [],
|
||||
ambientHome?: string,
|
||||
): JsonObject {
|
||||
const filesystem: JsonObject = {
|
||||
@@ -7021,7 +7065,7 @@ function policyFilesystemPermissions(
|
||||
[process.platform === "win32" ? ":root" : ":minimal"]: "read",
|
||||
":workspace_roots": "read",
|
||||
// Linux's sandbox re-executes Codex, including installations outside /usr.
|
||||
...Object.fromEntries(codexPaths.map((path) => [path, { ".": "read" }])),
|
||||
...Object.fromEntries(readPaths.map((path) => [path, { ".": "read" }])),
|
||||
// A scoped "." keeps native permission paths literal, including glob characters.
|
||||
...Object.fromEntries(deniedPaths.map((path) => [path, { ".": "deny" }])),
|
||||
};
|
||||
|
||||
@@ -9095,7 +9095,9 @@ async function assessPatchRisk(
|
||||
request.files === undefined
|
||||
? []
|
||||
: ["--", ...request.files.map((file) => file)];
|
||||
const root = await mkdtemp(join(tmpdir(), "codex-security-patch-risk-"));
|
||||
const root = await mkdtemp(
|
||||
join(await realpath(tmpdir()), "codex-security-patch-risk-"),
|
||||
);
|
||||
const patchPath = join(root, "patch.diff");
|
||||
try {
|
||||
const head =
|
||||
@@ -9168,7 +9170,9 @@ async function withPatchIndex<T>(
|
||||
git: (args: string[], input?: string) => Promise<string>,
|
||||
) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const root = await mkdtemp(join(tmpdir(), "codex-security-patch-tree-"));
|
||||
const root = await mkdtemp(
|
||||
join(await realpath(tmpdir()), "codex-security-patch-tree-"),
|
||||
);
|
||||
try {
|
||||
return await operation((args, input) =>
|
||||
dependencies.runRepositoryCommand("git", args, repository, {
|
||||
@@ -10466,6 +10470,7 @@ async function executeScan(
|
||||
let patchDaybreakFeatures: JsonObject = {};
|
||||
let selectedAuthentication: ScanAuthentication | null = null;
|
||||
let repository = "";
|
||||
let runningMockScan = false;
|
||||
let failed = false;
|
||||
let failure: unknown;
|
||||
try {
|
||||
@@ -11109,7 +11114,9 @@ async function executeScan(
|
||||
if (arguments_.dryRun) {
|
||||
preflight = await security.preflight(repository, options);
|
||||
} else {
|
||||
runningMockScan = arguments_.mock === true;
|
||||
result = await security.run(repository, options);
|
||||
runningMockScan = false;
|
||||
scanDir = result.scanDir;
|
||||
repository = resolve(dependencies.currentDirectory(), repository);
|
||||
if (arguments_.validate) {
|
||||
@@ -11307,7 +11314,9 @@ async function executeScan(
|
||||
if (failed) {
|
||||
const costLimitFailure =
|
||||
failure instanceof ScanCostLimitExceededError ? failure : undefined;
|
||||
const classification = classifyScanFailure(failure);
|
||||
const classification = runningMockScan
|
||||
? "local"
|
||||
: classifyScanFailure(failure);
|
||||
const message =
|
||||
failure instanceof OutputInsideProtectedRootError
|
||||
? errorMessage(protectedRootErrorMessage(failure))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/* Generated from plugin executable-path.ts. Run `pnpm generate:models`. */
|
||||
import { accessSync, constants, statSync } from "node:fs";
|
||||
import { win32 } from "node:path";
|
||||
|
||||
export function executablePathForSpawn(command: string): string {
|
||||
@@ -10,3 +11,38 @@ export function executablePathForSpawn(command: string): string {
|
||||
? command
|
||||
: win32.toNamespacedPath(command);
|
||||
}
|
||||
|
||||
export function isExecutableFile(value: string): boolean {
|
||||
try {
|
||||
if (!statSync(value).isFile()) return false;
|
||||
accessSync(value, constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isExplicitPathWithTrailingWhitespace(
|
||||
value: string,
|
||||
platform: NodeJS.Platform,
|
||||
): boolean {
|
||||
// Bare names keep their usual PATH precedence. Leading padding can change the path's root.
|
||||
return (
|
||||
platform !== "win32" &&
|
||||
value.includes("/") &&
|
||||
value.trimStart() === value &&
|
||||
value.trimEnd() !== value
|
||||
);
|
||||
}
|
||||
|
||||
export function configuredExecutableValue(
|
||||
value: string | undefined,
|
||||
platform: NodeJS.Platform,
|
||||
literalIsExecutable: (value: string) => boolean,
|
||||
): string | undefined {
|
||||
return value &&
|
||||
isExplicitPathWithTrailingWhitespace(value, platform) &&
|
||||
literalIsExecutable(value)
|
||||
? value
|
||||
: value?.trim();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
@@ -17,7 +17,9 @@ export async function prepareFindingPrompt(
|
||||
if (characterCount(prompt) <= MAX_CODEX_INPUT_CHARACTERS)
|
||||
return { prompt, async [Symbol.asyncDispose]() {} };
|
||||
|
||||
const directory = await mkdtemp(join(tmpdir(), "codex-security-finding-"));
|
||||
const directory = await mkdtemp(
|
||||
join(await realpath(tmpdir()), "codex-security-finding-"),
|
||||
);
|
||||
const cleanup = async () => {
|
||||
// Cleanup must not replace a completed result or the original failure.
|
||||
await rm(directory, { recursive: true, force: true }).catch(() => {});
|
||||
|
||||
@@ -154,7 +154,7 @@ export async function prepareKnowledgeBase(
|
||||
: await readKnowledgeBaseSnapshot(input, signal);
|
||||
const protectedRoots = await knowledgeBaseProtectedRoots(snapshot, signal);
|
||||
const path = await mkdtemp(
|
||||
join(directory ?? tmpdir(), "codex-security-knowledge-"),
|
||||
join(await realpath(directory ?? tmpdir()), "codex-security-knowledge-"),
|
||||
);
|
||||
try {
|
||||
for (const [filename, text] of Object.entries(snapshot.documents)) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { parseJson } from "./value.js";
|
||||
import type { webcrypto } from "node:crypto";
|
||||
import {
|
||||
AuthenticationLinearError,
|
||||
ForbiddenLinearError,
|
||||
@@ -8,6 +9,16 @@ import {
|
||||
import type { JsonObject } from "./config.js";
|
||||
import { CodexSecurityError, errorMessage } from "./errors.js";
|
||||
|
||||
// Linear's DPoP declarations use these global types even for Node-only clients.
|
||||
type NodeOnlyWebCrypto<T> = typeof globalThis extends { onmessage: unknown }
|
||||
? {}
|
||||
: T;
|
||||
|
||||
declare global {
|
||||
interface JsonWebKey extends NodeOnlyWebCrypto<webcrypto.JsonWebKey> {}
|
||||
interface CryptoKeyPair extends NodeOnlyWebCrypto<webcrypto.CryptoKeyPair> {}
|
||||
}
|
||||
|
||||
export type LinearClientFactory<
|
||||
Method extends keyof LinearClient = "issue" | "projects",
|
||||
> = (
|
||||
|
||||
+396
-66
@@ -1,4 +1,9 @@
|
||||
import { executablePathForSpawn } from "./executable-path.js";
|
||||
import {
|
||||
configuredExecutableValue,
|
||||
executablePathForSpawn,
|
||||
isExplicitPathWithTrailingWhitespace,
|
||||
isExecutableFile,
|
||||
} from "./executable-path.js";
|
||||
import { retryWindowsRename } from "./retry-windows-rename.js";
|
||||
export { executablePathForSpawn } from "./executable-path.js";
|
||||
import {
|
||||
@@ -7,7 +12,7 @@ import {
|
||||
PLUGIN_PYTHON_READY,
|
||||
} from "./plugin-python-probe.js";
|
||||
import { resolveBundledCodexExecutable } from "./codex-sdk-environment.js";
|
||||
import { gitProtectionRoots } from "./targets.js";
|
||||
import { abortable, gitProtectionRoots } from "./targets.js";
|
||||
import { isNonEmptyString, notify } from "./value.js";
|
||||
import {
|
||||
execFile as execFileCallback,
|
||||
@@ -15,7 +20,7 @@ import {
|
||||
type ChildProcessWithoutNullStreams,
|
||||
type SpawnOptionsWithoutStdio,
|
||||
} from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { createHash, randomUUID, type Hash } from "node:crypto";
|
||||
import { shortArchivePrefix } from "./scan-archive-path.js";
|
||||
import {
|
||||
chmodSync,
|
||||
@@ -36,6 +41,7 @@ import {
|
||||
lstat,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
open,
|
||||
readFile,
|
||||
readdir,
|
||||
realpath,
|
||||
@@ -244,7 +250,11 @@ function environmentValue(
|
||||
export function codexSecurityStateDirectory(
|
||||
environment: ProcessEnvironment = process.env,
|
||||
): string {
|
||||
const configured = environmentValue(environment, "CODEX_SECURITY_STATE_DIR");
|
||||
const configured = environmentValue(
|
||||
environment,
|
||||
"CODEX_SECURITY_STATE_DIR",
|
||||
process.platform !== "win32",
|
||||
);
|
||||
const path =
|
||||
configured !== undefined
|
||||
? resolve(expandHome(configured, environment))
|
||||
@@ -2042,11 +2052,13 @@ export async function runWorkbench(
|
||||
)
|
||||
: input,
|
||||
signal,
|
||||
registrationHandshake,
|
||||
// Frame Python arguments on stdin to preserve NUL and long diagnostics.
|
||||
native
|
||||
? undefined
|
||||
: `${JSON.stringify(arguments_.map((argument) => argument.toWellFormed()))}\n`,
|
||||
{
|
||||
registrationHandshake,
|
||||
// Frame Python arguments on stdin to preserve NUL and long diagnostics.
|
||||
stdinPrefix: native
|
||||
? undefined
|
||||
: `${JSON.stringify(arguments_.map((argument) => argument.toWellFormed()))}\n`,
|
||||
},
|
||||
);
|
||||
if (!result.success) {
|
||||
throw new Error(
|
||||
@@ -2819,11 +2831,26 @@ export async function extractPluginZip(
|
||||
archive: string,
|
||||
destination: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
return extractValidatedPluginZip(archive, destination, signal);
|
||||
}
|
||||
|
||||
async function extractValidatedPluginZip(
|
||||
archive: string,
|
||||
destination: string,
|
||||
signal?: AbortSignal,
|
||||
digest?: Hash,
|
||||
): Promise<string> {
|
||||
const archivePath = resolve(expandHome(archive));
|
||||
await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
|
||||
const parent = dirname(destination);
|
||||
await mkdir(parent, { recursive: true, mode: 0o700 });
|
||||
// Windows mkdtemp otherwise fails at 248 UTF-16 units, including its suffix.
|
||||
const stagingParent =
|
||||
process.platform === "win32"
|
||||
? win32.toNamespacedPath(await realpath(parent))
|
||||
: parent;
|
||||
const staging = await realpath(
|
||||
await mkdtemp(join(dirname(destination), ".codex-security-plugin-")),
|
||||
await mkdtemp(join(stagingParent, ".codex-security-plugin-")),
|
||||
);
|
||||
let publishingOnWindows = false;
|
||||
try {
|
||||
@@ -2874,6 +2901,7 @@ export async function extractPluginZip(
|
||||
const output = join(staging, ...path.split("/"));
|
||||
const entryMode = (entry.externalFileAttributes >>> 16) & 0xffff;
|
||||
const permissions = (entryMode || (directory ? 0o700 : 0o600)) & 0o777;
|
||||
digest?.update(JSON.stringify([path, directory, permissions]));
|
||||
await mkdir(directory ? output : dirname(output), {
|
||||
recursive: true,
|
||||
...(directory ? { mode: permissions } : {}),
|
||||
@@ -2898,6 +2926,7 @@ export async function extractPluginZip(
|
||||
`Plugin ZIP entry failed CRC-32 validation: ${path}`,
|
||||
);
|
||||
}
|
||||
digest?.update(createHash("sha256").update(bytes).digest());
|
||||
}
|
||||
const pluginRoot = await discoverPluginRoot(staging);
|
||||
throwIfSignalAborted(signal);
|
||||
@@ -3036,23 +3065,46 @@ export async function resolvePluginPath(
|
||||
workspace: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
return (await resolvePluginSource(pluginPath, workspace, signal)).root;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export interface PluginZipSource {
|
||||
path: string;
|
||||
digest: string;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export async function resolvePluginSource(
|
||||
pluginPath: string | undefined,
|
||||
workspace: string,
|
||||
signal?: AbortSignal,
|
||||
pinZip = false,
|
||||
): Promise<{ root: string; zip?: PluginZipSource }> {
|
||||
try {
|
||||
if (pluginPath === undefined) {
|
||||
return await bundledPluginRoot();
|
||||
return { root: await bundledPluginRoot() };
|
||||
}
|
||||
|
||||
const path = resolve(expandHome(pluginPath));
|
||||
const metadata = await lstat(path).catch(() => null);
|
||||
if (metadata?.isFile() && extname(path).toLowerCase() === ".zip") {
|
||||
return await extractPluginZip(
|
||||
path,
|
||||
const digest = pinZip ? createHash("sha256") : undefined;
|
||||
const archive = digest ? await realpath(path) : path;
|
||||
const root = await extractValidatedPluginZip(
|
||||
archive,
|
||||
join(workspace, "extracted-plugin"),
|
||||
signal,
|
||||
digest,
|
||||
);
|
||||
return {
|
||||
root,
|
||||
...(digest && { zip: { path: archive, digest: digest.digest("hex") } }),
|
||||
};
|
||||
}
|
||||
if (metadata?.isDirectory()) {
|
||||
throwIfSignalAborted(signal);
|
||||
return await validatePluginRoot(path);
|
||||
return { root: await validatePluginRoot(path) };
|
||||
}
|
||||
throw new PluginBootstrapError(
|
||||
`Plugin path must be a directory or ZIP: ${path}`,
|
||||
@@ -3064,6 +3116,104 @@ export async function resolvePluginPath(
|
||||
}
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export async function prepareWindowsScanPluginZip(
|
||||
source: PluginZipSource,
|
||||
scanDirectory: string,
|
||||
protectedDirectories: readonly string[],
|
||||
validateLocation: (path: string) => void,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ workspace: string; root: string } | undefined> {
|
||||
throwIfSignalAborted(signal);
|
||||
const protectedPath = (path: string) =>
|
||||
protectedDirectories.some((directory) => isWithin(directory, path));
|
||||
if (protectedPath(source.path)) return;
|
||||
const metadata = await lstat(source.path).catch(nullIfMissingFileError);
|
||||
if (metadata === null) return;
|
||||
const changed = "The selected plugin ZIP changed after runtime preparation.";
|
||||
if (!metadata.isFile()) throw new LocalPluginBootstrapError(changed);
|
||||
const canonicalSource = await realpath(source.path).catch(
|
||||
nullIfMissingFileError,
|
||||
);
|
||||
if (canonicalSource === null) return;
|
||||
if (protectedPath(canonicalSource))
|
||||
throw new LocalPluginBootstrapError(changed);
|
||||
let workspace: string | undefined;
|
||||
const parents = [...new Set([dirname(scanDirectory), tmpdir()])].filter(
|
||||
(parent) => !protectedPath(parent) && !isWithin(scanDirectory, parent),
|
||||
);
|
||||
// PowerShell may fail to launch the selected plugin's .cmd at a long path.
|
||||
// Prefer the shorter canonical parent, retaining the output parent on ties.
|
||||
const candidates = await abortable(
|
||||
() => Promise.allSettled(parents.map((path) => realpath(path))),
|
||||
signal,
|
||||
);
|
||||
const length = (candidate: PromiseSettledResult<string>) =>
|
||||
candidate.status === "fulfilled" ? candidate.value.length : Infinity;
|
||||
for (const candidate of candidates.sort((a, b) => length(a) - length(b))) {
|
||||
throwIfSignalAborted(signal);
|
||||
try {
|
||||
if (candidate.status === "rejected") throw candidate.reason;
|
||||
const canonical = candidate.value;
|
||||
if (protectedPath(canonical) || isWithin(scanDirectory, canonical))
|
||||
continue;
|
||||
// Host-side plugin helpers may execute from this copy. A sibling keeps it
|
||||
// outside the writable scan, and the native creator verifies its parents.
|
||||
workspace = await prepareOutputDir(
|
||||
undefined,
|
||||
"plugin-input",
|
||||
canonical,
|
||||
validateLocation,
|
||||
);
|
||||
break;
|
||||
} catch (error) {
|
||||
if (
|
||||
!(error instanceof OutputDirectoryError) &&
|
||||
!["EACCES", "EPERM", "ENOENT"].includes(nodeErrorCode(error) ?? "")
|
||||
)
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
// Keep existing plugin handling where neither scan input location is usable.
|
||||
if (workspace === undefined) return;
|
||||
try {
|
||||
throwIfSignalAborted(signal);
|
||||
const digest = createHash("sha256");
|
||||
const root = await extractValidatedPluginZip(
|
||||
source.path,
|
||||
join(workspace, "plugin"),
|
||||
signal,
|
||||
digest,
|
||||
);
|
||||
throwIfSignalAborted(signal);
|
||||
if (digest.digest("hex") !== source.digest) {
|
||||
throw new LocalPluginBootstrapError(changed);
|
||||
}
|
||||
return { workspace, root };
|
||||
} catch (error) {
|
||||
try {
|
||||
await cleanupSdkDirectory(workspace);
|
||||
} catch (cleanupError) {
|
||||
throwIfSignalAborted(signal);
|
||||
throw new LocalPluginBootstrapError(
|
||||
`${errorMessage(error)}\nCould not remove scan input directory ${workspace}: ${errorMessage(cleanupError)}`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
throwIfSignalAborted(signal);
|
||||
const cause =
|
||||
error instanceof PluginBootstrapError ? error.cause : undefined;
|
||||
if (
|
||||
isRecord(cause) &&
|
||||
cause["code"] === "ENOENT" &&
|
||||
cause["syscall"] === "open" &&
|
||||
cause["path"] === source.path
|
||||
)
|
||||
return;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function createMarketplace(
|
||||
codexHome: string,
|
||||
pluginRoot: string,
|
||||
@@ -3153,15 +3303,12 @@ async function pluginRuntimeProjection(
|
||||
}
|
||||
const environment = server["env_vars"];
|
||||
if (environment !== undefined && !Array.isArray(environment)) return;
|
||||
if (
|
||||
!Array.isArray(environment) ||
|
||||
!environment.includes("CODEX_SECURITY_PLUGIN_ROOT")
|
||||
) {
|
||||
server["env_vars"] = [
|
||||
...(Array.isArray(environment) ? environment : []),
|
||||
"CODEX_SECURITY_PLUGIN_ROOT",
|
||||
];
|
||||
}
|
||||
server["env_vars"] = [
|
||||
...(environment ?? []),
|
||||
...["CODEX_SECURITY_PLUGIN_ROOT", "CODEX_SECURITY_REPOSITORY"].filter(
|
||||
(name) => !environment?.includes(name),
|
||||
),
|
||||
];
|
||||
const files: PluginRuntimeProjection["files"] = new Map();
|
||||
server["command"] =
|
||||
server["command"] === "./scripts/launch_codex_security_mcp.cmd"
|
||||
@@ -3196,7 +3343,11 @@ async function pluginRuntimeProjection(
|
||||
export function resolveCodexCommand(
|
||||
environment: ProcessEnvironment = process.env,
|
||||
): CodexCommand {
|
||||
const configured = environmentValue(environment, "CODEX_CLI_PATH");
|
||||
const configured = configuredExecutableValue(
|
||||
environmentValue(environment, "CODEX_CLI_PATH", true),
|
||||
process.platform,
|
||||
(value) => isExecutableFile(expandHomeForLookup(value, environment)),
|
||||
);
|
||||
const expanded =
|
||||
configured === undefined
|
||||
? undefined
|
||||
@@ -3309,6 +3460,35 @@ export async function bootstrapPlugin(
|
||||
);
|
||||
const stagedMatches =
|
||||
staged?.version === version && (await matchesSelected(stagedRoot));
|
||||
const matchesNativeInstall = async (
|
||||
installedRoot: string,
|
||||
allowRuntimeFiles = false,
|
||||
) =>
|
||||
(await matchesSelected(stagedRoot)) &&
|
||||
// Ordinary reuse permits runtime files when all selected bytes are present.
|
||||
// The native receipt still verifies the complete generated command output.
|
||||
((allowRuntimeFiles && (await matchesSelected(installedRoot, true))) ||
|
||||
(await matchesSelected(
|
||||
installedRoot,
|
||||
false,
|
||||
migratedCommands(installedRoot),
|
||||
)));
|
||||
const nativeMigration = (installedRoot: string, allowRuntimeFiles = false) =>
|
||||
verifiedCommandMigration(
|
||||
installedRoot,
|
||||
(path) => matchesNativeInstall(path, allowRuntimeFiles),
|
||||
options.signal,
|
||||
);
|
||||
const matchesReceipt = async (installedRoot: string, migration: unknown) => {
|
||||
if (
|
||||
typeof migration === "string" &&
|
||||
options.runCodex === undefined &&
|
||||
(await isBundledPluginInstaller(command))
|
||||
) {
|
||||
return (await nativeMigration(installedRoot, true)) === migration;
|
||||
}
|
||||
return matchesSelected(installedRoot, true);
|
||||
};
|
||||
|
||||
if (!stagedMatches) {
|
||||
if (existing !== null) {
|
||||
@@ -3387,7 +3567,10 @@ export async function bootstrapPlugin(
|
||||
isRecord(previous) &&
|
||||
typeof previous["installedPath"] === "string" &&
|
||||
previous["version"] === version &&
|
||||
(await matchesSelected(previous["installedPath"], true))
|
||||
(await matchesReceipt(
|
||||
previous["installedPath"],
|
||||
previous["nativeCommandMigration"],
|
||||
))
|
||||
) {
|
||||
return {
|
||||
pluginRoot: root,
|
||||
@@ -3413,13 +3596,7 @@ export async function bootstrapPlugin(
|
||||
} catch (first) {
|
||||
if (!isRolledBackPluginActivation(first)) throw first;
|
||||
throwIfSignalAborted(options.signal);
|
||||
let bundled: string;
|
||||
try {
|
||||
bundled = resolveBundledCodexExecutable();
|
||||
} catch {
|
||||
throw first;
|
||||
}
|
||||
if (!(await sameFile(command.command, bundled))) throw first;
|
||||
if (!(await isBundledPluginInstaller(command))) throw first;
|
||||
// The bundled CLI restored the old cache. A short-lived Windows reader
|
||||
// of the new tree can release it before a fresh installation attempt.
|
||||
try {
|
||||
@@ -3460,22 +3637,28 @@ export async function bootstrapPlugin(
|
||||
);
|
||||
}
|
||||
|
||||
if (retried) {
|
||||
const installedRoot = installed["installedPath"];
|
||||
// The pinned local installer converts plugin commands into skills here.
|
||||
const migratedCommands = join(
|
||||
installedRoot,
|
||||
".codex-plugin",
|
||||
"migrated-command-skills",
|
||||
// The bundled installer removes stale command skills before regenerating them.
|
||||
const bundledInstaller =
|
||||
retried ||
|
||||
(options.runCodex === undefined &&
|
||||
(await isBundledPluginInstaller(command)));
|
||||
const hasSourceMigration =
|
||||
bundledInstaller &&
|
||||
(
|
||||
await lstat(migratedCommands(root)).catch(nullIfMissingFileError)
|
||||
)?.isDirectory() === true;
|
||||
const nativeCommandMigration = hasSourceMigration
|
||||
? await nativeMigration(installed["installedPath"])
|
||||
: undefined;
|
||||
if (
|
||||
retried &&
|
||||
!(hasSourceMigration
|
||||
? nativeCommandMigration !== undefined
|
||||
: await matchesNativeInstall(installed["installedPath"]))
|
||||
) {
|
||||
throw new PluginBootstrapError(
|
||||
"The retried Codex plugin install did not install the selected plugin contents.",
|
||||
);
|
||||
if (
|
||||
!(await matchesSelected(stagedRoot)) ||
|
||||
!(await matchesSelected(installedRoot, false, migratedCommands))
|
||||
) {
|
||||
throw new PluginBootstrapError(
|
||||
"The retried Codex plugin install did not install the selected plugin contents.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await writeFile(
|
||||
@@ -3483,6 +3666,7 @@ export async function bootstrapPlugin(
|
||||
JSON.stringify({
|
||||
installedPath: installed["installedPath"],
|
||||
version,
|
||||
...(nativeCommandMigration ? { nativeCommandMigration } : {}),
|
||||
}),
|
||||
{ mode: 0o600, signal: options.signal },
|
||||
);
|
||||
@@ -3497,6 +3681,111 @@ export async function bootstrapPlugin(
|
||||
};
|
||||
}
|
||||
|
||||
async function isBundledPluginInstaller(
|
||||
command: CodexCommand,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
return await sameFile(command.command, resolveBundledCodexExecutable());
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function migratedCommands(plugin: string): string {
|
||||
return join(plugin, ".codex-plugin", "migrated-command-skills");
|
||||
}
|
||||
|
||||
// Bind a receipt to the generated files observed in this installation.
|
||||
// Entry names come from its directories, never from the saved digest.
|
||||
async function verifiedCommandMigration(
|
||||
installedRoot: string,
|
||||
matchesSelected: (installedRoot: string) => Promise<boolean>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string | undefined> {
|
||||
const digest = createHash("sha256");
|
||||
const record = (...fields: (string | number)[]) =>
|
||||
digest.update(JSON.stringify(fields)).update("\n");
|
||||
async function visit(path: string, name: string): Promise<boolean> {
|
||||
throwIfSignalAborted(signal);
|
||||
const metadata = await lstat(path, { bigint: true });
|
||||
if (
|
||||
metadata.isSymbolicLink() ||
|
||||
relative(path, await realpath(path)) !== ""
|
||||
)
|
||||
return false;
|
||||
if (metadata.isDirectory()) {
|
||||
record("directory", name);
|
||||
for (const entry of (await readdir(path)).sort()) {
|
||||
const child = join(path, entry);
|
||||
if (!(await visit(child, name ? `${name}/${entry}` : entry)))
|
||||
return false;
|
||||
}
|
||||
return sameInode(metadata, await lstat(path, { bigint: true }));
|
||||
}
|
||||
if (!metadata.isFile()) return false;
|
||||
const file = await open(
|
||||
path,
|
||||
constants.O_RDONLY |
|
||||
(constants.O_NOFOLLOW ?? 0) |
|
||||
(constants.O_NONBLOCK ?? 0),
|
||||
);
|
||||
try {
|
||||
const opened = await file.stat({ bigint: true });
|
||||
if (!opened.isFile()) return false;
|
||||
if (!sameInode(metadata, opened)) {
|
||||
if (process.platform !== "win32") return false;
|
||||
// Some Windows Node versions report a different device on an open handle.
|
||||
const { sameCheckedFileDevice } = await import("./contract.js");
|
||||
if (!(await sameCheckedFileDevice(file, { path, metadata }, opened)))
|
||||
return false;
|
||||
}
|
||||
const contents = createHash("sha256")
|
||||
.update(await file.readFile({ signal }))
|
||||
.digest("hex");
|
||||
record("file", name, Number(opened.mode & 0o111n), contents);
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
throwIfSignalAborted(signal);
|
||||
const installation = await lstat(installedRoot, { bigint: true }).catch(
|
||||
nullIfMissingFileError,
|
||||
);
|
||||
if (
|
||||
!installation?.isDirectory() ||
|
||||
installation.ino === 0n ||
|
||||
!(await matchesSelected(installedRoot))
|
||||
)
|
||||
return;
|
||||
try {
|
||||
const directory = migratedCommands(await realpath(installedRoot));
|
||||
const parent = dirname(directory);
|
||||
if (
|
||||
!(await lstat(parent)).isDirectory() ||
|
||||
relative(parent, await realpath(parent)) !== ""
|
||||
)
|
||||
return;
|
||||
const root = await lstat(directory, { bigint: true }).catch(
|
||||
nullIfMissingFileError,
|
||||
);
|
||||
if (root && (!root.isDirectory() || !(await visit(directory, "")))) return;
|
||||
// Native activation replaces the installed directory even at the same version.
|
||||
if (!sameInode(installation, await lstat(installedRoot, { bigint: true })))
|
||||
return;
|
||||
throwIfSignalAborted(signal);
|
||||
return root ? `sha256:${digest.digest("hex")}` : "absent";
|
||||
} catch (error) {
|
||||
throwIfSignalAborted(signal);
|
||||
if (
|
||||
!["ENOENT", "ENOTDIR", "ELOOP", "EISDIR", "EACCES", "EPERM"].includes(
|
||||
nodeErrorCode(error) ?? "",
|
||||
)
|
||||
)
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function pluginContentsMatch(
|
||||
source: string,
|
||||
destination: string,
|
||||
@@ -3651,13 +3940,11 @@ export async function resolvePluginPython(
|
||||
options: PluginPythonOptions = {},
|
||||
): Promise<string> {
|
||||
const environment = options.environment ?? process.env;
|
||||
const requestedRoots = options.protectedRoot ?? process.cwd();
|
||||
const cwd = process.cwd();
|
||||
const requestedRoots = options.protectedRoot ?? cwd;
|
||||
const protectedRoot =
|
||||
typeof requestedRoots === "string" ? [requestedRoots] : [...requestedRoots];
|
||||
const callerDirectories = [
|
||||
process.cwd(),
|
||||
options.currentDirectory ?? process.cwd(),
|
||||
];
|
||||
const callerDirectories = new Set([cwd, options.currentDirectory ?? cwd]);
|
||||
// Preserve target and enclosing-checkout protection for every interpreter.
|
||||
for (const directory of new Set([...callerDirectories, ...protectedRoot])) {
|
||||
for (const checkout of await gitProtectionRoots(directory, options.signal))
|
||||
@@ -3665,7 +3952,21 @@ export async function resolvePluginPython(
|
||||
}
|
||||
// Named interpreters are ambient PATH discovery, even when PYTHON names one.
|
||||
// Explicit trusted paths and managed runtimes retain their existing precedence.
|
||||
const discoveryRoots = [...protectedRoot, ...callerDirectories];
|
||||
const discoveryRoots = [...protectedRoot];
|
||||
for (const directory of callerDirectories) {
|
||||
const physical =
|
||||
directory === cwd
|
||||
? cwd
|
||||
: await realpath(directory).catch(() => undefined);
|
||||
// A filesystem-root launch directory also contains the operator's installed tools.
|
||||
// Explicit scan roots and enclosing checkouts are already in protectedRoot.
|
||||
if (
|
||||
protectedRoot.length === 0 ||
|
||||
physical === undefined ||
|
||||
dirname(physical) !== physical
|
||||
)
|
||||
discoveryRoots.push(directory);
|
||||
}
|
||||
if (options.configuredPath !== undefined) {
|
||||
return await requirePython(
|
||||
options.configuredPath,
|
||||
@@ -3677,13 +3978,26 @@ export async function resolvePluginPython(
|
||||
options.signal,
|
||||
);
|
||||
}
|
||||
const inherited = environmentValue(environment, "PYTHON");
|
||||
const inherited = environmentValue(environment, "PYTHON", true);
|
||||
if (inherited) {
|
||||
const roots = isPythonPathCandidate(inherited)
|
||||
? protectedRoot
|
||||
: discoveryRoots;
|
||||
// Check an explicit literal path with the same repository protections as the launch.
|
||||
const candidate =
|
||||
isExplicitPathWithTrailingWhitespace(inherited, process.platform) &&
|
||||
(await resolveTrustedExecutable(
|
||||
expandHomeForLookup(inherited, environment),
|
||||
environment,
|
||||
roots,
|
||||
))
|
||||
? inherited
|
||||
: inherited.trim();
|
||||
return await requirePython(
|
||||
inherited,
|
||||
candidate,
|
||||
"PYTHON",
|
||||
environment,
|
||||
isPythonPathCandidate(inherited) ? protectedRoot : discoveryRoots,
|
||||
roots,
|
||||
options.signal,
|
||||
);
|
||||
}
|
||||
@@ -3822,8 +4136,15 @@ export async function runCodexCommand(
|
||||
environment: ProcessEnvironment,
|
||||
input?: string | Uint8Array,
|
||||
signal?: AbortSignal,
|
||||
registrationHandshake = false,
|
||||
stdinPrefix?: string,
|
||||
{
|
||||
registrationHandshake = false,
|
||||
stdinPrefix,
|
||||
cwd,
|
||||
}: {
|
||||
registrationHandshake?: boolean;
|
||||
stdinPrefix?: string;
|
||||
cwd?: string;
|
||||
} = {},
|
||||
): Promise<CodexCommandResult> {
|
||||
const cancellation = registrationHandshake
|
||||
? new AbortController()
|
||||
@@ -3834,6 +4155,7 @@ export async function runCodexCommand(
|
||||
executablePathForSpawn(command.command),
|
||||
[...(command.args ?? []), ...args],
|
||||
{
|
||||
cwd,
|
||||
env: environment,
|
||||
stdio: registrationHandshake
|
||||
? ["pipe", "pipe", "pipe", "pipe"]
|
||||
@@ -3967,13 +4289,21 @@ async function runPluginCommand(
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
try {
|
||||
const { success, exitCode, stdout, stderr } = await runCodexCommand(
|
||||
command,
|
||||
args,
|
||||
environment,
|
||||
undefined,
|
||||
signal,
|
||||
);
|
||||
const run = (argv: readonly string[], cwd?: string) =>
|
||||
runCodexCommand(command, argv, environment, undefined, signal, { cwd });
|
||||
let result = await run(args);
|
||||
const source = args[1] === "marketplace" ? args[3] : undefined;
|
||||
if (
|
||||
result.exitCode === 1 &&
|
||||
source?.includes("#") &&
|
||||
result.stderr
|
||||
.split(/\r?\n/u)
|
||||
.includes("Error: --ref is only supported for git marketplace sources")
|
||||
) {
|
||||
// Native Codex parsed a literal hash in the local path as a Git ref.
|
||||
result = await run(["plugin", "marketplace", "add", "."], source);
|
||||
}
|
||||
const { success, exitCode, stdout, stderr } = result;
|
||||
if (!success) {
|
||||
const detail =
|
||||
stderr.trim() ||
|
||||
|
||||
@@ -482,7 +482,25 @@ async function securityPolicyPaths(
|
||||
const directory = directories.pop()!;
|
||||
if (isGitData(directory)) continue;
|
||||
const entries = await readdir(directory, { withFileTypes: true });
|
||||
if (await isGitMetadataDirectory(directory, signal)) {
|
||||
let gitMetadata: boolean;
|
||||
try {
|
||||
gitMetadata = await isGitMetadataDirectory(directory, signal);
|
||||
} catch (error) {
|
||||
// POSIX can permit listing a directory but deny lookups of its children.
|
||||
// A leaf containing only unrelated regular files needs no further lookups.
|
||||
if (
|
||||
process.platform !== "win32" &&
|
||||
(error as NodeJS.ErrnoException).code === "EACCES" &&
|
||||
entries.every(
|
||||
(entry) =>
|
||||
entry.isFile() &&
|
||||
!/^(?:\.git|HEAD|SECURITY\.md)$/iu.test(entry.name),
|
||||
)
|
||||
)
|
||||
continue;
|
||||
throw error;
|
||||
}
|
||||
if (gitMetadata) {
|
||||
gitDirectories.add(directory);
|
||||
const common = await readFile(join(directory, "commondir"), "utf8").catch(
|
||||
nullIfMissingFile,
|
||||
|
||||
@@ -2,8 +2,16 @@ import { isNonEmptyString } from "./value.js";
|
||||
import { isUtf8 } from "node:buffer";
|
||||
import { execFile as execFileCallback } from "node:child_process";
|
||||
import { realpathSync, type Stats } from "node:fs";
|
||||
import { lstat, readFile, realpath, stat } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import {
|
||||
copyFile,
|
||||
lstat,
|
||||
mkdtemp,
|
||||
readFile,
|
||||
realpath,
|
||||
rm,
|
||||
stat,
|
||||
} from "node:fs/promises";
|
||||
import { homedir, tmpdir } from "node:os";
|
||||
import {
|
||||
basename,
|
||||
dirname,
|
||||
@@ -675,12 +683,60 @@ export async function validateCommittedDiffCheckout(
|
||||
);
|
||||
}
|
||||
|
||||
const tracked = await gitOutput(repository, ["ls-files", "-t", "-z"], signal);
|
||||
if (tracked.split("\0").some((entry) => entry.startsWith("S "))) {
|
||||
const tracked = (
|
||||
await gitOutput(repository, ["ls-files", "-v", "-z"], signal)
|
||||
).split("\0");
|
||||
if (tracked.some((entry) => /^[Ss] /u.test(entry))) {
|
||||
throw new InvalidTargetError(
|
||||
"Committed-diff scans require a full repository checkout. Sparse checkouts are not supported; materialize skipped tracked files and retry.",
|
||||
);
|
||||
}
|
||||
if (tracked.some((entry) => entry.startsWith("h "))) {
|
||||
await verifyAssumedUnchangedFiles(repository, signal);
|
||||
}
|
||||
}
|
||||
|
||||
async function verifyAssumedUnchangedFiles(
|
||||
repository: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
const index = await gitOutput(
|
||||
repository,
|
||||
["rev-parse", "--path-format=absolute", "--git-path", "index"],
|
||||
signal,
|
||||
);
|
||||
// Git changes to the repository before resolving GIT_INDEX_FILE, even when TMPDIR is relative.
|
||||
const directory = await mkdtemp(
|
||||
join(await realpath(tmpdir()), "codex-security-git-index-"),
|
||||
);
|
||||
const copy = join(directory, "index");
|
||||
try {
|
||||
// Git refreshes stat data and flags. Keep that write and any hooks out of the checkout.
|
||||
await copyFile(index, copy);
|
||||
await gitOutput(
|
||||
repository,
|
||||
[
|
||||
"-c",
|
||||
`core.hooksPath=${directory}`,
|
||||
"-c",
|
||||
"core.splitIndex=false",
|
||||
"update-index",
|
||||
"--really-refresh",
|
||||
],
|
||||
signal,
|
||||
{ GIT_INDEX_FILE: copy },
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && "code" in error && error.code === 1) {
|
||||
throw new InvalidTargetError(
|
||||
"Committed-diff scans require a clean repository checkout. A tracked file marked assume-unchanged has changed on disk.",
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
export function validateMode(target: NormalizedTarget, mode: ScanMode): void {
|
||||
|
||||
@@ -302,6 +302,14 @@ describe("CodexSecurity policy API", () => {
|
||||
filesystem: {
|
||||
[process.platform === "win32" ? ":root" : ":minimal"]: "read",
|
||||
":workspace_roots": "read",
|
||||
...(process.platform === "win32"
|
||||
? Object.fromEntries(
|
||||
f.threads[0]!.additionalDirectories!.map((path) => [
|
||||
path,
|
||||
{ ".": "read" },
|
||||
]),
|
||||
)
|
||||
: {}),
|
||||
...Object.fromEntries(
|
||||
readPaths.map((path) => [path, { ".": "read" }]),
|
||||
),
|
||||
|
||||
@@ -5,11 +5,14 @@ import {
|
||||
readFile,
|
||||
readdir,
|
||||
realpath,
|
||||
rm,
|
||||
stat,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { existsSync } from "node:fs";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import * as fsPromises from "node:fs/promises";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import * as os from "node:os";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import { afterEach, expect, spyOn, test } from "bun:test";
|
||||
@@ -49,6 +52,244 @@ test("preflights with explicit storage paths when the account has no home direct
|
||||
}
|
||||
});
|
||||
|
||||
test.skipIf(process.platform !== "win32").each(["changed", "canceled"])(
|
||||
"retains a %s ZIP error when Windows holds the scan input open",
|
||||
async (result) => {
|
||||
const root = await temporaryDirectory();
|
||||
using temporary = spyOn(os, "tmpdir").mockReturnValue(root);
|
||||
const bootstrap = join(root, "bootstrap");
|
||||
const output = join(root, "scan");
|
||||
const archive = join(root, "selected.zip");
|
||||
await mkdir(bootstrap);
|
||||
await mkdir(output);
|
||||
const plugin = (description: string) =>
|
||||
zipSync({
|
||||
".codex-plugin/plugin.json": strToU8(
|
||||
JSON.stringify({
|
||||
name: "codex-security",
|
||||
version: "1.2.3",
|
||||
description,
|
||||
}),
|
||||
),
|
||||
});
|
||||
await writeFile(archive, plugin("original"));
|
||||
const { zip } = await runtime.resolvePluginSource(
|
||||
archive,
|
||||
bootstrap,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
if (result === "changed") await writeFile(archive, plugin("replacement"));
|
||||
const controller = new AbortController();
|
||||
const reason = new Error("Canceled while preparing the scan input");
|
||||
const nativeRename = fsPromises.rename;
|
||||
let held = "";
|
||||
let release: (() => Promise<void>) | undefined;
|
||||
using publication = spyOn(fsPromises, "rename").mockImplementation(
|
||||
async (from, to) => {
|
||||
await nativeRename(from, to);
|
||||
if (basename(String(to)) !== "plugin") return;
|
||||
held = dirname(String(to));
|
||||
const holder = spawn(
|
||||
"node",
|
||||
["-e", 'process.stdout.write("ready"); process.stdin.resume()'],
|
||||
{ cwd: held, windowsHide: true },
|
||||
);
|
||||
const exited = once(holder, "exit");
|
||||
release = async () => {
|
||||
holder.stdin.end();
|
||||
await exited;
|
||||
};
|
||||
await once(holder.stdout, "data");
|
||||
if (result === "canceled") controller.abort(reason);
|
||||
},
|
||||
);
|
||||
try {
|
||||
const operation = runtime.prepareWindowsScanPluginZip(
|
||||
zip!,
|
||||
output,
|
||||
[bootstrap],
|
||||
() => {},
|
||||
controller.signal,
|
||||
);
|
||||
if (result === "canceled") await expect(operation).rejects.toBe(reason);
|
||||
else {
|
||||
const failure = await operation.catch((error: unknown) => error);
|
||||
expect((failure as Error).message).toContain(
|
||||
`Could not remove scan input directory ${held}:`,
|
||||
);
|
||||
expect(failure).toMatchObject({
|
||||
cause: {
|
||||
name: "LocalPluginBootstrapError",
|
||||
message: expect.stringContaining("ZIP changed"),
|
||||
},
|
||||
});
|
||||
}
|
||||
expect(publication).toHaveBeenCalled();
|
||||
expect(temporary).toHaveBeenCalled();
|
||||
expect(existsSync(held)).toBe(true);
|
||||
} finally {
|
||||
await release?.();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test.skipIf(process.platform !== "win32")(
|
||||
"cancels ZIP staging while a candidate parent is still being resolved",
|
||||
async () => {
|
||||
const root = await temporaryDirectory();
|
||||
const temp = join(root, "temp");
|
||||
const output = join(root, "longer-output-parent", "scan");
|
||||
const bootstrap = join(root, "bootstrap");
|
||||
const archive = join(root, "selected.zip");
|
||||
await mkdir(temp);
|
||||
await mkdir(bootstrap);
|
||||
await mkdir(output, { recursive: true });
|
||||
await writeFile(
|
||||
archive,
|
||||
zipSync({
|
||||
".codex-plugin/plugin.json": strToU8(
|
||||
'{"name":"codex-security","version":"1.2.3"}',
|
||||
),
|
||||
}),
|
||||
);
|
||||
const { zip } = await runtime.resolvePluginSource(
|
||||
archive,
|
||||
bootstrap,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
using temporary = spyOn(os, "tmpdir").mockReturnValue(temp);
|
||||
const started = Promise.withResolvers<void>();
|
||||
const held = Promise.withResolvers<string>();
|
||||
const canonicalize = fsPromises.realpath;
|
||||
using lookup = spyOn(fsPromises, "realpath").mockImplementation(
|
||||
new Proxy(canonicalize, {
|
||||
apply(target, receiver, args) {
|
||||
if (args[0] !== temp) return Reflect.apply(target, receiver, args);
|
||||
started.resolve();
|
||||
return held.promise;
|
||||
},
|
||||
}),
|
||||
);
|
||||
const controller = new AbortController();
|
||||
const reason = new Error("Canceled during scan input placement");
|
||||
let canceled: unknown;
|
||||
const operation = runtime
|
||||
.prepareWindowsScanPluginZip(
|
||||
zip!,
|
||||
output,
|
||||
[bootstrap],
|
||||
() => {},
|
||||
controller.signal,
|
||||
)
|
||||
.catch((error: unknown) => {
|
||||
canceled = error;
|
||||
});
|
||||
try {
|
||||
await started.promise;
|
||||
controller.abort(reason);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(canceled).toBe(reason);
|
||||
} finally {
|
||||
held.resolve(temp);
|
||||
await operation;
|
||||
}
|
||||
expect(await readdir(temp)).toEqual([]);
|
||||
expect(temporary).toHaveBeenCalled();
|
||||
expect(lookup).toHaveBeenCalledWith(temp);
|
||||
expect(await readdir(dirname(output))).toEqual(["scan"]);
|
||||
},
|
||||
);
|
||||
|
||||
test.skipIf(process.platform !== "win32")(
|
||||
"prepares the pinned ZIP from its original source for explicit and default Windows scan outputs",
|
||||
async () => {
|
||||
const root = await temporaryDirectory();
|
||||
const archive = join(root, "workflow [source].ZIP");
|
||||
const ambient = join(root, "ambient");
|
||||
const bootstrap = join(root, "bootstrap");
|
||||
const ordinaryTemp = join(root, "scan-temporary");
|
||||
const explicit = join(root, "explicit", "scan");
|
||||
const deepOutput = join(root, "nested-output-".repeat(8), "scan");
|
||||
const equalLengthTemp = join(root, "parallel");
|
||||
const configuredDefault = join(root, "state", "scans", "fixture", "scan");
|
||||
const privateDefault = join(ambient, "state", "scans", "fixture", "scan");
|
||||
for (const path of [
|
||||
bootstrap,
|
||||
ordinaryTemp,
|
||||
explicit,
|
||||
deepOutput,
|
||||
equalLengthTemp,
|
||||
configuredDefault,
|
||||
privateDefault,
|
||||
])
|
||||
await mkdir(path, { recursive: true });
|
||||
const contents = (skill: string) =>
|
||||
zipSync({
|
||||
"release/.codex-plugin/plugin.json": strToU8(
|
||||
JSON.stringify({ name: "codex-security", version: "1.2.3" }),
|
||||
),
|
||||
"release/skills/security-scan/SKILL.md": strToU8(skill),
|
||||
});
|
||||
const original = Buffer.from(contents("# Selected workflow"));
|
||||
await writeFile(archive, original);
|
||||
const { zip } = await runtime.resolvePluginSource(
|
||||
archive,
|
||||
bootstrap,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
expect(zip).toBeDefined();
|
||||
// Removing the synthetic install proves every scan reads its selected ZIP.
|
||||
await rm(bootstrap, { recursive: true });
|
||||
using temporary = spyOn(os, "tmpdir").mockReturnValue(ordinaryTemp);
|
||||
const prepare = (scan: string) =>
|
||||
runtime.prepareWindowsScanPluginZip(
|
||||
zip!,
|
||||
scan,
|
||||
[ambient, bootstrap],
|
||||
() => {},
|
||||
);
|
||||
for (const [output, temp, expectedParent] of [
|
||||
[explicit, ordinaryTemp, dirname(explicit)],
|
||||
[explicit, equalLengthTemp, dirname(explicit)],
|
||||
[deepOutput, ordinaryTemp, ordinaryTemp],
|
||||
[configuredDefault, ordinaryTemp, ordinaryTemp],
|
||||
[deepOutput, ambient, dirname(deepOutput)],
|
||||
[privateDefault, ordinaryTemp, ordinaryTemp],
|
||||
] as const) {
|
||||
temporary.mockReturnValue(temp);
|
||||
const staged = await prepare(output);
|
||||
expect(staged).toBeDefined();
|
||||
try {
|
||||
expect(dirname(staged!.workspace)).toBe(expectedParent);
|
||||
expect(staged!.root).toBe(join(staged!.workspace, "plugin", "release"));
|
||||
expect(
|
||||
await readFile(
|
||||
join(staged!.root, "skills/security-scan/SKILL.md"),
|
||||
"utf8",
|
||||
),
|
||||
).toBe("# Selected workflow");
|
||||
} finally {
|
||||
await runtime.cleanupSdkDirectory(staged!.workspace);
|
||||
}
|
||||
}
|
||||
expect(await readFile(archive)).toEqual(original);
|
||||
await writeFile(archive, contents("different bytes at the same version"));
|
||||
await expect(prepare(explicit)).rejects.toThrow(
|
||||
"changed after runtime preparation",
|
||||
);
|
||||
expect(await readdir(dirname(explicit))).toEqual(["scan"]);
|
||||
await rm(archive);
|
||||
expect(await prepare(explicit)).toBeUndefined();
|
||||
expect(await readdir(dirname(explicit))).toEqual(["scan"]);
|
||||
await writeFile(archive, original);
|
||||
temporary.mockReturnValue(ambient);
|
||||
expect(await prepare(privateDefault)).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
function stubPluginInstall() {
|
||||
return spyOn(runtime, "bootstrapPlugin").mockImplementation(
|
||||
async (_home, pluginRoot) => ({
|
||||
@@ -160,6 +401,10 @@ test.each(["ready", "denied", "canceled"])(
|
||||
"filesystem"
|
||||
] as Record<string, unknown>;
|
||||
expect(roots[dirname(profileFile)]).toEqual({ ".": "deny" });
|
||||
if (process.platform === "win32" && operation !== "validation")
|
||||
expect(roots[await realpath(repository)]).toEqual({
|
||||
".": "read",
|
||||
});
|
||||
if (process.platform === "win32" && operation !== "validation") {
|
||||
const staged = options.env!["CODEX_SECURITY_PLUGIN_ROOT"]!;
|
||||
expect(dirname(staged)).toBe(protectedDirectory!);
|
||||
@@ -255,7 +500,7 @@ test.each(["directory", "zip"])(
|
||||
await writeFile(join(pluginPath, name), contents);
|
||||
}
|
||||
}
|
||||
const snapshotAcl = () => {
|
||||
const snapshotAcl = (path = temporary) => {
|
||||
const system = join(process.env["SystemRoot"]!, "System32");
|
||||
const result = spawnSync(
|
||||
join(system, "WindowsPowerShell", "v1.0", "powershell.exe"),
|
||||
@@ -274,7 +519,7 @@ test.each(["directory", "zip"])(
|
||||
([name]) => name.toUpperCase() !== "PSMODULEPATH",
|
||||
),
|
||||
),
|
||||
CODEX_SECURITY_TEST_TEMP: temporary,
|
||||
CODEX_SECURITY_TEST_TEMP: path,
|
||||
PSModulePath: join(system, "WindowsPowerShell", "v1.0", "Modules"),
|
||||
},
|
||||
windowsHide: true,
|
||||
@@ -284,6 +529,8 @@ test.each(["directory", "zip"])(
|
||||
return result.stdout.trim();
|
||||
};
|
||||
let temporaryAcl: string | undefined;
|
||||
const sourceAcl =
|
||||
process.platform === "win32" ? snapshotAcl(pluginPath) : undefined;
|
||||
if (process.platform === "win32") {
|
||||
const grant = spawnSync(
|
||||
join(process.env["SystemRoot"]!, "System32", "icacls.exe"),
|
||||
@@ -308,6 +555,9 @@ test.each(["directory", "zip"])(
|
||||
const temporaryRoot = spyOn(os, "tmpdir").mockReturnValue(temporary);
|
||||
const install = stubPluginInstall();
|
||||
const workspaces = new Map<number, string>();
|
||||
const zipInputs = new Set<string>();
|
||||
let defaultOutput = false;
|
||||
let movedArchive = false;
|
||||
const clients: TestClient[] = [];
|
||||
const createClient = (index: number, stateDirectory = state) => {
|
||||
const client = new TestClient(
|
||||
@@ -353,19 +603,76 @@ test.each(["directory", "zip"])(
|
||||
const previous = workspaces.get(index);
|
||||
if (previous !== undefined) expect(workspace).toBe(previous);
|
||||
workspaces.set(index, workspace);
|
||||
expect(environment["CODEX_SECURITY_PLUGIN_ROOT"]).toBe(
|
||||
source === "zip"
|
||||
? join(workspace, "extracted-plugin")
|
||||
: pluginPath,
|
||||
);
|
||||
const plugin = environment["CODEX_SECURITY_PLUGIN_ROOT"]!;
|
||||
if (
|
||||
source === "zip" &&
|
||||
process.platform === "win32" &&
|
||||
!movedArchive
|
||||
) {
|
||||
const input = dirname(plugin);
|
||||
expect(dirname(input)).toBe(
|
||||
dirname(environment["CODEX_SECURITY_SCAN_DIR"]!),
|
||||
);
|
||||
expect(zipInputs.has(input)).toBe(false);
|
||||
zipInputs.add(input);
|
||||
expect(
|
||||
existsSync(join(plugin, "skills/security-scan/SKILL.md")),
|
||||
).toBe(true);
|
||||
const overrides = options.configOverrides!.find((entry) =>
|
||||
entry.startsWith("permissions.codex_security_scan.filesystem="),
|
||||
)!;
|
||||
expect(parseToml(overrides)).toEqual({
|
||||
permissions: {
|
||||
codex_security_scan: {
|
||||
filesystem: {
|
||||
":root": "read",
|
||||
":workspace_roots": "write",
|
||||
[plugin]: { ".": "read" },
|
||||
[repository]: { ".": "read" },
|
||||
[environment["CODEX_HOME"]!]: { ".": "deny" },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
} else {
|
||||
expect(plugin).toBe(
|
||||
source === "zip"
|
||||
? join(workspace, "extracted-plugin")
|
||||
: pluginPath,
|
||||
);
|
||||
if (movedArchive) {
|
||||
const overrides = options.configOverrides!.find((entry) =>
|
||||
entry.startsWith(
|
||||
"permissions.codex_security_scan.filesystem=",
|
||||
),
|
||||
)!;
|
||||
expect(parseToml(overrides)).toEqual({
|
||||
permissions: {
|
||||
codex_security_scan: {
|
||||
filesystem: {
|
||||
":root": "read",
|
||||
":workspace_roots": "write",
|
||||
[repository]: { ".": "read" },
|
||||
[environment["CODEX_HOME"]!]: { ".": "deny" },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
const codex = codexFactory(async function () {
|
||||
throw new Error("synthetic scan reached");
|
||||
})();
|
||||
return {
|
||||
startThread: (threadOptions) => {
|
||||
expect(threadOptions.workingDirectory).toBe(
|
||||
join(root, `scan-${index}`),
|
||||
);
|
||||
if (defaultOutput) {
|
||||
expect(dirname(threadOptions.workingDirectory!)).toBe(
|
||||
join(stateDirectory, "scans", "repository"),
|
||||
);
|
||||
} else
|
||||
expect(threadOptions.workingDirectory).toBe(
|
||||
join(root, `scan-${index}`),
|
||||
);
|
||||
return codex.startThread();
|
||||
},
|
||||
};
|
||||
@@ -385,18 +692,39 @@ test.each(["directory", "zip"])(
|
||||
expect(run(second, 1)).rejects.toThrow("synthetic scan reached"),
|
||||
]);
|
||||
expect(workspaces.size).toBe(2);
|
||||
for (const input of zipInputs) expect(existsSync(input)).toBe(false);
|
||||
expect(workspaces.get(0)).not.toBe(workspaces.get(1));
|
||||
await first.close();
|
||||
expect(existsSync(workspaces.get(0)!)).toBe(false);
|
||||
expect(existsSync(workspaces.get(1)!)).toBe(true);
|
||||
await expect(run(second, 1)).rejects.toThrow("synthetic scan reached");
|
||||
for (const input of zipInputs) expect(existsSync(input)).toBe(false);
|
||||
if (process.platform === "win32") {
|
||||
if (source === "zip") {
|
||||
defaultOutput = true;
|
||||
await expect(second.run(repository)).rejects.toThrow(
|
||||
"synthetic scan reached",
|
||||
);
|
||||
defaultOutput = false;
|
||||
for (const input of zipInputs) expect(existsSync(input)).toBe(false);
|
||||
movedArchive = true;
|
||||
await fsPromises.rename(pluginPath, `${pluginPath}.moved`);
|
||||
try {
|
||||
await expect(run(second, 1)).rejects.toThrow(
|
||||
"synthetic scan reached",
|
||||
);
|
||||
} finally {
|
||||
await fsPromises.rename(`${pluginPath}.moved`, pluginPath);
|
||||
movedArchive = false;
|
||||
}
|
||||
}
|
||||
const rejected = createClient(2, join(temporary, "untrusted-state"));
|
||||
await expect(run(rejected, 2)).rejects.toThrow(
|
||||
"allows another identity to replace",
|
||||
);
|
||||
expect(workspaces.has(2)).toBe(false);
|
||||
expect(snapshotAcl()).toBe(temporaryAcl!);
|
||||
expect(snapshotAcl(pluginPath)).toBe(sourceAcl!);
|
||||
}
|
||||
expect({ TEMP: process.env["TEMP"], TMP: process.env["TMP"] }).toEqual(
|
||||
processTemporary,
|
||||
@@ -410,5 +738,5 @@ test.each(["directory", "zip"])(
|
||||
expect(existsSync(workspace)).toBe(false);
|
||||
}
|
||||
},
|
||||
60_000,
|
||||
process.platform === "win32" ? 120_000 : 60_000,
|
||||
);
|
||||
|
||||
@@ -7,6 +7,9 @@ import { bundledSeverityRubric } from "../src/severity-rubric.js";
|
||||
import { mockWorkbench, TestClient } from "./support/api-client.js";
|
||||
import { codexFactory, preparedRuntime } from "./support/api-events.js";
|
||||
import { createApiTestFixtures } from "./support/temporary-directories.js";
|
||||
import { useTestPython } from "./support/python.js";
|
||||
|
||||
const pythonExecutable = useTestPython();
|
||||
|
||||
const { temporaryDirectory, cleanup } = createApiTestFixtures();
|
||||
afterEach(cleanup);
|
||||
@@ -28,7 +31,7 @@ for (const mode of ["standard", "deep"] as const) {
|
||||
CODEX_SECURITY_ENABLE_REMOTE_SEVERITY_RUBRIC:
|
||||
source === "bundled" ? undefined : "1",
|
||||
};
|
||||
const python = Bun.which("python3") ?? Bun.which("python");
|
||||
const python = pythonExecutable();
|
||||
if (!python) throw new Error("Python is required for this test.");
|
||||
const markdown = `Use this synthetic ${source} policy.`;
|
||||
const rubricPath = join(root, "policy.md");
|
||||
|
||||
@@ -225,6 +225,9 @@ describe("CodexSecurity finding validation", () => {
|
||||
permissions: {
|
||||
codex_security_validation: {
|
||||
filesystem: {
|
||||
...(process.platform === "win32"
|
||||
? { [options.repositoryPath]: { ".": "read" } }
|
||||
: {}),
|
||||
":root": "read",
|
||||
":workspace_roots": "read",
|
||||
...credentialDenies,
|
||||
|
||||
@@ -3,12 +3,12 @@ import { gitText } from "./support/shell.js";
|
||||
import { emptyPage } from "./support/linear-pagination.js";
|
||||
import { resolving } from "./support/promises.js";
|
||||
import { parse as parseToml } from "smol-toml";
|
||||
import { afterEach, describe, expect, test, mock } from "bun:test";
|
||||
import { afterEach, describe, expect, test, mock, spyOn } from "bun:test";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { hash } from "node:crypto";
|
||||
import { mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, relative, resolve } from "node:path";
|
||||
import * as os from "node:os";
|
||||
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
||||
import { Writable } from "node:stream";
|
||||
import { stripVTControlCharacters } from "node:util";
|
||||
import type { Finding, JsonObject, SeverityLevel } from "../src/index.js";
|
||||
@@ -982,6 +982,9 @@ describe("scan and patch workflow", () => {
|
||||
|
||||
test("assesses only changes made during a literal patch run", async () => {
|
||||
const directory = await temporaryDirectory("codex-security-patch-risk-");
|
||||
using _temporary = spyOn(os, "tmpdir").mockReturnValue(
|
||||
relative(process.cwd(), directory),
|
||||
);
|
||||
const repository = join(directory, "repository");
|
||||
await mkdir(repository, { recursive: true });
|
||||
const git = repositoryGit(repository);
|
||||
@@ -1046,6 +1049,7 @@ describe("scan and patch workflow", () => {
|
||||
.split("\n")
|
||||
.find((line) => line.startsWith('{"path":'))!,
|
||||
) as { path: string; sha256: string };
|
||||
expect(isAbsolute(artifact.path)).toBe(true);
|
||||
const patch = await readFile(artifact.path, "utf8");
|
||||
expect(patch).toContain("+patch change");
|
||||
expect(patch).not.toContain("+user change");
|
||||
@@ -1059,7 +1063,11 @@ describe("scan and patch workflow", () => {
|
||||
output?.stdout.write("Patch complete.");
|
||||
return 0;
|
||||
},
|
||||
onRepositoryCommand: runGitRepositoryCommand,
|
||||
onRepositoryCommand: (command, args, cwd, options) => {
|
||||
const index = options?.environment?.["GIT_INDEX_FILE"];
|
||||
if (index !== undefined) expect(isAbsolute(index)).toBe(true);
|
||||
return runGitRepositoryCommand(command, args, cwd, options);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1431,7 +1439,7 @@ describe("scan and patch workflow", () => {
|
||||
test.each(["synthetic.provider", "openai"])(
|
||||
"preserves %s command-provider authentication when patching after a scan",
|
||||
async (provider) => {
|
||||
const home = join(tmpdir(), "synthetic-auth-home");
|
||||
const home = join(os.tmpdir(), "synthetic-auth-home");
|
||||
let providerOverride: string | undefined;
|
||||
const outcome = await runWorkflow(
|
||||
[
|
||||
|
||||
@@ -5049,6 +5049,25 @@ describe("CLI", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("reports an unreadable mock scan artifact as a local failure", async () => {
|
||||
const message =
|
||||
"Could not save the mock scan: scan-manifest.json: [Errno 13] Permission denied";
|
||||
const { stdout, stderr, runCli } = createCliTest(main);
|
||||
const deps = dependencies();
|
||||
deps.createSecurity = () => failingSecurity(message);
|
||||
|
||||
expect(
|
||||
await runCli(["scan", ".", "--mock", "--json", "--verbose"], deps),
|
||||
).toBe(2);
|
||||
expect(JSON.parse(stdout.text())).toEqual({
|
||||
status: "failed",
|
||||
code: "SCAN_FAILED",
|
||||
message,
|
||||
});
|
||||
expect(stderr.text()).toContain(message);
|
||||
expect(stderr.text()).toContain('scan.failed classification="local"');
|
||||
});
|
||||
|
||||
test("keeps model authorization advice for genuine transport failures", async () => {
|
||||
// The bypass must not swallow real 401/403 handling, and the advice must
|
||||
// still replace upstream text that can name the organization or project.
|
||||
|
||||
@@ -125,7 +125,7 @@ for (const mode of [
|
||||
},
|
||||
undefined,
|
||||
controller.signal,
|
||||
mode.startsWith("archive-"),
|
||||
{ registrationHandshake: mode.startsWith("archive-") },
|
||||
);
|
||||
} finally {
|
||||
observer.mockRestore();
|
||||
|
||||
@@ -24,11 +24,14 @@ import {
|
||||
} from "../src/contract.js";
|
||||
import type { NormalizedTarget, ScanExpectation } from "../src/index.js";
|
||||
import { PLUGIN_ROOT } from "./plugin-root.js";
|
||||
import { useTestPython } from "./support/python.js";
|
||||
import { runPython } from "./support/python-probe.js";
|
||||
import { createContractTestFixtures } from "./support/contract-fixture.js";
|
||||
import { readJson as readJsonFile, writeJson } from "./support/json.js";
|
||||
import { runTestInSubprocess } from "./support/test-subprocess.js";
|
||||
|
||||
const pythonExecutable = useTestPython();
|
||||
|
||||
const EXAMPLE = join(PLUGIN_ROOT, "examples", "legacy-completed-scan");
|
||||
const { temporaryDirectory, cleanup, copyExample } =
|
||||
createContractTestFixtures();
|
||||
@@ -50,7 +53,7 @@ async function reseal(scanDir: string): Promise<void> {
|
||||
}
|
||||
|
||||
function pythonExport(scanDir: string) {
|
||||
return runPython(process.env["PYTHON"] ?? Bun.which("python3") ?? "python", [
|
||||
return runPython(pythonExecutable() ?? "python", [
|
||||
join(PLUGIN_ROOT, "scripts", "finalize_scan_contract.py"),
|
||||
"--scan-dir",
|
||||
scanDir,
|
||||
@@ -89,14 +92,11 @@ describe("canonical scan contract", () => {
|
||||
}
|
||||
await writeJson(manifestPath, manifest);
|
||||
await loadContract(scanDir, { pluginRoot: PLUGIN_ROOT });
|
||||
const result = runPython(
|
||||
process.env["PYTHON"] ?? Bun.which("python3") ?? "python",
|
||||
[
|
||||
join(PLUGIN_ROOT, "scripts", "finalize_scan_contract.py"),
|
||||
"--scan-dir",
|
||||
scanDir,
|
||||
],
|
||||
);
|
||||
const result = runPython(pythonExecutable() ?? "python", [
|
||||
join(PLUGIN_ROOT, "scripts", "finalize_scan_contract.py"),
|
||||
"--scan-dir",
|
||||
scanDir,
|
||||
]);
|
||||
expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(0);
|
||||
for (const path of projections)
|
||||
expect(await readFile(join(scanDir, path), "utf8")).toBe(path);
|
||||
@@ -127,15 +127,12 @@ describe("canonical scan contract", () => {
|
||||
await writeJson(findingsPath, findings);
|
||||
await writeJson(manifestPath, manifest);
|
||||
await reseal(scanDir);
|
||||
const result = runPython(
|
||||
process.env["PYTHON"] ?? Bun.which("python3") ?? "python",
|
||||
[
|
||||
"-c",
|
||||
"import sys; from pathlib import Path; sys.path.insert(0, sys.argv[1]); from finalize_scan_contract import _prepare_scan_finalization; _prepare_scan_finalization(Path(sys.argv[2]))",
|
||||
join(PLUGIN_ROOT, "scripts"),
|
||||
scanDir,
|
||||
],
|
||||
);
|
||||
const result = runPython(pythonExecutable() ?? "python", [
|
||||
"-c",
|
||||
"import sys; from pathlib import Path; sys.path.insert(0, sys.argv[1]); from finalize_scan_contract import _prepare_scan_finalization; _prepare_scan_finalization(Path(sys.argv[2]))",
|
||||
join(PLUGIN_ROOT, "scripts"),
|
||||
scanDir,
|
||||
]);
|
||||
expect(result.exitCode, new TextDecoder().decode(result.stderr)).not.toBe(
|
||||
0,
|
||||
);
|
||||
@@ -512,14 +509,11 @@ describe("canonical scan contract", () => {
|
||||
manifest["scan"]["target"]["kind"] = kind;
|
||||
manifest["scan"]["target"]["revision"] = "";
|
||||
await writeJson(manifestPath, manifest);
|
||||
const result = runPython(
|
||||
process.env["PYTHON"] ?? Bun.which("python3") ?? "python",
|
||||
[
|
||||
join(PLUGIN_ROOT, "scripts", "finalize_scan_contract.py"),
|
||||
"--scan-dir",
|
||||
scanDir,
|
||||
],
|
||||
);
|
||||
const result = runPython(pythonExecutable() ?? "python", [
|
||||
join(PLUGIN_ROOT, "scripts", "finalize_scan_contract.py"),
|
||||
"--scan-dir",
|
||||
scanDir,
|
||||
]);
|
||||
expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(0);
|
||||
await loadContract(scanDir, { pluginRoot: PLUGIN_ROOT });
|
||||
},
|
||||
@@ -895,8 +889,7 @@ describe("canonical scan contract", () => {
|
||||
});
|
||||
|
||||
test("keeps bundled finalizer paths portable to Windows", () => {
|
||||
const python =
|
||||
process.env["PYTHON"] ?? Bun.which("python3") ?? Bun.which("python");
|
||||
const python = pythonExecutable();
|
||||
expect(python).not.toBeNull();
|
||||
const program = [
|
||||
"import json, sys",
|
||||
@@ -1109,8 +1102,7 @@ describe("canonical scan contract", () => {
|
||||
loadContract(scanDir, { pluginRoot: PLUGIN_ROOT }),
|
||||
).rejects.toThrow("duplicate artifact path");
|
||||
|
||||
const python =
|
||||
process.env["PYTHON"] ?? Bun.which("python3") ?? Bun.which("python");
|
||||
const python = pythonExecutable();
|
||||
expect(python).not.toBeNull();
|
||||
const result = runPython(python!, [
|
||||
join(PLUGIN_ROOT, "scripts", "finalize_scan_contract.py"),
|
||||
|
||||
@@ -2,9 +2,14 @@ import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { PLUGIN_ROOT } from "./plugin-root.js";
|
||||
import { useTestPython } from "./support/python.js";
|
||||
|
||||
const pythonExecutable = useTestPython();
|
||||
// Source-scope scenarios exercise many native Git commands on Windows.
|
||||
const previewTimeout = process.platform === "win32" ? 180_000 : 30_000;
|
||||
|
||||
function checkSourceScope(scenario: string, expected: unknown = null): void {
|
||||
const python = Bun.which("python3") ?? Bun.which("python") ?? Bun.which("py");
|
||||
const python = pythonExecutable();
|
||||
expect(python).not.toBeNull();
|
||||
const result = Bun.spawnSync(
|
||||
[
|
||||
@@ -22,114 +27,170 @@ function checkSourceScope(scenario: string, expected: unknown = null): void {
|
||||
}
|
||||
|
||||
describe("bundled finding previews", () => {
|
||||
test("reads only the immutable source objects selected for the scan", () => {
|
||||
checkSourceScope("boundaries", {
|
||||
selected: "1 public source",
|
||||
outside: null,
|
||||
additional: "1 selected file",
|
||||
repository: "1 private source",
|
||||
fileDescendant: null,
|
||||
traversal: null,
|
||||
absolute: null,
|
||||
redirected: null,
|
||||
escaped: null,
|
||||
legacyScoped: "1 public source",
|
||||
legacyUnmarkedFile: "1 selected file",
|
||||
legacyUnmarkedFileDescendant: null,
|
||||
legacyRoot: "1 private source",
|
||||
legacyKnownDirectory: "1 public source",
|
||||
legacyKnownFile: "1 selected file",
|
||||
legacyFileDescendant: null,
|
||||
emptyAuthority: null,
|
||||
dirty: null,
|
||||
fallback: "1 public source",
|
||||
rootControl: "1 public source",
|
||||
replacedFile: "1 selected file",
|
||||
replacedFileDescendant: null,
|
||||
removedDirectory: "1 nested source",
|
||||
offline: "1 public source",
|
||||
missingObject: null,
|
||||
});
|
||||
}, 30_000);
|
||||
test(
|
||||
"reads only the immutable source objects selected for the scan",
|
||||
() => {
|
||||
checkSourceScope("boundaries", {
|
||||
selected: "1 public source",
|
||||
outside: null,
|
||||
additional: "1 selected file",
|
||||
repository: "1 private source",
|
||||
fileDescendant: null,
|
||||
traversal: null,
|
||||
absolute: null,
|
||||
redirected: null,
|
||||
escaped: null,
|
||||
legacyScoped: "1 public source",
|
||||
legacyUnmarkedFile: "1 selected file",
|
||||
legacyUnmarkedFileDescendant: null,
|
||||
legacyRoot: "1 private source",
|
||||
legacyKnownDirectory: "1 public source",
|
||||
legacyKnownFile: "1 selected file",
|
||||
legacyFileDescendant: null,
|
||||
emptyAuthority: null,
|
||||
dirty: null,
|
||||
fallback: "1 public source",
|
||||
rootControl: "1 public source",
|
||||
replacedFile: "1 selected file",
|
||||
replacedFileDescendant: null,
|
||||
removedDirectory: "1 nested source",
|
||||
offline: "1 public source",
|
||||
missingObject: null,
|
||||
});
|
||||
},
|
||||
previewTimeout,
|
||||
);
|
||||
|
||||
test("keeps captured filesystem aliases usable after their source paths disappear", () => {
|
||||
checkSourceScope("aliases", {
|
||||
case: expect.any(Boolean),
|
||||
unicode: expect.any(Boolean),
|
||||
nonAscii: expect.any(Boolean),
|
||||
collisionChecked: true,
|
||||
});
|
||||
}, 30_000);
|
||||
test(
|
||||
"keeps captured filesystem aliases usable after their source paths disappear",
|
||||
() => {
|
||||
checkSourceScope("aliases", {
|
||||
case: expect.any(Boolean),
|
||||
unicode: expect.any(Boolean),
|
||||
nonAscii: expect.any(Boolean),
|
||||
collisionChecked: true,
|
||||
});
|
||||
},
|
||||
previewTimeout,
|
||||
);
|
||||
|
||||
test("requires distinct filesystem witnesses for colliding descendants", () => {
|
||||
checkSourceScope("descendant_aliases");
|
||||
}, 30_000);
|
||||
test(
|
||||
"requires distinct filesystem witnesses for colliding descendants",
|
||||
() => {
|
||||
checkSourceScope("descendant_aliases");
|
||||
},
|
||||
previewTimeout,
|
||||
);
|
||||
|
||||
test("keeps saved immutable objects readable after replacement refs change", () => {
|
||||
checkSourceScope("replacements");
|
||||
}, 30_000);
|
||||
test(
|
||||
"keeps saved immutable objects readable after replacement refs change",
|
||||
() => {
|
||||
checkSourceScope("replacements");
|
||||
},
|
||||
previewTimeout,
|
||||
);
|
||||
|
||||
test("does not run working-tree filters when registering a committed-ref scan", () => {
|
||||
checkSourceScope("replacement_filters");
|
||||
}, 30_000);
|
||||
test(
|
||||
"does not run working-tree filters when registering a committed-ref scan",
|
||||
() => {
|
||||
checkSourceScope("replacement_filters");
|
||||
},
|
||||
previewTimeout,
|
||||
);
|
||||
|
||||
test("omits source authority when replacement refs changed the scanned tree", () => {
|
||||
checkSourceScope("replacement_snapshot");
|
||||
}, 30_000);
|
||||
test(
|
||||
"omits source authority when replacement refs changed the scanned tree",
|
||||
() => {
|
||||
checkSourceScope("replacement_snapshot");
|
||||
},
|
||||
previewTimeout,
|
||||
);
|
||||
|
||||
test("omits stale committed excerpts for working-tree diff scans", () => {
|
||||
checkSourceScope("working_tree_excerpt", {
|
||||
authorityOmitted: true,
|
||||
currentExcerptOmitted: true,
|
||||
legacyExcerptOmitted: true,
|
||||
rangeExcerptPreserved: true,
|
||||
});
|
||||
}, 30_000);
|
||||
test(
|
||||
"omits stale committed excerpts for working-tree diff scans",
|
||||
() => {
|
||||
checkSourceScope("working_tree_excerpt", {
|
||||
authorityOmitted: true,
|
||||
currentExcerptOmitted: true,
|
||||
legacyExcerptOmitted: true,
|
||||
rangeExcerptPreserved: true,
|
||||
});
|
||||
},
|
||||
previewTimeout,
|
||||
);
|
||||
|
||||
test("indexes Git names once for large explicit scope lists", () => {
|
||||
checkSourceScope("indexed_scopes", 256);
|
||||
}, 30_000);
|
||||
test(
|
||||
"indexes Git names once for large explicit scope lists",
|
||||
() => {
|
||||
checkSourceScope("indexed_scopes", 256);
|
||||
},
|
||||
previewTimeout,
|
||||
);
|
||||
|
||||
test("selects source excerpts from the displayed finding locations", () => {
|
||||
checkSourceScope("display_locations", 8);
|
||||
}, 30_000);
|
||||
test(
|
||||
"selects source excerpts from the displayed finding locations",
|
||||
() => {
|
||||
checkSourceScope("display_locations", 8);
|
||||
},
|
||||
previewTimeout,
|
||||
);
|
||||
|
||||
test("does not grant source scope through a selected directory link", () => {
|
||||
checkSourceScope("selected_redirects");
|
||||
}, 30_000);
|
||||
test(
|
||||
"does not grant source scope through a selected directory link",
|
||||
() => {
|
||||
checkSourceScope("selected_redirects");
|
||||
},
|
||||
previewTimeout,
|
||||
);
|
||||
|
||||
test("rejects unsafe finding locations before invoking Git", () => {
|
||||
checkSourceScope("unsafe_locations");
|
||||
}, 30_000);
|
||||
test(
|
||||
"rejects unsafe finding locations before invoking Git",
|
||||
() => {
|
||||
checkSourceScope("unsafe_locations");
|
||||
},
|
||||
previewTimeout,
|
||||
);
|
||||
|
||||
test("does not treat links or reparse points as filesystem alias evidence", () => {
|
||||
checkSourceScope("alias_evidence", {
|
||||
ordinary: true,
|
||||
hardlink: false,
|
||||
symlink: false,
|
||||
reparse: false,
|
||||
});
|
||||
}, 30_000);
|
||||
test(
|
||||
"does not treat links or reparse points as filesystem alias evidence",
|
||||
() => {
|
||||
checkSourceScope("alias_evidence", {
|
||||
ordinary: true,
|
||||
hardlink: false,
|
||||
symlink: false,
|
||||
reparse: false,
|
||||
});
|
||||
},
|
||||
previewTimeout,
|
||||
);
|
||||
|
||||
test("keeps subdirectory and linked-worktree targets bound to their selected tree", () => {
|
||||
checkSourceScope("worktrees");
|
||||
}, 30_000);
|
||||
test(
|
||||
"keeps subdirectory and linked-worktree targets bound to their selected tree",
|
||||
() => {
|
||||
checkSourceScope("worktrees");
|
||||
},
|
||||
previewTimeout,
|
||||
);
|
||||
|
||||
test.each(["workspace", "prompt", "headless", "deep", "cli"])(
|
||||
"records source authority through the %s scan-start path",
|
||||
(writer) => {
|
||||
checkSourceScope(`writer_${writer}`, writer);
|
||||
},
|
||||
30_000,
|
||||
previewTimeout,
|
||||
);
|
||||
|
||||
test("preserves legacy scans and separately owned migration history", () => {
|
||||
checkSourceScope("migration");
|
||||
}, 30_000);
|
||||
test(
|
||||
"preserves legacy scans and separately owned migration history",
|
||||
() => {
|
||||
checkSourceScope("migration");
|
||||
},
|
||||
previewTimeout,
|
||||
);
|
||||
});
|
||||
|
||||
test("bundled finding previews normalize details without changing stored findings", () => {
|
||||
const python = Bun.which("python3") ?? Bun.which("python") ?? Bun.which("py");
|
||||
const python = pythonExecutable();
|
||||
expect(python).not.toBeNull();
|
||||
const original = {
|
||||
attackPath: { likelihood: "medium" },
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { expect, test } from "bun:test";
|
||||
import * as os from "node:os";
|
||||
import { dirname, isAbsolute, relative } from "node:path";
|
||||
import { expect, spyOn, test } from "bun:test";
|
||||
import { MAX_CODEX_INPUT_CHARACTERS } from "../src/codex-prompt.js";
|
||||
import { prepareFindingPrompt } from "../src/finding-prompt.js";
|
||||
|
||||
@@ -20,6 +21,8 @@ test.each([false, true])(
|
||||
evidence: '"\\\n🦞'.repeat(200_000),
|
||||
tail: "Final evidence",
|
||||
});
|
||||
const temporaryRoot = relative(process.cwd(), os.tmpdir()) || ".";
|
||||
using _temporary = spyOn(os, "tmpdir").mockReturnValue(temporaryRoot);
|
||||
let path = "";
|
||||
const run = async () => {
|
||||
await using prepared = await prepareFindingPrompt(
|
||||
@@ -28,6 +31,7 @@ test.each([false, true])(
|
||||
);
|
||||
expect(prepared.prompt.length).toBeLessThan(MAX_CODEX_INPUT_CHARACTERS);
|
||||
path = JSON.parse(prepared.prompt.match(/^".*finding\.json"$/m)![0]);
|
||||
expect(isAbsolute(path)).toBe(true);
|
||||
expect(await readFile(path, "utf8")).toBe(finding);
|
||||
if (process.platform !== "win32") {
|
||||
expect((await stat(path)).mode & 0o777).toBe(0o600);
|
||||
|
||||
@@ -24,11 +24,14 @@ import { ScanResult } from "../src/result.js";
|
||||
import { runWorkbench } from "../src/runtime.js";
|
||||
import { VERSION } from "../src/version.js";
|
||||
import { PLUGIN_ROOT } from "./plugin-root.js";
|
||||
import { useTestPython } from "./support/python.js";
|
||||
import { runTestInSubprocess } from "./support/test-subprocess.js";
|
||||
import { createApiTestFixtures } from "./support/temporary-directories.js";
|
||||
import { rejecting } from "./support/errors.js";
|
||||
import { TestClient } from "./support/api-client.js";
|
||||
|
||||
const pythonExecutable = useTestPython();
|
||||
|
||||
const { temporaryDirectories: roots, cleanup } = createApiTestFixtures();
|
||||
afterEach(cleanup);
|
||||
|
||||
@@ -86,7 +89,7 @@ async function fixture(format: "csv" | "json" = "csv") {
|
||||
join(await realpath(tmpdir()), "import-scan-test-"),
|
||||
);
|
||||
roots.track(root);
|
||||
const python = Bun.which("python3") ?? Bun.which("python");
|
||||
const python = pythonExecutable();
|
||||
expect(python).not.toBeNull();
|
||||
const stateDirectory = join(root, "state");
|
||||
const environment = {
|
||||
@@ -170,6 +173,7 @@ test.each(["completed", "failed", "interrupted", "preview"] as const)(
|
||||
runTestInSubprocess(
|
||||
import.meta.path,
|
||||
`scratch cleanup failure preserves the ${outcome} import outcome`,
|
||||
{ PYTHON: pythonExecutable() ?? undefined },
|
||||
)
|
||||
)
|
||||
return;
|
||||
@@ -634,6 +638,7 @@ test.each(["regular file", "symbolic link"])(
|
||||
runTestInSubprocess(
|
||||
import.meta.path,
|
||||
`import rejects a source replaced with a ${replacement} before reading`,
|
||||
{ PYTHON: pythonExecutable() ?? undefined },
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
} from "node:fs/promises";
|
||||
import * as filesystem from "node:fs/promises";
|
||||
import * as os from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { dirname, join, relative, sep } from "node:path";
|
||||
import { afterEach, describe, expect, mock, spyOn, test } from "bun:test";
|
||||
import { strToU8, zipSync } from "fflate";
|
||||
import { ConfigurationError } from "../src/errors.js";
|
||||
@@ -896,6 +896,37 @@ describe("scan knowledge bases", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test.each(["relative", "linked parent"])(
|
||||
"stages knowledge in the worker-readable temporary directory: %s",
|
||||
async (spelling) => {
|
||||
const root = await temporaryDirectory();
|
||||
const source = join(root, "policy.md");
|
||||
await writeFile(source, "Synthetic policy.");
|
||||
const staging = join(root, "staging");
|
||||
await mkdir(staging);
|
||||
let temporary = relative(process.cwd(), staging);
|
||||
if (spelling === "linked parent") {
|
||||
const child = join(staging, "child");
|
||||
const link = join(root, "alias");
|
||||
await mkdir(child);
|
||||
await symlink(
|
||||
child,
|
||||
link,
|
||||
process.platform === "win32" ? "junction" : "dir",
|
||||
);
|
||||
temporary = link + sep + "..";
|
||||
}
|
||||
const expected = await filesystem.realpath(temporary);
|
||||
using _temporary = spyOn(os, "tmpdir").mockReturnValue(temporary);
|
||||
const prepared = await prepareKnowledgeBase([source]);
|
||||
temporaryDirectories.track(prepared.path);
|
||||
expect(dirname(prepared.path)).toBe(expected);
|
||||
expect(await extractedDocuments(prepared.path)).toEqual([
|
||||
"Synthetic policy.",
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
test("skips macOS metadata files copied next to documents", async () => {
|
||||
const root = await temporaryDirectory();
|
||||
await writeFile(join(root, "guide.md"), "Rotate admin keys monthly.");
|
||||
|
||||
@@ -43,11 +43,14 @@ test.skipIf(process.platform !== "win32")(
|
||||
);
|
||||
const fixture = join(root, "python.test.ts");
|
||||
const helper = new URL("./support/python.ts", import.meta.url).href;
|
||||
const isolated = new URL("./support/test-subprocess.ts", import.meta.url)
|
||||
.href;
|
||||
await writeFile(
|
||||
fixture,
|
||||
[
|
||||
'import { expect, test } from "bun:test";',
|
||||
`import { useTestPython } from ${JSON.stringify(helper)};`,
|
||||
`import { runTestInSubprocess } from ${JSON.stringify(isolated)};`,
|
||||
"const resolve = useTestPython();",
|
||||
'test("uses the prepared Python", () => {',
|
||||
" expect(resolve()).toBe(process.env.EXPECTED_PYTHON);",
|
||||
@@ -59,6 +62,10 @@ test.skipIf(process.platform !== "win32")(
|
||||
" expect(resolve()).toBe(process.env.EXPECTED_PYTHON);",
|
||||
" }",
|
||||
"});",
|
||||
'test("isolated child reuses the prepared Python", () => {',
|
||||
' if (runTestInSubprocess(import.meta.path, "isolated child reuses the prepared Python", { PYTHON: resolve() ?? undefined })) return;',
|
||||
" expect(resolve()).toBe(process.env.EXPECTED_PYTHON);",
|
||||
"}, 30000);",
|
||||
].join("\n"),
|
||||
);
|
||||
for (const configured of [python, ""]) {
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createMarketplace } from "../src/runtime.js";
|
||||
import { createApiTestFixtures } from "./support/temporary-directories.js";
|
||||
|
||||
const { temporaryDirectory, cleanup } = createApiTestFixtures();
|
||||
afterEach(cleanup);
|
||||
const pluginRoot = fileURLToPath(
|
||||
new URL("../../../plugins/codex-security/", import.meta.url),
|
||||
);
|
||||
const parentSandbox = new URL(
|
||||
"../../../plugins/codex-security/mcp-app/src/deep-scan/parent-sandbox.ts",
|
||||
import.meta.url,
|
||||
).href;
|
||||
|
||||
test.each(["bundled", "legacy projection", "declared projection"])(
|
||||
"%s forwards each scan's repository through the MCP environment",
|
||||
async (configuration) => {
|
||||
const root = await temporaryDirectory();
|
||||
let manifest = join(pluginRoot, ".mcp.json");
|
||||
if (configuration !== "bundled") {
|
||||
const selected = join(root, "selected plugin");
|
||||
await mkdir(join(selected, ".codex-plugin"), { recursive: true });
|
||||
await writeFile(
|
||||
join(selected, ".codex-plugin", "plugin.json"),
|
||||
JSON.stringify({ name: "codex-security", version: "1.2.3" }),
|
||||
);
|
||||
await writeFile(
|
||||
join(selected, ".mcp.json"),
|
||||
JSON.stringify({
|
||||
mcpServers: {
|
||||
"codex-security": {
|
||||
command: "./scripts/launch_codex_security_mcp",
|
||||
env_vars:
|
||||
configuration === "declared projection"
|
||||
? ["CODEX_SECURITY_PLUGIN_ROOT", "CODEX_SECURITY_REPOSITORY"]
|
||||
: [],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const marketplace = await createMarketplace(join(root, "home"), selected);
|
||||
manifest = join(marketplace, "plugins", "codex-security", ".mcp.json");
|
||||
}
|
||||
const mcp = JSON.parse(await readFile(manifest, "utf8"));
|
||||
const allowed: string[] = mcp.mcpServers["codex-security"].env_vars;
|
||||
expect(
|
||||
allowed.filter((name) => name === "CODEX_SECURITY_REPOSITORY"),
|
||||
).toHaveLength(1);
|
||||
|
||||
for (const scan of ["fresh", "resumed"]) {
|
||||
const source = join(root, `${scan} source [fixture]`);
|
||||
const credentials = join(source, "config.toml");
|
||||
const parentEnvironment = {
|
||||
CODEX_SECURITY_PLUGIN_ROOT: pluginRoot,
|
||||
CODEX_SECURITY_REPOSITORY: source,
|
||||
SYNTHETIC_UNDECLARED_VALUE: "ambient fixture",
|
||||
};
|
||||
// Model the native MCP allowlist, then inspect the actual child process.
|
||||
const environment = Object.fromEntries(
|
||||
Object.entries(parentEnvironment).filter(([name]) =>
|
||||
allowed.includes(name),
|
||||
),
|
||||
);
|
||||
const entries = [
|
||||
{ path: { type: "special", value: { kind: "root" } }, access: "read" },
|
||||
{ path: { type: "path", path: source }, access: "read" },
|
||||
{ path: { type: "path", path: credentials }, access: "deny" },
|
||||
];
|
||||
const extra = {
|
||||
_meta: {
|
||||
"codex/sandbox-state-meta": {
|
||||
permissionProfile: {
|
||||
type: "managed",
|
||||
file_system: { type: "restricted", entries },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
const child = spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
"--eval",
|
||||
`import { resolveDeepWorkerParentSandbox } from ${JSON.stringify(parentSandbox)};
|
||||
const extra = JSON.parse(process.argv[1]);
|
||||
const inherited = resolveDeepWorkerParentSandbox(extra);
|
||||
extra._meta["codex/sandbox-state-meta"].permissionProfile.file_system.entries.splice(1, 1);
|
||||
console.log(JSON.stringify({
|
||||
repository: process.env.CODEX_SECURITY_REPOSITORY,
|
||||
ambient: process.env.SYNTHETIC_UNDECLARED_VALUE,
|
||||
inherited,
|
||||
withoutNamedGrant: resolveDeepWorkerParentSandbox(extra),
|
||||
}));`,
|
||||
JSON.stringify(extra),
|
||||
],
|
||||
{
|
||||
env: { SystemRoot: process.env["SystemRoot"], ...environment },
|
||||
encoding: "utf8",
|
||||
windowsHide: true,
|
||||
},
|
||||
);
|
||||
expect(child.error).toBeUndefined();
|
||||
expect(child.stderr).toBe("");
|
||||
expect(child.status).toBe(0);
|
||||
expect(JSON.parse(child.stdout)).toEqual({
|
||||
repository: source,
|
||||
inherited: {
|
||||
filesystemDenies: [],
|
||||
literalFilesystemDenies: [credentials],
|
||||
...(process.platform === "win32" ? { sourceReadRoot: source } : {}),
|
||||
},
|
||||
withoutNamedGrant: {
|
||||
filesystemDenies: [],
|
||||
literalFilesystemDenies: [credentials],
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -1,5 +1,15 @@
|
||||
import { afterEach, expect, spyOn, test } from "bun:test";
|
||||
import { cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import * as files from "node:fs/promises";
|
||||
import {
|
||||
cp,
|
||||
mkdir,
|
||||
readFile,
|
||||
readdir,
|
||||
rename,
|
||||
rm,
|
||||
symlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import * as timers from "node:timers/promises";
|
||||
import * as executable from "../src/codex-sdk-environment.js";
|
||||
@@ -57,6 +67,7 @@ const fakeCli = `
|
||||
process.exit(step.exit);
|
||||
}
|
||||
const installedPath = join(home, "installed");
|
||||
fs.rmSync(installedPath, { recursive: true, force: true });
|
||||
fs.cpSync(staged, installedPath, { recursive: true });
|
||||
if (step.stale) fs.writeFileSync(join(installedPath, "marker.txt"), "previous");
|
||||
if (step.extraSkill === "installed") addSkill(installedPath, "skills/unselected");
|
||||
@@ -118,6 +129,7 @@ async function fixture(
|
||||
const command = nodeCommand().command;
|
||||
return {
|
||||
command,
|
||||
selected,
|
||||
previous,
|
||||
record,
|
||||
previousReceipt,
|
||||
@@ -204,10 +216,272 @@ test
|
||||
result.installedRoot,
|
||||
);
|
||||
expect(await f.remaining()).toHaveLength(0);
|
||||
expect((await f.install()).installedRoot).toBe(result.installedRoot);
|
||||
expect(resolver).toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
test("only the bundled installer reuses its regenerated command output", async () => {
|
||||
const f = await fixture([{}, {}, {}], "regenerated");
|
||||
using resolver = spyOn(
|
||||
executable,
|
||||
"resolveBundledCodexExecutable",
|
||||
).mockReturnValue(f.previous);
|
||||
await f.install();
|
||||
expect(await f.remaining()).toHaveLength(2);
|
||||
|
||||
resolver.mockReturnValue(f.command);
|
||||
const installed = await f.install();
|
||||
expect(await f.remaining()).toHaveLength(1);
|
||||
expect((await f.install()).installedRoot).toBe(installed.installedRoot);
|
||||
expect(await f.remaining()).toHaveLength(1);
|
||||
|
||||
resolver.mockReturnValue(f.previous);
|
||||
await f.install();
|
||||
expect(await f.remaining()).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("rechecks the full marketplace selection and the recovered installed files", async () => {
|
||||
const f = await fixture([{}, {}, {}], "regenerated");
|
||||
using resolver = spyOn(
|
||||
executable,
|
||||
"resolveBundledCodexExecutable",
|
||||
).mockReturnValue(f.command);
|
||||
const { installedRoot } = await f.install();
|
||||
const staleSkill = join(
|
||||
f.selected,
|
||||
".codex-plugin",
|
||||
"migrated-command-skills",
|
||||
"source-command-retired",
|
||||
"SKILL.md",
|
||||
);
|
||||
await writeFile(staleSkill, "revised stale source");
|
||||
await f.install();
|
||||
expect(await f.remaining()).toHaveLength(1);
|
||||
|
||||
await mkdir(join(installedRoot, "skills", "other-selection"), {
|
||||
recursive: true,
|
||||
});
|
||||
await writeFile(
|
||||
join(installedRoot, "skills", "other-selection", "SKILL.md"),
|
||||
"other",
|
||||
);
|
||||
await f.install();
|
||||
expect(await f.remaining()).toHaveLength(0);
|
||||
expect(resolver).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("preserves runtime files when the selection already contains the native command output", async () => {
|
||||
const f = await fixture([{}, {}, {}, {}]);
|
||||
using resolver = spyOn(
|
||||
executable,
|
||||
"resolveBundledCodexExecutable",
|
||||
).mockReturnValue(f.command);
|
||||
const { installedRoot } = await f.install();
|
||||
const migration = join(".codex-plugin", "migrated-command-skills");
|
||||
const generated = join(installedRoot, migration);
|
||||
await cp(generated, join(f.selected, migration), { recursive: true });
|
||||
await f.install();
|
||||
const receipt = await readFile(f.record, "utf8");
|
||||
expect(JSON.parse(receipt).nativeCommandMigration).toMatch(/^sha256:/u);
|
||||
const bytecode = join(installedRoot, "scripts", "__pycache__");
|
||||
await mkdir(bytecode, { recursive: true });
|
||||
const cached = join(bytecode, "helper.cpython-312.pyc");
|
||||
await writeFile(cached, "runtime-generated");
|
||||
|
||||
expect((await f.install()).installedRoot).toBe(installedRoot);
|
||||
expect(await f.remaining()).toHaveLength(2);
|
||||
expect(await readFile(cached, "utf8")).toBe("runtime-generated");
|
||||
expect(await readFile(f.record, "utf8")).toBe(receipt);
|
||||
|
||||
const skill = join(generated, "source-command-sample", "SKILL.md");
|
||||
await rm(skill);
|
||||
await f.install();
|
||||
expect(await f.remaining()).toHaveLength(1);
|
||||
expect(await readFile(skill, "utf8")).toBe("synthetic skill");
|
||||
await mkdir(join(generated, "foreign-command"));
|
||||
await writeFile(join(generated, "foreign-command", "SKILL.md"), "foreign");
|
||||
await f.install();
|
||||
expect(await f.remaining()).toHaveLength(0);
|
||||
expect(await readdir(generated)).toEqual(["source-command-sample"]);
|
||||
expect(resolver).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("a link replacing the installed command migration directory requires reinstall", async () => {
|
||||
const f = await fixture([{}, {}], "regenerated");
|
||||
using resolver = spyOn(
|
||||
executable,
|
||||
"resolveBundledCodexExecutable",
|
||||
).mockReturnValue(f.command);
|
||||
const { installedRoot } = await f.install();
|
||||
const migration = join(
|
||||
installedRoot,
|
||||
".codex-plugin",
|
||||
"migrated-command-skills",
|
||||
);
|
||||
const outside = await temporaryDirectory();
|
||||
await writeFile(join(outside, "marker.txt"), "unrelated");
|
||||
await rm(migration, { recursive: true });
|
||||
await symlink(
|
||||
outside,
|
||||
migration,
|
||||
process.platform === "win32" ? "junction" : "dir",
|
||||
);
|
||||
await f.install();
|
||||
expect(await f.remaining()).toHaveLength(0);
|
||||
expect(await readFile(join(outside, "marker.txt"), "utf8")).toBe("unrelated");
|
||||
expect(resolver).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test.each([
|
||||
"missing file",
|
||||
"changed bytes",
|
||||
"renamed skill",
|
||||
"changed file type",
|
||||
"restored source with changed output",
|
||||
"extra output",
|
||||
"missing directory",
|
||||
"nested link",
|
||||
"previously absent",
|
||||
] as const)(
|
||||
"repairs %s in a recorded native command migration",
|
||||
async (damage) => {
|
||||
const absent = damage === "previously absent";
|
||||
const f = await fixture([{}, {}], absent ? "removed" : "regenerated");
|
||||
using resolver = spyOn(
|
||||
executable,
|
||||
"resolveBundledCodexExecutable",
|
||||
).mockReturnValue(f.command);
|
||||
const { installedRoot } = await f.install();
|
||||
const migration = join(
|
||||
installedRoot,
|
||||
".codex-plugin",
|
||||
"migrated-command-skills",
|
||||
);
|
||||
const skill = join(migration, "source-command-sample");
|
||||
const file = join(skill, "SKILL.md");
|
||||
const outside = await temporaryDirectory();
|
||||
const sentinel = join(outside, "SKILL.md");
|
||||
await writeFile(sentinel, "outside");
|
||||
switch (damage) {
|
||||
case "missing file":
|
||||
await rm(file);
|
||||
break;
|
||||
case "restored source with changed output":
|
||||
await cp(
|
||||
join(f.selected, ".codex-plugin", "migrated-command-skills"),
|
||||
migration,
|
||||
{ recursive: true },
|
||||
);
|
||||
await writeFile(file, "different skill");
|
||||
break;
|
||||
case "changed bytes":
|
||||
await writeFile(file, "different skill");
|
||||
break;
|
||||
case "renamed skill":
|
||||
await rename(skill, join(migration, "other-command-name"));
|
||||
break;
|
||||
case "changed file type":
|
||||
await rm(file);
|
||||
await mkdir(file);
|
||||
break;
|
||||
case "extra output":
|
||||
await writeFile(join(skill, "extra.md"), "unselected");
|
||||
break;
|
||||
case "missing directory":
|
||||
await rm(migration, { recursive: true });
|
||||
break;
|
||||
case "nested link":
|
||||
await rm(skill, { recursive: true });
|
||||
await symlink(
|
||||
outside,
|
||||
skill,
|
||||
process.platform === "win32" ? "junction" : "dir",
|
||||
);
|
||||
break;
|
||||
case "previously absent":
|
||||
await mkdir(migration);
|
||||
break;
|
||||
}
|
||||
await f.install();
|
||||
expect(await f.remaining()).toHaveLength(0);
|
||||
if (absent) {
|
||||
await expect(readdir(migration)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
} else {
|
||||
expect(await readdir(migration)).toEqual(["source-command-sample"]);
|
||||
expect(await readdir(skill)).toEqual(["SKILL.md"]);
|
||||
expect(await readFile(file, "utf8")).toBe("synthetic skill");
|
||||
}
|
||||
expect(await readFile(sentinel, "utf8")).toBe("outside");
|
||||
expect(resolver).toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
test("canceling a generated skill read leaves its native receipt and caller reason intact", async () => {
|
||||
const f = await fixture([{}], "regenerated");
|
||||
using resolver = spyOn(
|
||||
executable,
|
||||
"resolveBundledCodexExecutable",
|
||||
).mockReturnValue(f.command);
|
||||
const { installedRoot } = await f.install();
|
||||
const generated = join(
|
||||
installedRoot,
|
||||
".codex-plugin",
|
||||
"migrated-command-skills",
|
||||
"source-command-sample",
|
||||
"SKILL.md",
|
||||
);
|
||||
const receipt = await readFile(f.record);
|
||||
const controller = new AbortController();
|
||||
const reason = new Error(
|
||||
"synthetic cancellation while reading generated skill",
|
||||
);
|
||||
const prior = files.open;
|
||||
using opening = spyOn(files, "open").mockImplementation(async (...args) => {
|
||||
const result = await prior(...args);
|
||||
if (String(args[0]) === generated) controller.abort(reason);
|
||||
return result;
|
||||
});
|
||||
await expect(f.install(controller.signal)).rejects.toBe(reason);
|
||||
expect(await f.remaining()).toHaveLength(0);
|
||||
expect(await readFile(f.record)).toEqual(receipt);
|
||||
expect(opening).toHaveBeenCalled();
|
||||
expect(resolver).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("checks the generated output and selected files in the same installation", async () => {
|
||||
const f = await fixture([{}, {}], "regenerated");
|
||||
using resolver = spyOn(
|
||||
executable,
|
||||
"resolveBundledCodexExecutable",
|
||||
).mockReturnValue(f.command);
|
||||
const { installedRoot } = await f.install();
|
||||
const previous = join(await temporaryDirectory(), "previous");
|
||||
const original = files.realpath;
|
||||
let replaced = false;
|
||||
using resolving = spyOn(files, "realpath").mockImplementation((async (
|
||||
...args: Parameters<typeof original>
|
||||
) => {
|
||||
if (!replaced && args[0] === installedRoot) {
|
||||
replaced = true;
|
||||
await rename(installedRoot, previous);
|
||||
await cp(previous, installedRoot, { recursive: true });
|
||||
await writeFile(join(installedRoot, "marker.txt"), "other selection");
|
||||
}
|
||||
return original(...args);
|
||||
}) as typeof original);
|
||||
await f.install();
|
||||
expect(replaced).toBe(true);
|
||||
expect(await f.remaining()).toHaveLength(0);
|
||||
expect(await readFile(join(installedRoot, "marker.txt"), "utf8")).toBe(
|
||||
"selected",
|
||||
);
|
||||
expect(resolving).toHaveBeenCalled();
|
||||
expect(resolver).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test.skipIf(process.platform !== "win32").each([
|
||||
[
|
||||
"persistent denial",
|
||||
|
||||
@@ -907,6 +907,25 @@ describe("plugin runtime preparation", () => {
|
||||
).toBeDefined();
|
||||
});
|
||||
|
||||
test("installs a local marketplace when the Codex home contains a literal hash", async () => {
|
||||
const root = await temporaryDirectory();
|
||||
const home = join(root, "codex #team");
|
||||
const source = await bundledPluginRoot();
|
||||
const installed = await bootstrapPlugin(home, source, {
|
||||
environment: {
|
||||
HOME: root,
|
||||
USERPROFILE: root,
|
||||
PATH: process.env["PATH"],
|
||||
SystemRoot: process.env["SystemRoot"],
|
||||
},
|
||||
});
|
||||
|
||||
const manifest = join(".codex-plugin", "plugin.json");
|
||||
expect(
|
||||
await readFile(join(installed.installedRoot, manifest), "utf8"),
|
||||
).toBe(await readFile(join(source, manifest), "utf8"));
|
||||
});
|
||||
|
||||
test("keeps local marketplace failures separate from installer failures", async () => {
|
||||
const root = await temporaryDirectory();
|
||||
const selected = await plugin(root);
|
||||
@@ -1028,7 +1047,7 @@ for await (const line of createInterface({ input: process.stdin })) {
|
||||
const result = request.method === "initialize"
|
||||
? { protocolVersion: request.params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "synthetic-launcher", version: "1" } }
|
||||
: request.method === "tools/list"
|
||||
? { tools: [{ name: "probe", description: "Reports test launcher details.", _meta: { launch: { pluginRoot, args: process.argv.slice(2), execArgv: process.execArgv, cwd: process.cwd(), entry: process.argv[1] } }, inputSchema: { type: "object", properties: {} } }] }
|
||||
? { tools: [{ name: "probe", description: "Reports test launcher details.", _meta: { launch: { pluginRoot, repository: process.env.CODEX_SECURITY_REPOSITORY, ambient: process.env.SYNTHETIC_UNDECLARED_VALUE, args: process.argv.slice(2), execArgv: process.execArgv, cwd: process.cwd(), entry: process.argv[1] } }, inputSchema: { type: "object", properties: {} } }] }
|
||||
: request.method === "resources/list" ? { resources: [] }
|
||||
: request.method === "resources/templates/list" ? { resourceTemplates: [] }
|
||||
: {};
|
||||
@@ -1106,12 +1125,11 @@ for await (const line of createInterface({ input: process.stdin })) {
|
||||
cwd: mcp.mcpServers["codex-security"].cwd,
|
||||
startup_timeout_sec:
|
||||
mcp.mcpServers["codex-security"].startup_timeout_sec,
|
||||
env_vars: declaredRoot
|
||||
? mcp.mcpServers["codex-security"].env_vars
|
||||
: [
|
||||
...mcp.mcpServers["codex-security"].env_vars,
|
||||
"CODEX_SECURITY_PLUGIN_ROOT",
|
||||
],
|
||||
env_vars: [
|
||||
...mcp.mcpServers["codex-security"].env_vars,
|
||||
...(declaredRoot ? [] : ["CODEX_SECURITY_PLUGIN_ROOT"]),
|
||||
"CODEX_SECURITY_REPOSITORY",
|
||||
],
|
||||
});
|
||||
expect(
|
||||
JSON.parse(await readFile(join(selected, ".mcp.json"), "utf8")),
|
||||
@@ -1137,6 +1155,11 @@ for await (const line of createInterface({ input: process.stdin })) {
|
||||
...environment,
|
||||
CODEX_HOME: home,
|
||||
CODEX_SQLITE_HOME: sqliteHome,
|
||||
CODEX_SECURITY_REPOSITORY: join(
|
||||
root,
|
||||
pluginRoot === second ? "second source" : "first source",
|
||||
),
|
||||
SYNTHETIC_UNDECLARED_VALUE: "ambient fixture",
|
||||
...(pluginRoot === undefined
|
||||
? {}
|
||||
: { CODEX_SECURITY_PLUGIN_ROOT: pluginRoot }),
|
||||
@@ -1200,6 +1223,10 @@ for await (const line of createInterface({ input: process.stdin })) {
|
||||
});
|
||||
const details = server.tools.probe._meta.launch;
|
||||
expect(details.pluginRoot).toBe(await realpath(pluginRoot));
|
||||
expect(details.repository).toBe(
|
||||
join(root, pluginRoot === second ? "second source" : "first source"),
|
||||
);
|
||||
expect(details.ambient).toBeUndefined();
|
||||
expect(details.args).toEqual(argumentsAfterEntry);
|
||||
expect(details.cwd).toBe(
|
||||
process.platform === "win32"
|
||||
@@ -1844,6 +1871,38 @@ for await (const line of createInterface({ input: process.stdin })) {
|
||||
}
|
||||
});
|
||||
|
||||
test.skipIf(process.platform !== "win32")(
|
||||
"extracts plugin ZIPs across Windows temporary directory path limits",
|
||||
async () => {
|
||||
const root = await temporaryDirectory();
|
||||
const archive = join(root, "plugin.zip");
|
||||
const manifest = ".codex-plugin/plugin.json";
|
||||
const data = JSON.stringify({ name: "codex-security", version: "1.2.3" });
|
||||
await writeFile(
|
||||
archive,
|
||||
zipSync({ [`release/${manifest}`]: strToU8(data) }),
|
||||
);
|
||||
const templateLength = join(root, ".codex-security-plugin-XXXXXX").length;
|
||||
using createStaging = spyOn(fsPromises, "mkdtemp");
|
||||
for (const length of [247, 248, 259, 260, 280]) {
|
||||
const padding = Math.max(1, length - templateLength - 1);
|
||||
const parent = join(root, "p".repeat(padding));
|
||||
const destination = join(parent, `extracted-${length}`);
|
||||
const plugin = await extractPluginZip(archive, destination);
|
||||
expect(createStaging).toHaveBeenLastCalledWith(
|
||||
win32.toNamespacedPath(join(parent, ".codex-security-plugin-")),
|
||||
);
|
||||
expect(plugin).toBe(join(destination, "release"));
|
||||
expect(await readFile(join(plugin, manifest), "utf8")).toBe(data);
|
||||
expect(
|
||||
(await readdir(parent)).some((entry) =>
|
||||
entry.startsWith(".codex-security-plugin-"),
|
||||
),
|
||||
).toBe(false);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("rejects a ZIP entry with an invalid CRC-32", async () => {
|
||||
const root = await temporaryDirectory();
|
||||
const archive = join(root, "invalid-crc.zip");
|
||||
@@ -2273,7 +2332,11 @@ for await (const line of createInterface({ input: process.stdin })) {
|
||||
command: "./scripts/launch_codex_security_mcp_sdk",
|
||||
args: ["--stdio", "synthetic argument"],
|
||||
cwd: ".",
|
||||
env_vars: ["CODEX_HOME", "CODEX_SECURITY_PLUGIN_ROOT"],
|
||||
env_vars: [
|
||||
"CODEX_HOME",
|
||||
"CODEX_SECURITY_PLUGIN_ROOT",
|
||||
"CODEX_SECURITY_REPOSITORY",
|
||||
],
|
||||
});
|
||||
expect(
|
||||
(await stat(join(staged, "scripts", "launch_codex_security_mcp")))
|
||||
@@ -3341,23 +3404,30 @@ describe("runtime directories and plugin Python boundary", () => {
|
||||
let stickyParent = shared;
|
||||
await mkdir(stickyParent, { mode: 0o1777 });
|
||||
await chmod(stickyParent, 0o1777);
|
||||
if (((await lstat(stickyParent)).mode & 0o1000) === 0) {
|
||||
stickyParent = await realpath(tmpdir());
|
||||
try {
|
||||
if (((await lstat(stickyParent)).mode & 0o1000) === 0) {
|
||||
return;
|
||||
stickyParent = await realpath(tmpdir());
|
||||
if (((await lstat(stickyParent)).mode & 0o1000) === 0) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const stateDirectory = join(
|
||||
stickyParent,
|
||||
`codex-security-sticky-${process.pid}-${Date.now()}`,
|
||||
);
|
||||
if (stickyParent !== shared) temporaryDirectories.track(stateDirectory);
|
||||
await mkdir(stateDirectory, { recursive: true, mode: 0o700 });
|
||||
const home = await prepareCodexSecurityCredentialHome({
|
||||
CODEX_SECURITY_STATE_DIR: stateDirectory,
|
||||
});
|
||||
await expect(requireSecureCredentialHome(home)).resolves.toBeDefined();
|
||||
await expect(
|
||||
requireSecureOutputAncestry(home),
|
||||
).resolves.toBeUndefined();
|
||||
} finally {
|
||||
// Restore this fixture's parent before recursive cleanup on macOS.
|
||||
await chmod(shared, 0o700);
|
||||
}
|
||||
const stateDirectory = join(
|
||||
stickyParent,
|
||||
`codex-security-sticky-${process.pid}-${Date.now()}`,
|
||||
);
|
||||
if (stickyParent !== shared) temporaryDirectories.track(stateDirectory);
|
||||
await mkdir(stateDirectory, { recursive: true, mode: 0o700 });
|
||||
const home = await prepareCodexSecurityCredentialHome({
|
||||
CODEX_SECURITY_STATE_DIR: stateDirectory,
|
||||
});
|
||||
await expect(requireSecureCredentialHome(home)).resolves.toBeDefined();
|
||||
await expect(requireSecureOutputAncestry(home)).resolves.toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -5837,6 +5907,19 @@ describe("runtime directories and plugin Python boundary", () => {
|
||||
},
|
||||
);
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"preserves trailing whitespace in an explicit POSIX state directory",
|
||||
async () => {
|
||||
const root = await temporaryDirectory();
|
||||
for (const suffix of [" ", "\u00a0"]) {
|
||||
const state = join(root, `explicit-state${suffix}`);
|
||||
expect(
|
||||
codexSecurityStateDirectory({ CODEX_SECURITY_STATE_DIR: state }),
|
||||
).toBe(state);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("derives persistent state from the ambient home or explicit override", async () => {
|
||||
const root = await temporaryDirectory();
|
||||
expect(codexSecurityStateDirectory({ CODEX_HOME: root })).toBe(
|
||||
@@ -6476,25 +6559,30 @@ describe("runtime directories and plugin Python boundary", () => {
|
||||
const shared = join(root, "shared");
|
||||
await mkdir(shared, { mode: 0o1777 });
|
||||
await chmod(shared, 0o1777);
|
||||
// Some filesystems (notably user dirs on macOS APFS) ignore sticky on
|
||||
// chmod; fall back to the process temp root when it is already sticky.
|
||||
let stickyParent = shared;
|
||||
if (((await lstat(shared)).mode & 0o1000) === 0) {
|
||||
stickyParent = await realpath(tmpdir());
|
||||
if (((await lstat(stickyParent)).mode & 0o1000) === 0) {
|
||||
return;
|
||||
try {
|
||||
// Some filesystems (notably user dirs on macOS APFS) ignore sticky on
|
||||
// chmod; fall back to the process temp root when it is already sticky.
|
||||
let stickyParent = shared;
|
||||
if (((await lstat(shared)).mode & 0o1000) === 0) {
|
||||
stickyParent = await realpath(tmpdir());
|
||||
if (((await lstat(stickyParent)).mode & 0o1000) === 0) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
const output = join(
|
||||
stickyParent,
|
||||
`codex-security-sticky-${process.pid}-${Date.now()}`,
|
||||
);
|
||||
if (stickyParent !== shared) temporaryDirectories.track(output);
|
||||
const output = join(
|
||||
stickyParent,
|
||||
`codex-security-sticky-${process.pid}-${Date.now()}`,
|
||||
);
|
||||
if (stickyParent !== shared) temporaryDirectories.track(output);
|
||||
|
||||
await expect(
|
||||
requireSecureOutputAncestry(output),
|
||||
).resolves.toBeUndefined();
|
||||
expect(await prepareOutputDir(output, "repo")).toBe(output);
|
||||
await expect(
|
||||
requireSecureOutputAncestry(output),
|
||||
).resolves.toBeUndefined();
|
||||
expect(await prepareOutputDir(output, "repo")).toBe(output);
|
||||
} finally {
|
||||
// Restore this fixture's parent before recursive cleanup on macOS.
|
||||
await chmod(shared, 0o700);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -6934,6 +7022,128 @@ describe("runtime directories and plugin Python boundary", () => {
|
||||
}
|
||||
});
|
||||
|
||||
testPosix(
|
||||
"discovers Python outside explicit targets from a filesystem-root working directory",
|
||||
async () => {
|
||||
if (
|
||||
runTestInSubprocess(
|
||||
fileURLToPath(import.meta.url),
|
||||
"discovers Python outside explicit targets from a filesystem-root working directory",
|
||||
{},
|
||||
"/",
|
||||
)
|
||||
)
|
||||
return;
|
||||
const target = await temporaryDirectory();
|
||||
const tools = await temporaryDirectory();
|
||||
const system = pythonWithLauncher();
|
||||
expect(system).not.toBeNull();
|
||||
const name = "fixture-python";
|
||||
await symlink(system!, join(tools, name));
|
||||
await symlink(system!, join(target, name));
|
||||
const alias = join(tools, "root-directory");
|
||||
await symlink("/", alias, "dir");
|
||||
expect(process.cwd()).toBe("/");
|
||||
const environment = { PATH: [target, tools].join(":"), PYTHON: name };
|
||||
for (const caller of ["/", alias]) {
|
||||
const selected = await resolvePluginPython({
|
||||
currentDirectory: caller,
|
||||
protectedRoot: target,
|
||||
environment,
|
||||
});
|
||||
expect(selected).toBe(join(tools, name));
|
||||
}
|
||||
await expect(
|
||||
resolvePluginPython({
|
||||
currentDirectory: `/${basename(target)}-missing/..`,
|
||||
protectedRoot: target,
|
||||
environment,
|
||||
}),
|
||||
).rejects.toThrow("unavailable");
|
||||
await expect(resolvePluginPython({ environment })).rejects.toThrow(
|
||||
"unavailable",
|
||||
);
|
||||
for (const protectedRoot of [[], "/"]) {
|
||||
await expect(
|
||||
resolvePluginPython({ protectedRoot, environment }),
|
||||
).rejects.toThrow("unavailable");
|
||||
}
|
||||
await expect(
|
||||
resolvePluginPython({
|
||||
protectedRoot: target,
|
||||
environment: { PATH: target, PYTHON: name },
|
||||
}),
|
||||
).rejects.toThrow("unavailable");
|
||||
},
|
||||
);
|
||||
|
||||
testPosix(
|
||||
"preserves literal executable override names and accepts padding",
|
||||
async () => {
|
||||
const tools = await realpath(await temporaryDirectory());
|
||||
const repository = await temporaryDirectory();
|
||||
const interpreter = pythonWithLauncher();
|
||||
expect(interpreter).not.toBeNull();
|
||||
const ordinary = join(tools, "tool");
|
||||
const literal = ordinary + " ";
|
||||
await symlink(interpreter!, ordinary);
|
||||
await symlink(interpreter!, literal);
|
||||
|
||||
for (const [configured, expected] of [
|
||||
[literal, literal],
|
||||
[` ${ordinary} `, ordinary],
|
||||
] as const) {
|
||||
expect(
|
||||
resolveCodexCommand({ CODEX_CLI_PATH: configured }).command,
|
||||
).toBe(expected);
|
||||
await expect(
|
||||
resolvePluginPython({
|
||||
environment: { PYTHON: configured, PATH: tools },
|
||||
protectedRoot: repository,
|
||||
}),
|
||||
).resolves.toBe(expected);
|
||||
}
|
||||
await expect(
|
||||
resolvePluginPython({
|
||||
environment: { PYTHON: "tool ", PATH: tools },
|
||||
protectedRoot: repository,
|
||||
}),
|
||||
).resolves.toBe(ordinary);
|
||||
|
||||
const paddedAbsolute = ` ${ordinary} `;
|
||||
const shadow = join(repository, paddedAbsolute);
|
||||
await mkdir(dirname(shadow), { recursive: true });
|
||||
await writeFile(shadow, "#!/bin/sh\nexit 93\n", { mode: 0o700 });
|
||||
const runtime = new URL("../src/runtime.ts", import.meta.url).href;
|
||||
const child = spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
"-e",
|
||||
`import { resolveCodexCommand } from ${JSON.stringify(runtime)};
|
||||
import { spawnSync } from "node:child_process";
|
||||
const { command } = resolveCodexCommand();
|
||||
process.exit(spawnSync(command, ["-I", "-c", "pass"]).status ?? 1);`,
|
||||
],
|
||||
{
|
||||
cwd: repository,
|
||||
env: { ...process.env, CODEX_CLI_PATH: paddedAbsolute },
|
||||
},
|
||||
);
|
||||
expect(child.status).toBe(0);
|
||||
|
||||
await rm(literal);
|
||||
expect(resolveCodexCommand({ CODEX_CLI_PATH: literal }).command).toBe(
|
||||
ordinary,
|
||||
);
|
||||
await expect(
|
||||
resolvePluginPython({
|
||||
environment: { PYTHON: literal, PATH: tools },
|
||||
protectedRoot: repository,
|
||||
}),
|
||||
).resolves.toBe(ordinary);
|
||||
},
|
||||
);
|
||||
|
||||
test("resolves inherited Python names case-insensitively", async () => {
|
||||
const discovered = pythonWithLauncher();
|
||||
expect(discovered).not.toBeNull();
|
||||
|
||||
@@ -20,10 +20,15 @@ import {
|
||||
import { dirname, join } from "node:path";
|
||||
import { afterEach, expect, spyOn, test } from "bun:test";
|
||||
import { parse as parseToml } from "smol-toml";
|
||||
import { strToU8, zipSync } from "fflate";
|
||||
import { main } from "../src/cli.js";
|
||||
import { scanPreflightCodexConfig, type ScanOptions } from "../src/api.js";
|
||||
import { writeCodexConfig, type JsonObject } from "../src/config.js";
|
||||
import { runWorkbench } from "../src/runtime.js";
|
||||
import {
|
||||
writeCodexConfig,
|
||||
type CodexSecurityConfig,
|
||||
type JsonObject,
|
||||
} from "../src/config.js";
|
||||
import { resolvePluginSource, runWorkbench } from "../src/runtime.js";
|
||||
import { readKnowledgeBaseSnapshot } from "../src/knowledge-base.js";
|
||||
import { saveScanKnowledge, scanInputIdentity } from "../src/scan-inputs.js";
|
||||
import { workflowDigest } from "../src/finding-workflow.js";
|
||||
@@ -440,7 +445,14 @@ test.each([
|
||||
},
|
||||
);
|
||||
|
||||
test("CLI resumes through native execution with current permissions and preserves interrupted state and output permissions", async () => {
|
||||
const resumePlugins =
|
||||
process.platform === "win32" ? ["bundled", "zip"] : ["bundled"];
|
||||
test.each(resumePlugins)(
|
||||
"CLI resumes through native execution with current permissions and preserves interrupted state and output permissions (%s)",
|
||||
resumeWithPlugin,
|
||||
);
|
||||
|
||||
async function resumeWithPlugin(source: string) {
|
||||
const markdown = "Keep the grading policy chosen when this scan started.";
|
||||
const severityRubric = {
|
||||
markdown,
|
||||
@@ -450,6 +462,24 @@ test("CLI resumes through native execution with current permissions and preserve
|
||||
const f = await interruptedScan("deep", false, { severityRubric });
|
||||
const bootstrapWorkspace = join(f.root, "resumed-bootstrap");
|
||||
await mkdir(bootstrapWorkspace);
|
||||
const archive = join(f.root, "selected.zip");
|
||||
if (source === "zip") {
|
||||
await writeFile(
|
||||
archive,
|
||||
zipSync({
|
||||
".codex-plugin/plugin.json": strToU8(
|
||||
JSON.stringify({ name: "codex-security", version: "0.1.0" }),
|
||||
),
|
||||
"skills/deep-security-scan/SKILL.md": strToU8(
|
||||
"# Custom resumed workflow",
|
||||
),
|
||||
}),
|
||||
);
|
||||
}
|
||||
const selected =
|
||||
source === "zip"
|
||||
? await resolvePluginSource(archive, bootstrapWorkspace, undefined, true)
|
||||
: undefined;
|
||||
Object.assign(f.environment, {
|
||||
CODEX_SECURITY_ENABLE_REMOTE_SEVERITY_RUBRIC: "1",
|
||||
});
|
||||
@@ -474,7 +504,9 @@ test("CLI resumes through native execution with current permissions and preserve
|
||||
);
|
||||
const originalFeedback =
|
||||
JSON.stringify([{ reason: "Original reviewer rationale." }]) + "\n";
|
||||
await mkdir(join(f.scanDir, "artifacts", "01_context"), { recursive: true });
|
||||
await mkdir(join(f.scanDir, "artifacts", "01_context"), {
|
||||
recursive: true,
|
||||
});
|
||||
await writeFile(feedbackPath, originalFeedback, { mode: 0o600 });
|
||||
const originalHome = join(f.root, "original-codex-home");
|
||||
await appendFile(
|
||||
@@ -503,17 +535,21 @@ test("CLI resumes through native execution with current permissions and preserve
|
||||
]);
|
||||
let resumedThread: string | undefined;
|
||||
const { stderr, runCli } = createCliTest(main);
|
||||
// The host can supply a ZIP through its SDK client when replaying a scan.
|
||||
const withPlugin = (config: CodexSecurityConfig) =>
|
||||
selected ? { ...config, pluginPath: archive } : config;
|
||||
|
||||
const flags = ["scans", "resume", f.scanId, "--json", "--verbose"];
|
||||
const code = await runCli(flags, {
|
||||
...dependencies({ environment: f.environment, currentDirectory: f.root }),
|
||||
runWorkbench: f.command,
|
||||
createSecurity: (config) =>
|
||||
new TestClient(config, {
|
||||
new TestClient(withPlugin(config), {
|
||||
environment: f.environment,
|
||||
prepareRuntime: async () => ({
|
||||
...preparedRuntime(f.codexHome),
|
||||
bootstrapWorkspace,
|
||||
pluginZipSource: selected?.zip,
|
||||
deepScanConfigDirectory: join(f.codexHome, "worker-config"),
|
||||
deepScanConfigPath: join(
|
||||
f.codexHome,
|
||||
@@ -549,7 +585,9 @@ test("CLI resumes through native execution with current permissions and preserve
|
||||
options.configOverrides!.join("\n"),
|
||||
) as {
|
||||
permissions: {
|
||||
codex_security_scan: { filesystem: Record<string, unknown> };
|
||||
codex_security_scan: {
|
||||
filesystem: Record<string, unknown>;
|
||||
};
|
||||
};
|
||||
};
|
||||
const filesystem =
|
||||
@@ -558,7 +596,13 @@ test("CLI resumes through native execution with current permissions and preserve
|
||||
expect(filesystem[originalHome]).toBeUndefined();
|
||||
if (process.platform === "win32") {
|
||||
const currentPlugin = options.env!["CODEX_SECURITY_PLUGIN_ROOT"]!;
|
||||
expect(dirname(currentPlugin)).toBe(bootstrapWorkspace);
|
||||
if (selected) {
|
||||
// The fixture root and its process temp parent can both host the ZIP.
|
||||
expect([f.root, dirname(f.root)]).toContain(
|
||||
dirname(dirname(currentPlugin)),
|
||||
);
|
||||
expect(currentPlugin).not.toBe(selected.root);
|
||||
} else expect(dirname(currentPlugin)).toBe(bootstrapWorkspace);
|
||||
expect(filesystem[currentPlugin]).toEqual({ ".": "read" });
|
||||
}
|
||||
expect(options.env).toMatchObject({
|
||||
@@ -568,6 +612,16 @@ test("CLI resumes through native execution with current permissions and preserve
|
||||
return {
|
||||
id: threadId,
|
||||
async runStreamed(prompt) {
|
||||
if (selected)
|
||||
expect(
|
||||
await readFile(
|
||||
join(
|
||||
options.env!["CODEX_SECURITY_PLUGIN_ROOT"]!,
|
||||
"skills/deep-security-scan/SKILL.md",
|
||||
),
|
||||
"utf8",
|
||||
),
|
||||
).toBe("# Custom resumed workflow");
|
||||
if (process.platform !== "win32")
|
||||
expect((await stat(f.scanDir)).mode & 0o777).toBe(0o755);
|
||||
expect(await readFile(feedbackPath, "utf8")).toBe(
|
||||
@@ -616,7 +670,7 @@ test("CLI resumes through native execution with current permissions and preserve
|
||||
expect(await readFile(feedbackPath, "utf8")).toBe(originalFeedback);
|
||||
if (process.platform !== "win32")
|
||||
expect((await stat(f.scanDir)).mode & 0o777).toBe(0o755);
|
||||
});
|
||||
}
|
||||
|
||||
test.each([false, true])(
|
||||
"resume restores private provider refinements (bulk: %p)",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { nodeCommand, gitText } from "./support/shell.js";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import {
|
||||
chmod,
|
||||
cp,
|
||||
mkdir,
|
||||
readFile,
|
||||
@@ -398,6 +399,35 @@ describe("security policy generation", () => {
|
||||
expect(inventory.gitMetadataPaths).toEqual([]);
|
||||
});
|
||||
|
||||
test.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"inventories policies when an unrelated leaf directory only permits listing",
|
||||
async () => {
|
||||
const f = await fixture();
|
||||
policyGit(f.repository, "init", "--quiet");
|
||||
const leaf = join(f.repository, "data");
|
||||
await mkdir(leaf);
|
||||
await writeFile(join(leaf, "sample.txt"), "fixture\n");
|
||||
await writeFile(join(f.repository, "SECURITY.md"), POLICY);
|
||||
const target = await resolveSecurityPolicyTarget(f.repository);
|
||||
try {
|
||||
await chmod(leaf, 0o400);
|
||||
expect(
|
||||
(await inspectSecurityPolicySources(target)).policyPaths,
|
||||
).toEqual(["SECURITY.md"]);
|
||||
await chmod(leaf, 0o700);
|
||||
await writeFile(join(leaf, "SECURITY.md"), POLICY);
|
||||
await chmod(leaf, 0o400);
|
||||
await expect(
|
||||
inspectSecurityPolicySources(target),
|
||||
).rejects.toMatchObject({
|
||||
code: "EACCES",
|
||||
});
|
||||
} finally {
|
||||
await chmod(leaf, 0o700);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("leaves Git-ignored dependencies out of the policy inventory", async () => {
|
||||
const f = await fixture();
|
||||
policyGit(f.repository, "init", "--quiet");
|
||||
|
||||
@@ -2,8 +2,10 @@ import { createTemporaryDirectoriesSync } from "./support/temporary-directories.
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import { PLUGIN_ROOT } from "./plugin-root.js";
|
||||
import { runNodePython } from "./support/python-probe.js";
|
||||
import { useTestPython } from "./support/python.js";
|
||||
|
||||
const temporaryDirectories = createTemporaryDirectoriesSync();
|
||||
const pythonExecutable = useTestPython();
|
||||
|
||||
afterEach(temporaryDirectories.cleanup);
|
||||
|
||||
@@ -171,7 +173,7 @@ function runStoppedScanProbe(
|
||||
prefix: string,
|
||||
terminalStatus?: string,
|
||||
) {
|
||||
const python = Bun.which("python3") ?? Bun.which("python");
|
||||
const python = pythonExecutable();
|
||||
expect(python).not.toBeNull();
|
||||
const root = temporaryDirectories.create(prefix);
|
||||
const result = runNodePython(python!, [
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { expect } from "bun:test";
|
||||
|
||||
export function runTestInSubprocess(file: string, name: string): boolean {
|
||||
export function runTestInSubprocess(
|
||||
file: string,
|
||||
name: string,
|
||||
environment: NodeJS.ProcessEnv = {},
|
||||
cwd: string | URL = new URL("../../", import.meta.url),
|
||||
): boolean {
|
||||
const identity = `${file}::${name}`;
|
||||
if (process.env["CODEX_SECURITY_ISOLATED_TEST"] === identity) return false;
|
||||
const timeout = process.env["CODEX_SECURITY_TEST_TIMEOUT_MS"] ?? "30000";
|
||||
@@ -11,9 +16,13 @@ export function runTestInSubprocess(file: string, name: string): boolean {
|
||||
process.execPath,
|
||||
["test", "--timeout", timeout, "--test-name-pattern", pattern, file],
|
||||
{
|
||||
cwd: new URL("../../", import.meta.url),
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, CODEX_SECURITY_ISOLATED_TEST: identity },
|
||||
env: {
|
||||
...process.env,
|
||||
...environment,
|
||||
CODEX_SECURITY_ISOLATED_TEST: identity,
|
||||
},
|
||||
windowsHide: true,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { delimiter, join } from "node:path";
|
||||
import { delimiter, join, relative } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import {
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
gitMarkerRoot,
|
||||
isGitMetadataDirectory,
|
||||
gitProtectionRoots,
|
||||
validateCommittedDiffCheckout,
|
||||
} from "../src/targets.js";
|
||||
import { createApiTestFixtures } from "./support/temporary-directories.js";
|
||||
import { runCommand } from "./support/shell.js";
|
||||
@@ -161,7 +162,10 @@ function git(repo: string, ...args: string[]): string {
|
||||
return execFileSync("git", args, { cwd: repo, encoding: "utf8" }).trim();
|
||||
}
|
||||
|
||||
function validateCommittedDiffWithCredentialConfig(repo: string) {
|
||||
function validateCommittedDiffWithCredentialConfig(
|
||||
repo: string,
|
||||
environment: NodeJS.ProcessEnv = {},
|
||||
) {
|
||||
return spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
@@ -174,6 +178,7 @@ function validateCommittedDiffWithCredentialConfig(repo: string) {
|
||||
encoding: "utf8",
|
||||
env: {
|
||||
...process.env,
|
||||
...environment,
|
||||
GIT_CONFIG_COUNT: "1",
|
||||
GIT_CONFIG_KEY_0: "http.extraHeader",
|
||||
GIT_CONFIG_VALUE_0: "SYNTHETIC_GIT_CREDENTIAL",
|
||||
@@ -569,6 +574,42 @@ describe("scan target normalization", () => {
|
||||
}
|
||||
});
|
||||
|
||||
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, "..");
|
||||
|
||||
@@ -42,6 +42,7 @@ async function fixture() {
|
||||
const plugin = join(root, "plugin");
|
||||
const paths = [
|
||||
"scripts/workbench_scan_usage.py",
|
||||
"scripts/snapshot_sqlite.py",
|
||||
"scripts/windows_scan_local_files.py",
|
||||
"scripts/read_codex_session.mjs",
|
||||
"scripts/workbench/__init__.py",
|
||||
|
||||
Reference in New Issue
Block a user