diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 4ec3f6a74b810..b68fdfed14eff 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -1533,25 +1533,85 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { }).pipe(Effect.provideService(CommandResolutionCache, new Map())), ); - it.effect("keeps git when PATH has another git or the host is not macOS", () => - Effect.gen(function* () { - const homebrew = setup({ gitOnPath: "/opt/homebrew/bin/git", xcrunGit: XCODE_GIT }); - expect(yield* homebrew.resolve).toBe("git"); - expect(homebrew.host.xcrunCalls).toBe(0); + it.effect.runIf(HostProcess.Platform.defaultValue() !== "win32")( + "distinguishes symlink/.. custom git from /usr/bin/git using realpath", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-macos-git-shim-" }); + const customDir = path.join(root, "custom"); + const customSub = path.join(customDir, "sub"); + const link = path.join(root, "link"); + yield* fs.makeDirectory(customSub, { recursive: true }); + yield* fs.symlink(customSub, link); + + const customGit = path.join(customDir, "git"); + yield* fs.writeFileString(customGit, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(customGit, 0o755); + + let xcrunCalls = 0; + const resolved = yield* resolveSpawnCommand("git", ["status"], { + env: { PATH: `${link}/..` }, + }).pipe( + Effect.map((r) => r.command), + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(XcodeGitLocation, () => { + xcrunCalls += 1; + return XCODE_GIT; + }), + ); + expect(resolved).toBe(`${link}/../git`); + expect(xcrunCalls).toBe(0); - const linux = setup({ platform: "linux", gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT }); - expect(yield* linux.resolve).toBe("git"); - }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + const hasDirectUsrBinGit = yield* fs.realPath("/usr/bin/git").pipe( + Effect.map((resolvedPath) => resolvedPath === "/usr/bin/git"), + Effect.orElseSucceed(() => false), + ); + if (hasDirectUsrBinGit) { + const shimLink = path.join(root, "usr-bin-link"); + yield* fs.symlink("/usr/bin", shimLink); + const shimResolved = yield* resolveSpawnCommand("git", ["status"], { + env: { PATH: `${shimLink}/.` }, + }).pipe( + Effect.map((r) => r.command), + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(XcodeGitLocation, () => { + xcrunCalls += 1; + return customGit; + }), + ); + expect(shimResolved).toBe(customGit); + expect(xcrunCalls).toBe(1); + } + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + ); + + it.effect( + "uses PATH git without xcrun when PATH has another git, and keeps bare git on Linux", + () => + Effect.gen(function* () { + const homebrew = setup({ gitOnPath: "/opt/homebrew/bin/git", xcrunGit: XCODE_GIT }); + expect(yield* homebrew.resolve).toBe("/opt/homebrew/bin/git"); + expect(homebrew.host.xcrunCalls).toBe(0); + + const linux = setup({ + platform: "linux", + gitOnPath: "/usr/bin/git", + xcrunGit: XCODE_GIT, + }); + expect(yield* linux.resolve).toBe("git"); + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), ); - it.effect("keeps git when xcrun fails or names a missing file", () => + it.effect("falls back to /usr/bin/git when xcrun fails or names a missing file", () => Effect.gen(function* () { const failed = setup({ gitOnPath: "/usr/bin/git", xcrunGit: undefined }); - expect(yield* failed.resolve).toBe("git"); + expect(yield* failed.resolve).toBe("/usr/bin/git"); const missing = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT }); missing.files.delete(XCODE_GIT); - expect(yield* missing.resolve).toBe("git"); + expect(yield* missing.resolve).toBe("/usr/bin/git"); }).pipe(Effect.provideService(CommandResolutionCache, new Map())), ); @@ -1568,6 +1628,229 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { expect(host.xcrunCalls).toBe(2); }).pipe(Effect.provideService(CommandResolutionCache, new Map())), ); + + it.effect("does not reuse an unset-PATH Xcode git cache entry for an explicit empty PATH", () => + Effect.gen(function* () { + const files = new Set(["/usr/bin/git", XCODE_GIT]); + let xcrunCalls = 0; + const resolveExecutable = ( + command: string, + _platform: NodeJS.Platform, + lookupEnv: NodeJS.ProcessEnv, + ) => { + if (command !== "git") return files.has(command) ? command : undefined; + return lookupEnv.PATH === "" ? undefined : "/usr/bin/git"; + }; + const locateXcodeGit = () => { + xcrunCalls += 1; + return XCODE_GIT; + }; + const resolveWithEnv = (env: NodeJS.ProcessEnv) => + resolveSpawnCommand("git", ["status"], { env }).pipe( + Effect.map((resolved) => resolved.command), + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(SpawnExecutableResolution, resolveExecutable), + Effect.provideService(XcodeGitLocation, locateXcodeGit), + ); + + expect(yield* resolveWithEnv({})).toBe(XCODE_GIT); + expect(yield* resolveWithEnv({})).toBe(XCODE_GIT); + expect(xcrunCalls).toBe(1); + + expect(yield* resolveWithEnv({ PATH: "" })).toBe("git"); + expect(xcrunCalls).toBe(1); + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + ); + }); + + describe("macOS bare commands", () => { + it.effect.runIf(HostProcess.Platform.defaultValue() !== "win32")( + "rescans PATH on each macOS spawn so earlier PATH additions win immediately", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-macos-path-" }); + const first = path.join(root, "first"); + const second = path.join(root, "second"); + yield* fs.makeDirectory(first); + yield* fs.makeDirectory(second); + + const laterTool = path.join(second, "mytool"); + yield* fs.writeFileString(laterTool, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(laterTool, 0o755); + + const resolve = resolveSpawnCommand("mytool", ["--flag"], { + env: { PATH: `${first}:${second}` }, + }).pipe(Effect.provideService(HostProcess.Platform, "darwin")); + + const resolved = yield* resolve; + expect(resolved).toEqual({ + command: laterTool, + args: ["--flag"], + shell: false, + }); + + const earlierTool = path.join(first, "mytool"); + yield* fs.writeFileString(earlierTool, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(earlierTool, 0o755); + + expect(yield* resolve).toEqual({ + command: earlierTool, + args: ["--flag"], + shell: false, + }); + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + ); + + it.effect.runIf(HostProcess.Platform.defaultValue() !== "win32")( + "skips directories and non-executable files in earlier PATH entries, but defers on ELOOP or a missing interpreter", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-macos-errno-path-" }); + const dirEntry = path.join(root, "has-dir"); + const nonExecEntry = path.join(root, "has-non-exec"); + const loopEntry = path.join(root, "has-loop"); + const validEntry = path.join(root, "valid"); + yield* fs.makeDirectory(path.join(dirEntry, "mytool"), { recursive: true }); + yield* fs.makeDirectory(nonExecEntry); + yield* fs.makeDirectory(loopEntry); + yield* fs.makeDirectory(validEntry); + + const nonExecTool = path.join(nonExecEntry, "mytool"); + yield* fs.writeFileString(nonExecTool, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(nonExecTool, 0o644); + + const validTool = path.join(validEntry, "mytool"); + yield* fs.writeFileString(validTool, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(validTool, 0o755); + + // Directory and non-executable file (EACCES) are skipped so validTool wins. + const skipped = yield* resolveSpawnCommand("mytool", [], { + env: { PATH: `${dirEntry}:${nonExecEntry}:${validEntry}` }, + }).pipe( + Effect.map((r) => r.command), + Effect.provideService(HostProcess.Platform, "darwin"), + ); + expect(skipped).toBe(validTool); + + // A script whose interpreter is missing fails posix_spawn with ENOENT, after which native + // PATH lookup continues to validTool, so resolution defers instead of pinning it. + const staleEntry = path.join(root, "stale"); + yield* fs.makeDirectory(staleEntry); + const staleTool = path.join(staleEntry, "mytool"); + yield* fs.writeFileString(staleTool, "#!/missing/interpreter\nexit 0\n"); + yield* fs.chmod(staleTool, 0o755); + const deferredOnStale = yield* resolveSpawnCommand("mytool", [], { + env: { PATH: `${staleEntry}:${validEntry}` }, + }).pipe( + Effect.map((r) => r.command), + Effect.provideService(HostProcess.Platform, "darwin"), + ); + expect(deferredOnStale).toBe("mytool"); + + // macOS treats CR as part of the interpreter path (not whitespace/EOL), so `#!/bin/sh\r\n` + // fails posix_spawn with ENOENT and native PATH lookup continues to validTool. + const crlfEntry = path.join(root, "crlf"); + yield* fs.makeDirectory(crlfEntry); + const crlfTool = path.join(crlfEntry, "mytool"); + yield* fs.writeFileString(crlfTool, "#!/bin/sh\r\nexit 0\n"); + yield* fs.chmod(crlfTool, 0o755); + const deferredOnCrlf = yield* resolveSpawnCommand("mytool", [], { + env: { PATH: `${crlfEntry}:${validEntry}` }, + }).pipe( + Effect.map((r) => r.command), + Effect.provideService(HostProcess.Platform, "darwin"), + ); + expect(deferredOnCrlf).toBe("mytool"); + + // Symlink loop (ELOOP) stops the scan and defers to native spawn instead of skipping to validTool. + const loopA = path.join(loopEntry, "loop-a"); + const loopB = path.join(loopEntry, "loop-b"); + yield* fs.symlink(loopB, loopA); + yield* fs.symlink(loopA, loopB); + yield* fs.symlink(loopA, path.join(loopEntry, "mytool")); + + const deferredOnLoop = yield* resolveSpawnCommand("mytool", [], { + env: { PATH: `${loopEntry}:${validEntry}` }, + }).pipe( + Effect.map((r) => r.command), + Effect.provideService(HostProcess.Platform, "darwin"), + ); + expect(deferredOnLoop).toBe("mytool"); + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + ); + + it.effect.runIf(HostProcess.Platform.defaultValue() !== "win32")( + "uses uppercase PATH, defaults to /usr/bin:/bin when unset, and defers on empty or relative entries", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-macos-env-path-" }); + const bin = path.join(root, "bin"); + yield* fs.makeDirectory(bin); + const tool = path.join(bin, "mytool"); + yield* fs.writeFileString(tool, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(tool, 0o755); + + const resolveWithEnv = (command: string, env: NodeJS.ProcessEnv) => + resolveSpawnCommand(command, [], { env }).pipe( + Effect.map((resolved) => resolved.command), + Effect.provideService(HostProcess.Platform, "darwin"), + ); + + // Empty or relative entries are searched from the child's cwd, so they defer to native lookup. + expect(yield* resolveWithEnv("mytool", { PATH: "" })).toBe("mytool"); + expect(yield* resolveWithEnv("mytool", { PATH: `:${bin}` })).toBe("mytool"); + expect(yield* resolveWithEnv("mytool", { PATH: `rel/bin:${bin}` })).toBe("mytool"); + + // Empty or relative entries after a match do not change it. + expect(yield* resolveWithEnv("mytool", { PATH: `${bin}/:.` })).toBe(`${bin}/mytool`); + + // Lowercase Path is ignored on macOS; unset PATH falls back to /usr/bin:/bin. + expect(yield* resolveWithEnv("mytool", { Path: bin })).toBe("mytool"); + const expectedDefaultSh = ["/usr/bin/sh", "/bin/sh"].find((candidate) => { + try { + NodeFS.accessSync(candidate, NodeFS.constants.X_OK); + return NodeFS.statSync(candidate).isFile(); + } catch { + return false; + } + }); + if (expectedDefaultSh !== undefined) { + expect(yield* resolveWithEnv("sh", {})).toBe(expectedDefaultSh); + } + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + ); + + it.effect("skips resolution for explicit paths on macOS and for bare commands on Linux", () => + Effect.gen(function* () { + let resolverCalls = 0; + const resolver = () => { + resolverCalls += 1; + return "/bin/ps"; + }; + + expect( + yield* resolveSpawnCommand("/bin/ps", ["-A"], { env: { PATH: "/bin" } }).pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(SpawnExecutableResolution, resolver), + ), + ).toEqual({ command: "/bin/ps", args: ["-A"], shell: false }); + + expect( + yield* resolveSpawnCommand("ps", ["-A"], { env: { PATH: "/bin" } }).pipe( + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(SpawnExecutableResolution, resolver), + ), + ).toEqual({ command: "ps", args: ["-A"], shell: false }); + + expect(resolverCalls).toBe(0); + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + ); }); it.effect("does not fall back to a shell for unresolved Windows commands", () => diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index c23492c4863cb..9e7d0cb134888 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -1047,18 +1047,132 @@ export const XcodeGitLocation = Context.Reference( ); const MACOS_GIT_SHIM = "/usr/bin/git"; +// POSIX default search path (_PATH_DEFPATH) when PATH is unset. +const POSIX_DEFAULT_PATH = "/usr/bin:/bin"; +const POSIX_PATH_SCAN_CONTINUE_ERRORS = new Set(["ENOENT", "ENOTDIR", "EACCES"]); + +function isPosixPathScanContinueError(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException | null)?.code; + return typeof code === "string" && POSIX_PATH_SCAN_CONTINUE_ERRORS.has(code); +} + +async function isMacosGitShim(candidate: string): Promise { + if (candidate === MACOS_GIT_SHIM) return true; + try { + return (await NodeFS.promises.realpath(candidate)) === MACOS_GIT_SHIM; + } catch { + return false; + } +} + +// An empty or relative POSIX PATH entry depends on the child's cwd, which resolveSpawnCommand does not take. +function hasRelativePosixPathEntryBefore( + pathValue: string | undefined, + resolvedPath: string, +): boolean { + if (pathValue === undefined) return false; + const resolvedDir = NodePath.posix.resolve(NodePath.posix.dirname(resolvedPath)); + for (const entry of pathValue.split(POSIX_PATH_DELIMITER)) { + if (entry.length === 0 || !entry.startsWith("/")) return true; + if (NodePath.posix.resolve(entry) === resolvedDir) return false; + } + return false; +} + +// posix_spawn fails a script with ENOENT when its interpreter is missing, and native PATH lookup then +// moves on to later entries, so such a candidate defers to native spawn. +async function hasLaunchableInterpreter(candidate: string): Promise { + let header: string; + try { + const handle = await NodeFS.promises.open(candidate, "r"); + try { + const { buffer, bytesRead } = await handle.read(Buffer.alloc(512), 0, 512, 0); + header = buffer.toString("latin1", 0, bytesRead); + } finally { + await handle.close(); + } + } catch { + return true; + } + if (!header.startsWith("#!")) return true; + // macOS XNU's exec_shell_imgact only splits on space, tab, or newline (not CR), so a CRLF + // shebang like `#!/bin/sh\r\n` looks up `/bin/sh\r` (ENOENT) and must defer to native spawn. + const interpreter = header.match(/^#![ \t]*([^ \t\n]+)/)?.[1]; + if (interpreter === undefined || !interpreter.startsWith("/")) return false; + try { + if (!(await NodeFS.promises.stat(interpreter)).isFile()) return false; + await NodeFS.promises.access(interpreter, NodeFS.constants.X_OK); + return true; + } catch { + return false; + } +} + +// Scan macOS PATH entries literally so the kernel resolves `..` after symlinks as native spawn does. +// Only continue past ENOENT/ENOTDIR/EACCES; other errors (such as ELOOP or EIO) defer to native spawn. +async function resolveMacosPathExecutable( + command: string, + env: NodeJS.ProcessEnv, +): Promise { + const pathValue = env.PATH ?? POSIX_DEFAULT_PATH; + for (const entry of pathValue.split(POSIX_PATH_DELIMITER)) { + if (entry.length === 0 || !entry.startsWith("/")) return undefined; + const candidate = entry.endsWith("/") ? `${entry}${command}` : `${entry}/${command}`; + try { + if (!(await NodeFS.promises.stat(candidate)).isFile()) continue; + await NodeFS.promises.access(candidate, NodeFS.constants.X_OK); + return candidate; + } catch (error) { + if (!isPosixPathScanContinueError(error)) return undefined; + } + } + return undefined; +} + +/** + * Resolve bare commands to absolute paths on macOS before spawning. + * libuv's macOS posix_spawn walks PATH by calling posix_spawn on each directory; every ENOENT miss + * still allocates a kernel PID and triggers syspolicyd provenance errors and Endpoint Security hooks. + * Rescans PATH on each spawn (async stat/access only, zero PIDs) so earlier PATH additions take effect immediately. + */ +const resolveMacosBareCommand = Effect.fnUntraced(function* ( + command: string, + env: NodeJS.ProcessEnv, + resolveExecutable: SpawnExecutableResolver, +): Effect.fn.Return { + const found = + resolveExecutable === resolveSpawnExecutableWithNode + ? yield* Effect.promise(() => resolveMacosPathExecutable(command, env)) + : yield* Effect.promise(async () => resolveExecutable(command, "darwin", env)); + if ( + found === undefined || + !NodePath.posix.isAbsolute(found) || + hasRelativePosixPathEntryBefore(env.PATH, found) || + !(yield* Effect.promise(() => hasLaunchableInterpreter(found))) + ) { + return undefined; + } + return found; +}); /** * Skip the xcrun shim's per-spawn lookup only when git resolves to /usr/bin/git. - * User-selected git on PATH still wins, children keep PATH, and lookup failures use `git`. + * User-selected git on PATH still wins and children keep PATH. When the PATH walk defers to native + * spawn, git falls back to the default resolver's lookup. */ const resolveMacosGit = Effect.fnUntraced(function* ( env: NodeJS.ProcessEnv, resolveExecutable: SpawnExecutableResolver, ) { + const gitOnPath = yield* resolveMacosBareCommand("git", env, resolveExecutable); + const isShim = + gitOnPath !== undefined && (yield* Effect.promise(() => isMacosGitShim(gitOnPath))); + if (gitOnPath !== undefined && !isShim) return gitOnPath; + const fallback = isShim ? gitOnPath : "git"; + const locateXcodeGit = yield* XcodeGitLocation; const cache = yield* CommandResolutionCache; - const pathValue = resolvePathEnvironmentVariable(env); + const pathValue = env.PATH ?? POSIX_DEFAULT_PATH; const nowNanos = yield* Clock.currentTimeNanos; // Read after the clock, so the lookup below starts in the directory the key names. const cwd = pathSearchCwd(pathValue, "darwin"); @@ -1079,10 +1193,12 @@ const resolveMacosGit = Effect.fnUntraced(function* ( (yield* Effect.promise(async () => resolveExecutable(cachedPath, "darwin", env))) !== undefined ) { - return cachedPath ?? "git"; + return cachedPath ?? fallback; } } - const pathGit = yield* Effect.promise(async () => resolveExecutable("git", "darwin", env)); + const pathGit = isShim + ? MACOS_GIT_SHIM + : yield* Effect.promise(async () => resolveExecutable("git", "darwin", env)); const located = pathGit === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; const realGit = located !== undefined && @@ -1097,7 +1213,7 @@ const resolveMacosGit = Effect.fnUntraced(function* ( if (cwd !== null && pathSearchCwd(pathValue, "darwin") === cwd) { cacheCommandResolution(cache, cacheKey, realGit, nowNanos); } - return realGit ?? "git"; + return realGit ?? fallback; }); export interface SpawnCommandOptions extends CommandAvailabilityOptions { @@ -1153,8 +1269,11 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( options: SpawnCommandOptions = {}, ): Effect.fn.Return { const platform = yield* HostProcess.Platform; - const isMacosGit = platform === "darwin" && command === "git"; - if (platform !== "win32" && !isMacosGit) { + if (platform !== "win32" && platform !== "darwin") { + return { command, args: [...args], shell: false }; + } + const explicitPath = command.includes("/") || (platform === "win32" && command.includes("\\")); + if (platform === "darwin" && (command.length === 0 || explicitPath)) { return { command, args: [...args], shell: false }; } @@ -1166,16 +1285,19 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( ? { ...hostEnvironment, ...options.env } : options.env; const resolveExecutable = yield* SpawnExecutableResolution; - if (isMacosGit) { + if (platform === "darwin") { + const resolved = + command === "git" + ? yield* resolveMacosGit(env, resolveExecutable) + : ((yield* resolveMacosBareCommand(command, env, resolveExecutable)) ?? command); return { - command: yield* resolveMacosGit(env, resolveExecutable), + command: resolved, args: [...args], shell: false, }; } // Cache successful PATH lookups. Explicit paths and misses stay uncached so // newly installed executables are discoverable immediately. - const explicitPath = command.includes("/") || command.includes("\\"); const cache = yield* CommandResolutionCache; const cacheKey = [ "spawn",