From b1a390fcee8b0764ca80fe743edb84c561b653bf Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Thu, 19 Nov 2026 10:10:50 +0800 Subject: [PATCH] fix(desktop): honor clean env launch prefixes (#12117) * fix(desktop): honor clean env launch prefixes * fix(desktop): retain process ownership across env prefixes --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- docs/desktop-application-capture.md | 8 ++ .../desktop/DesktopApplicationCapture.test.ts | 53 +++++++++ .../desktop/DesktopApplicationCapture.ts | 7 +- .../desktop/DesktopExportLaunch.ts | 1 + src/desktop/DesktopApplicationSession.ts | 13 ++- src/desktop/LinuxApplicationInventory.test.ts | 46 ++++++++ src/desktop/LinuxApplicationInventory.ts | 25 ++++- src/domain/desktop/appDownloadDesktop.ts | 12 ++- src/domain/desktop/desktopEntry.test.ts | 24 +++++ src/domain/desktop/desktopEntry.ts | 102 ++++++++++++------ src/ports/DesktopApplicationSession.ts | 4 + .../providers/desktopBuildInstall.test.ts | 10 +- .../providers/desktopLaunchCommand.test.ts | 22 ++-- 13 files changed, 278 insertions(+), 49 deletions(-) diff --git a/docs/desktop-application-capture.md b/docs/desktop-application-capture.md index c96228fa08..78481021b9 100644 --- a/docs/desktop-application-capture.md +++ b/docs/desktop-application-capture.md @@ -58,6 +58,14 @@ computer would not have that entry. An `--executable` runs from the current directory, as it would from a shell, and a relative path to it is resolved there. +An `env -i`, `env --ignore-environment` or `env -` prefix drops the +inherited environment before applying any assignments in the command. The +short options can be combined, as in `env -iC /path/to/work app`. +Inventory uses the resulting XDG roots and the Linux system search path +when the prefix leaves `PATH` unset. During capture, REA passes its run +token after the prefix's assignments so it can still identify the app's +processes after the launcher exits. + A nested desktop file uses a dashed ID: `vendor/app.desktop` has ID `vendor-app`. REA checks path spellings that can encode that ID within each XDG root before trying the next root. Unrelated directories do not affect diff --git a/src/application/desktop/DesktopApplicationCapture.test.ts b/src/application/desktop/DesktopApplicationCapture.test.ts index 4fff6e8dc0..0c795865c4 100644 --- a/src/application/desktop/DesktopApplicationCapture.test.ts +++ b/src/application/desktop/DesktopApplicationCapture.test.ts @@ -370,6 +370,59 @@ it.skipIf(process.platform !== "linux")( }, ); +it.skipIf(process.platform !== "linux")( + "keeps ownership of a worker after its clean-env launcher exits", + async () => { + const { root, environment } = await fixture(); + const app = join(root, "bin/fakeapp"); + const worker = join(root, "worker"); + const pidFile = join(root, "worker-pid"); + const completed = join(root, "worker-completed"); + await executable(app, `#!/bin/sh\n"${worker}" &\nexit 0\n`); + await executable( + worker, + [ + "#!/bin/sh", + `printf '%s\\n' "$$" > "${pidFile}"`, + "/bin/sleep 2", + '[ "${INHERITED-unset}" = unset ] && [ "$SELECTED" = yes ] || exit 91', + `touch "${completed}"`, + ].join("\n"), + ); + const entry = join(root, "clean.desktop"); + const argv = ["/usr/bin/env", "-i", "SELECTED=yes", app]; + await writeFile( + entry, + `[Desktop Entry]\nType=Application\nName=FakeApp\nExec=${argv.join(" ")}\n`, + ); + + const evidence = await captureDesktopApplication( + { + ...request(join(root, "out")), + desktopEntry: entry, + executable: undefined, + maxDurationSeconds: 8, + }, + host({ ...environment, INHERITED: "host" }), + ); + if ("error" in evidence) throw new Error(JSON.stringify(evidence)); + const capture = desktopApplicationCaptureSchema.parse( + evidence.normalized_result, + ); + expect(capture.application.argv).toEqual(argv); + expect(capture.session).toMatchObject({ + end_reason: "application_exited", + cleanup: { verified: true }, + }); + const workerPid = Number(await readFile(pidFile, "utf8")); + expect(workerPid).not.toBe(capture.session.launch_pid); + expect(capture.session.processes).toContainEqual( + expect.objectContaining({ pid: workerPid, started_by_capture: true }), + ); + expect(fileExists(completed)).toBe(true); + }, +); + describe.skipIf(process.platform !== "linux")( "captureDesktopApplication on Linux", () => { diff --git a/src/application/desktop/DesktopApplicationCapture.ts b/src/application/desktop/DesktopApplicationCapture.ts index dc891c66a0..53ef4c510c 100644 --- a/src/application/desktop/DesktopApplicationCapture.ts +++ b/src/application/desktop/DesktopApplicationCapture.ts @@ -216,7 +216,8 @@ const admit = async ( signal, ); if (!inspected.ok) throw applicationRefusal(inspected.error); - const { inventory, limitations, signingKeys } = inspected.value; + const { inventory, envProgramIndex, limitations, signingKeys } = + inspected.value; const windows = host.desktop.observeWindows(xprop, host.environment); const windowMatching = applicationWindowMatching(inventory); const running = await host.desktop.runningApplicationWindows( @@ -240,6 +241,7 @@ const admit = async ( home: await canonicalCallerPath(home), output: prepared.path, inventory, + envProgramIndex, limitations, signingKeys, windows, @@ -289,6 +291,9 @@ const recordCapture = async ( await host.report(`Launching ${inventory.argv.join(" ")}.`); const outcome = await host.desktop.runSession({ argv: inventory.argv, + ...(admitted.envProgramIndex === undefined + ? {} + : { envProgramIndex: admitted.envProgramIndex }), workingDirectory: inventory.working_directory, environment: host.environment, windows: admitted.windows, diff --git a/src/application/desktop/DesktopExportLaunch.ts b/src/application/desktop/DesktopExportLaunch.ts index 93101d84b9..474ab272b3 100644 --- a/src/application/desktop/DesktopExportLaunch.ts +++ b/src/application/desktop/DesktopExportLaunch.ts @@ -143,6 +143,7 @@ export const planLaunch = ( chdir !== undefined ? [ ...application.argv.slice(0, chdir.start), + ...(chdir.includesClearEnvironment ? ["-i"] : []), "-C", workingDirectory, ...application.argv.slice(chdir.end), diff --git a/src/desktop/DesktopApplicationSession.ts b/src/desktop/DesktopApplicationSession.ts index 9a67c51acc..a48ea2f944 100644 --- a/src/desktop/DesktopApplicationSession.ts +++ b/src/desktop/DesktopApplicationSession.ts @@ -288,7 +288,18 @@ const launch = async ( runId: string, signal: AbortSignal, ) => { - const [command, ...arguments_] = plan.argv; + // An env wrapper can clear or overwrite the token supplied to its own + // process. Give the application the supervisor's token as the last + // assignment, without changing the recorded argv or the wrapper's options. + const argv = + plan.envProgramIndex === undefined + ? plan.argv + : plan.argv.toSpliced( + plan.envProgramIndex, + 0, + `REA_PROCESS_RUN_ID=${runId}`, + ); + const [command, ...arguments_] = argv; const spawned = await spawnOwnedProviderProcess({ command: command ?? "", arguments: arguments_, diff --git a/src/desktop/LinuxApplicationInventory.test.ts b/src/desktop/LinuxApplicationInventory.test.ts index 6d946c6014..5b84671e72 100644 --- a/src/desktop/LinuxApplicationInventory.test.ts +++ b/src/desktop/LinuxApplicationInventory.test.ts @@ -1166,3 +1166,49 @@ it.skipIf(process.platform === "win32").each([ } }, ); + +describe.skipIf(process.platform !== "linux")( + "clean env launch inventory", + () => { + it.each([ + ["-i", false], + ["--ignore-environment", true], + ["-- -", false], + ])( + "models env %s without borrowing PATH or XDG roots from the host", + async (flags, explicit) => { + const installed = await fixture(); + const { home, bin, environment } = installed; + const ambient = join(home, "ambient"); + const selected = join(home, "selected"); + await writeFile(join(bin, "true"), "#!/bin/sh\nexit 2\n"); + await chmod(join(bin, "true"), 0o755); + const prefix = [ + "/usr/bin/env", + ...flags.split(" "), + ...(explicit ? [`PATH=${bin}`, `XDG_CONFIG_HOME=${selected}`] : []), + ]; + await writeFile( + join( + environment.XDG_DATA_DIRS, + "applications/org.example.notes.desktop", + ), + `[Desktop Entry]\nType=Application\nName=Notes\nExec=${prefix.join(" ")} true -- -i\n`, + ); + const inventory = await inventoryOf("org.example.notes", { + ...installed, + environment: { ...environment, XDG_CONFIG_HOME: ambient }, + }); + expect(inventory.argv).toEqual([...prefix, "true", "--", "-i"]); + expect(inventory.executable.path).toBe( + explicit ? join(bin, "true") : "/bin/true", + ); + const paths = inventory.state_directories.map(({ path }) => path); + expect(paths).toContain( + join(explicit ? selected : join(home, ".config"), "true"), + ); + expect(paths).not.toContain(join(ambient, "true")); + }, + ); + }, +); diff --git a/src/desktop/LinuxApplicationInventory.ts b/src/desktop/LinuxApplicationInventory.ts index fd2646fa31..633ee82763 100644 --- a/src/desktop/LinuxApplicationInventory.ts +++ b/src/desktop/LinuxApplicationInventory.ts @@ -247,6 +247,23 @@ const readHeader = async ( } }; +const launchEnvironment = ( + wrapper: ReturnType, + inherited: LinuxApplicationRequest["environment"], +) => { + if (!wrapper.clearEnvironment) { + const environment = { ...inherited, ...wrapper.environment }; + return { environment, lookupEnvironment: environment }; + } + const environment = wrapper.environment; + // GNU env's execvp searches the Linux system path when PATH is absent. + const lookupEnvironment = + environment.PATH === undefined + ? { ...environment, PATH: "/bin:/usr/bin" } + : environment; + return { environment, lookupEnvironment }; +}; + /** The launched program as found on PATH and after resolving links. */ interface ProgramLocation { readonly program: string; @@ -439,10 +456,13 @@ export const inspectLinuxApplication = async ( const applicationDirectory = directory.value; // An `env` prefix's assignments are what the program sees: its PATH finds // the program and its XDG folders hold the program's state. - const environment = { ...request.environment, ...wrapper.environment }; + const { environment, lookupEnvironment } = launchEnvironment( + wrapper, + request.environment, + ); const found = await resolveProgram( wrapper.program, - environment, + lookupEnvironment, applicationDirectory ?? workingDirectory, ); if (found === undefined) @@ -520,6 +540,7 @@ export const inspectLinuxApplication = async ( sandboxDirectories, ), }, + ...(wrapper.index === 0 ? {} : { envProgramIndex: wrapper.index }), limitations, signingKeys, }); diff --git a/src/domain/desktop/appDownloadDesktop.ts b/src/domain/desktop/appDownloadDesktop.ts index 281a5e0e0d..0de7522cd1 100644 --- a/src/domain/desktop/appDownloadDesktop.ts +++ b/src/domain/desktop/appDownloadDesktop.ts @@ -62,13 +62,17 @@ def program_span(raw): directory = None while index < len(tokens): option = tokens[index][0] - if option in ("-C", "--chdir"): + if option == "--ignore-environment" or re.fullmatch(r"-i+", option): + index += 1 + continue + short_directory = re.fullmatch(r"-i*C(.*)", option, re.DOTALL) + if option == "--chdir" or (short_directory and not short_directory[1]): index += 1 directory = tokens[index][0] if index < len(tokens) else "" elif option.startswith("--chdir="): directory = option[len("--chdir="):] - elif option.startswith("-C"): - directory = option[2:] + elif short_directory: + directory = short_directory[1] else: break index += 1 @@ -76,6 +80,8 @@ def program_span(raw): raise ValueError("missing env chdir directory in desktop Exec") if index < len(tokens) and tokens[index][0] == "--": index += 1 + if index < len(tokens) and tokens[index][0] == "-": + index += 1 while index < len(tokens) and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", tokens[index][0]): index += 1 if index >= len(tokens) or not tokens[index][0]: diff --git a/src/domain/desktop/desktopEntry.test.ts b/src/domain/desktop/desktopEntry.test.ts index e465a48852..04e04b7495 100644 --- a/src/domain/desktop/desktopEntry.test.ts +++ b/src/domain/desktop/desktopEntry.test.ts @@ -177,6 +177,29 @@ describe("expandDesktopExec", () => { }); describe("unwrapDesktopCommand", () => { + it("combines a clean environment with an env-selected launch directory", () => { + expect( + unwrapDesktopCommand([ + "env", + "-i", + "-C", + "/tmp", + "--", + "A=1", + "app", + "--ignore-environment", + ]), + ).toEqual({ + kind: "direct", + program: "app", + index: 6, + argumentIndex: 7, + environment: { A: "1" }, + clearEnvironment: true, + chdir: { path: "/tmp", start: 2, end: 4 }, + }); + }); + it("keeps an env operand named -- after an assignment distinct from the option terminator", () => { expect( unwrapDesktopCommand(["env", "MODE=selected", "--", "notes"]), @@ -228,6 +251,7 @@ describe("unwrapDesktopCommand", () => { ).toEqual({ kind: "flatpak", program: "/usr/bin/flatpak", + index: 0, argumentIndex: 5, environment: {}, application_id: "net.cozic.joplin_desktop", diff --git a/src/domain/desktop/desktopEntry.ts b/src/domain/desktop/desktopEntry.ts index 8369aba7b4..03945263b9 100644 --- a/src/domain/desktop/desktopEntry.ts +++ b/src/domain/desktop/desktopEntry.ts @@ -265,21 +265,25 @@ export const expandDesktopExec = ( export type DesktopCommandWrapper = { /** The program `env` runs, or the first argument when there is no `env`. */ readonly program: string; + /** The program's position in the expanded command, after any env operands. */ + readonly index: number; /** Variables an `env` prefix sets; its `PATH` is the one that finds the program. */ readonly environment: Readonly>; + /** Present when the env wrapper discards all inherited variables. */ + readonly clearEnvironment?: true; /** The last env chdir option and the argv span that carries its operand. */ readonly chdir?: { readonly path: string; readonly start: number; readonly end: number; + /** This option also requests a clean environment, as in `-iC`. */ + readonly includesClearEnvironment?: true; }; /** First argument of the application, after the program or flatpak's app id. */ readonly argumentIndex: number; } & ( | { readonly kind: "direct"; - /** The program's position in the command. */ - readonly index: number; } | { readonly kind: "flatpak"; readonly application_id: string | null } ); @@ -353,50 +357,80 @@ const flatpakApplication = (argv: readonly string[], start: number) => { return { application_id: null, argumentIndex: argv.length }; }; -/** Apply env directory and assignment prefixes and recognise flatpak run launchers. */ -export const unwrapDesktopCommand = ( - argv: readonly string[], -): DesktopCommandWrapper => { - let index = 0; +const desktopEnvironment = (argv: readonly string[]) => { + let index = 1; + let clearEnvironment = false; let chdir: DesktopCommandWrapper["chdir"]; // No prototype, so an assignment such as `__proto__=x` stays a variable. const environment: Record = Object.create(null); - if (argv[0]?.split("/").at(-1) === "env") { - index = 1; - while (index < argv.length) { - const option = argv[index]!; - const separate = option === "-C" || option === "--chdir"; - const path = separate - ? (argv[index + 1] ?? "") - : option.startsWith("--chdir=") - ? option.slice("--chdir=".length) - : option.startsWith("-C") - ? option.slice(2) - : undefined; - if (path === undefined) break; - const start = index; - index += separate ? 2 : 1; - chdir = { path, start, end: index }; - } - // Only the option terminator before the first operand belongs to env; - // a later `--` can name the command or belong to the application. - if (argv[index] === "--") index += 1; - while (/^[A-Za-z_][A-Za-z0-9_]*=/u.test(argv[index] ?? "")) { - const assignment = argv[index] ?? ""; - const split = assignment.indexOf("="); - environment[assignment.slice(0, split)] = assignment.slice(split + 1); + while (index < argv.length) { + const option = argv[index]!; + if (/^-i+$/u.test(option) || option === "--ignore-environment") { + clearEnvironment = true; index += 1; + continue; } + const shortDirectory = /^-(i*)C(.*)$/su.exec(option); + const separate = shortDirectory?.[2] === "" || option === "--chdir"; + const path = separate + ? (argv[index + 1] ?? "") + : option.startsWith("--chdir=") + ? option.slice("--chdir=".length) + : shortDirectory?.[2]; + if (path === undefined) break; + const start = index; + index += separate ? 2 : 1; + const combined = Boolean(shortDirectory?.[1]); + if (combined) clearEnvironment = true; + chdir = { + path, + start, + end: index, + ...(combined ? { includesClearEnvironment: true as const } : {}), + }; } + // Only the option terminator before the first operand belongs to env; + // a later `--` can name the command or belong to the application. + if (argv[index] === "--") index += 1; + if (argv[index] === "-") { + clearEnvironment = true; + index += 1; + } + while (/^[A-Za-z_][A-Za-z0-9_]*=/u.test(argv[index] ?? "")) { + const assignment = argv[index] ?? ""; + const split = assignment.indexOf("="); + environment[assignment.slice(0, split)] = assignment.slice(split + 1); + index += 1; + } + return { index, chdir, clearEnvironment, environment }; +}; + +/** Apply env prefixes and recognise flatpak run launchers. */ +export const unwrapDesktopCommand = ( + argv: readonly string[], +): DesktopCommandWrapper => { + const { index, chdir, clearEnvironment, environment } = + argv[0]?.split("/").at(-1) === "env" + ? desktopEnvironment(argv) + : { + index: 0, + chdir: undefined, + clearEnvironment: false, + environment: Object.create(null) as Record, + }; const program = argv[index] ?? ""; - const directoryOption = chdir === undefined ? {} : { chdir }; + const wrapperOptions = { + ...(chdir === undefined ? {} : { chdir }), + ...(clearEnvironment ? { clearEnvironment: true as const } : {}), + }; if (program.split("/").at(-1) === "flatpak" && argv[index + 1] === "run") return { kind: "flatpak", program, + index, environment, ...flatpakApplication(argv, index + 2), - ...directoryOption, + ...wrapperOptions, }; return { kind: "direct", @@ -404,6 +438,6 @@ export const unwrapDesktopCommand = ( environment, index, argumentIndex: index + 1, - ...directoryOption, + ...wrapperOptions, }; }; diff --git a/src/ports/DesktopApplicationSession.ts b/src/ports/DesktopApplicationSession.ts index 1b3a678861..e4a9f0d470 100644 --- a/src/ports/DesktopApplicationSession.ts +++ b/src/ports/DesktopApplicationSession.ts @@ -103,6 +103,8 @@ export interface LinuxApplicationRequest { /** The inventory plus limitations found while building it. */ export interface LinuxApplicationFacts { readonly inventory: DesktopApplicationInventory; + /** If wrapped by env, where a final environment assignment goes in inventory.argv. */ + readonly envProgramIndex?: number; readonly limitations: readonly string[]; /** Verified apt signing keys' bytes by sha256, for the capture to retain. */ readonly signingKeys: ReadonlyMap; @@ -143,6 +145,8 @@ export type CheckpointTrigger = "request" | "stop" | "exit"; /** Everything the session loop needs from its caller. */ export interface DesktopSessionPlan { readonly argv: readonly string[]; + /** Where a final environment assignment goes when argv starts with env. */ + readonly envProgramIndex?: number; readonly workingDirectory: string; readonly environment: NodeJS.ProcessEnv; readonly windows: DesktopWindowObserver; diff --git a/tests/boundary/providers/desktopBuildInstall.test.ts b/tests/boundary/providers/desktopBuildInstall.test.ts index cefc9ee1ca..f2c8949ed2 100644 --- a/tests/boundary/providers/desktopBuildInstall.test.ts +++ b/tests/boundary/providers/desktopBuildInstall.test.ts @@ -140,7 +140,15 @@ describe("download install scripts", () => { expect(failed?.stderr).toContain("drawio.desktop"); }); - it.each(["", "-- ", "-C /opt --chdir=/tmp -- ", "--chdir= -C /tmp -- "])( + it.each([ + "", + "-- ", + "-C /opt --chdir=/tmp -- ", + "-iC/tmp -- ", + "--ignore-environment ", + "-- - ", + "--chdir= -C /tmp -- ", + ])( "keeps an env %sprefix and its assignments when it points the AppImage's entry at AppRun", async (delimiter) => { const root = await stage("rea-appimage-env-"); diff --git a/tests/boundary/providers/desktopLaunchCommand.test.ts b/tests/boundary/providers/desktopLaunchCommand.test.ts index e4dd3cf08c..d736b19c89 100644 --- a/tests/boundary/providers/desktopLaunchCommand.test.ts +++ b/tests/boundary/providers/desktopLaunchCommand.test.ts @@ -15,9 +15,12 @@ import { launchCommand } from "../../../src/domain/desktop/appExport.js"; import { planLaunch } from "../../../src/application/desktop/DesktopExportLaunch.js"; import type { DesktopApplicationCapture } from "../../../src/domain/desktop/desktopCapture.js"; -it.skipIf(process.platform === "win32")( - "launches in an empty env-selected directory under the replay home", - () => { +it.skipIf(process.platform === "win32").each([ + ["--chdir", false], + ["-iC", true], +])( + "replays an empty directory selected by env %s with the expected environment", + (option, clean) => { const home = mkdtempSync(join(tmpdir(), "rea-working-home-")); try { const selected = "Projects/Empty workspace"; @@ -26,9 +29,11 @@ it.skipIf(process.platform === "win32")( application: { argv: [ "/usr/bin/env", - "--chdir", + option, `/home/ada/${selected}`, - "/bin/pwd", + process.execPath, + "-e", + "console.log(process.cwd()); console.log(process.env.REA_REPLAY_MARKER)", ], working_directory: "/home/ada/ambient", application_working_directory: `/home/ada/${selected}`, @@ -41,10 +46,13 @@ it.skipIf(process.platform === "win32")( } = planLaunch(capture, false, new Map(), new Map()); const result = spawnSync(program!, args, { encoding: "utf8", - env: { ...process.env, HOME: home }, + env: { ...process.env, HOME: home, REA_REPLAY_MARKER: "inherited" }, }); expect(result.status, result.stderr).toBe(0); - expect(result.stdout.trimEnd()).toBe(join(realpathSync(home), selected)); + expect(result.stdout.trimEnd().split("\n")).toEqual([ + join(realpathSync(home), selected), + clean ? "undefined" : "inherited", + ]); } finally { rmSync(home, { recursive: true, force: true }); }