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>
This commit is contained in:
ShuaixinHuangandmorluto authored and GitHub committed 2026-11-19 02:10:50 +00:00
1 parent c5e44c8857
commit b1a390fcee
13 files changed
+278 -49

No files matched your search

+8
View File
@@ -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
@@ -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",
() => {
@@ -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,
@@ -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),
+12 -1
View File
@@ -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_,
@@ -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"));
},
);
},
);
+23 -2
View File
@@ -247,6 +247,23 @@ const readHeader = async (
}
};
const launchEnvironment = (
wrapper: ReturnType<typeof unwrapDesktopCommand>,
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,
});
+9 -3
View File
@@ -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]:
+24
View File
@@ -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",
+68 -34
View File
@@ -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<Record<string, string>>;
/** 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<string, string> = 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<string, string>,
};
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,
};
};
+4
View File
@@ -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<string, Buffer>;
@@ -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;
@@ -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-");
@@ -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 });
}