The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): the system proxy reaches only the update's children
Teknium20e892f81a32
diff --git a/apps/desktop/electron/entry.ts b/apps/desktop/electron/entry.tsindex 85720e42381..115433928d8 100644--- a/apps/desktop/electron/entry.ts+++ b/apps/desktop/electron/entry.ts@@ -7,9 +7,14 @@ import { app } from 'electron'import { resolveDesktopHermesHome } from './data-paths'import { releasePackagedWorkingDirectory } from './packaged-working-directory'import { readDesktopLaunchConfig } from './renderer-heap-flags'+import { restoreUserProxyEnv } from './updater/system-proxy-env'import { wslgLaunchArgs } from './wslg-launch'import { spawnWslgLaunch } from './wslg-launch-process'+// A Desktop relaunched by an update (any rung: hand-off script, staged updater,+// Start-Process) must not keep the system proxy the update's children were given.+restoreUserProxyEnv(process.env)+// `hermes desktop` asks this binary whether Chromium's namespace sandbox starts under the host's// AppArmor policy (#130177). Chromium creates its sandboxed zygote before any JS runs, so reaching// this line answers yes; exit before any window, single-instance lock, backend or relaunch.diff --git a/apps/desktop/electron/updater/checkout-source.ts b/apps/desktop/electron/updater/checkout-source.tsindex cc04236bfcf..ac256f36bbf 100644--- a/apps/desktop/electron/updater/checkout-source.ts+++ b/apps/desktop/electron/updater/checkout-source.ts@@ -54,11 +54,19 @@ function probeFlags(probe: SourceUpdateProbe): string[] {]}-/** Every update child's env: the system proxy when none is set (#123387), then this process's env. */-export async function sourceUpdateEnvironment(updateRoot: string, hermesHome: string): Promise<NodeJS.ProcessEnv> {+/**+ * Every update child's env: this process's env plus the system proxy when none+ * is set (#123387). The proxy env comes last so its extended NO_PROXY is the+ * one the children read; it is empty whenever the user set a proxy.+ */+export async function sourceUpdateEnvironment(+ updateRoot: string,+ hermesHome: string,+ note?: (message: string) => void+): Promise<NodeJS.ProcessEnv> {const env: NodeJS.ProcessEnv = {- ...(await updateProxyEnv()),...process.env,+ ...(await updateProxyEnv(process.env, note)),...buildDesktopBackendEnv(),HERMES_HOME: hermesHome,HERMES_INSTALL_ROOT: updateRootdiff --git a/apps/desktop/electron/updater/checkout.ts b/apps/desktop/electron/updater/checkout.tsindex b2d149c003e..7589afcf232 100644--- a/apps/desktop/electron/updater/checkout.ts+++ b/apps/desktop/electron/updater/checkout.ts@@ -367,7 +367,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): CheckoutStraconst child = spawnUpdaterProcess(updater, updaterArgs, {cwd: deps.hermesHome,env: {- ...(await sourceUpdateEnvironment(updateRoot, deps.hermesHome))+ ...(await sourceUpdateEnvironment(updateRoot, deps.hermesHome, deps.rememberLog))},detached: true,stdio: 'ignore'@@ -753,7 +753,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): CheckoutStraconst child = spawnUpdaterProcess(handoff.command, args, {cwd: deps.hermesHome,env: {- ...(await sourceUpdateEnvironment(updateRoot, deps.hermesHome)),+ ...(await sourceUpdateEnvironment(updateRoot, deps.hermesHome, deps.rememberLog)),HERMES_UPDATE_STARTED_AT: String(updateStartedAt)},detached: true,diff --git a/apps/desktop/electron/updater/system-proxy-env.test.ts b/apps/desktop/electron/updater/system-proxy-env.test.tsindex 8cb695c2384..86d552eeab6 100644--- a/apps/desktop/electron/updater/system-proxy-env.test.ts+++ b/apps/desktop/electron/updater/system-proxy-env.test.ts@@ -1,8 +1,9 @@import { describe, expect, it } from 'vitest'-import { systemProxyEnv } from './system-proxy-env'+import { LOCAL_BYPASS, restoreUserProxyEnv, systemProxyEnv } from './system-proxy-env'const pac = (answers: Record<string, string>) => async (url: string) => answers[new URL(url).hostname] ?? 'DIRECT'+const proxied = (value: string) => ({ HTTPS_PROXY: value, https_proxy: value, HTTP_PROXY: value, http_proxy: value })describe('update child proxy env from the system proxy (#123387)', () => {it('hands the system proxy to children that read only proxy env, bypassing hosts the system sends direct', async () => {@@ -12,28 +13,75 @@ describe('update child proxy env from the system proxy (#123387)', () => {['github.com', 'registry.npmjs.org', 'pypi.org'])+ const noProxy = [...LOCAL_BYPASS, 'registry.npmjs.org'].join(',')+expect(env).toEqual({- HTTPS_PROXY: 'http://10.0.0.7:7890',- https_proxy: 'http://10.0.0.7:7890',- HTTP_PROXY: 'http://10.0.0.7:7890',- http_proxy: 'http://10.0.0.7:7890',- NO_PROXY: 'localhost,127.0.0.1,::1,registry.npmjs.org',- no_proxy: 'localhost,127.0.0.1,::1,registry.npmjs.org'+ ...proxied('http://10.0.0.7:7890'),+ NO_PROXY: noProxy,+ no_proxy: noProxy,+ HERMES_UPDATE_SYSTEM_PROXY: 'HTTPS_PROXY,https_proxy,HTTP_PROXY,http_proxy,NO_PROXY,no_proxy'})})+ it('bypasses loopback, private ranges and .local names a PAC sends direct', async () => {+ const env = await systemProxyEnv({}, pac({ 'github.com': 'PROXY 10.0.0.7:7890' }), ['github.com'])++ for (const entry of ['127.0.0.0/8', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '::1', '.local']) {+ expect(env.NO_PROXY?.split(',')).toContain(entry)+ }+ })+it('leaves an explicit proxy env alone and adds nothing when the system goes direct', async () => {const asked: string[] = []const resolve = async (url: string) => {asked.push(url)- return 'SOCKS5 10.0.0.9:1080'+ return 'PROXY 10.0.0.9:1080'}expect(await systemProxyEnv({ https_proxy: 'http://corp:3128' }, resolve)).toEqual({})expect(asked).toEqual([])expect(await systemProxyEnv({}, async () => 'DIRECT')).toEqual({})- expect((await systemProxyEnv({}, resolve, ['github.com'])).HTTPS_PROXY).toBe('socks5h://10.0.0.9:1080')+ })++ it('exports no SOCKS or TLS proxy, which urllib and npm cannot use, and says so', async () => {+ for (const answer of ['SOCKS 10.0.0.9:1080', 'SOCKS5 10.0.0.9:1080', 'HTTPS 10.0.0.9:443']) {+ const notes: string[] = []++ expect(await systemProxyEnv({}, async () => answer, ['github.com'], note => notes.push(note))).toEqual({})+ expect(notes.join()).toContain(`github.com=${answer.split(' ')[0]}`)+ }+ })++ it('never routes one host through the proxy the PAC chose for another', async () => {+ const notes: string[] = []++ const env = await systemProxyEnv(+ {},+ pac({ 'github.com': 'PROXY 10.0.0.7:7890', 'pypi.org': 'PROXY 10.0.0.8:3128' }),+ ['github.com', 'pypi.org'],+ note => notes.push(note)+ )++ expect(env).toEqual({})+ expect(notes).toHaveLength(1)+ })++ it("extends the user's own NO_PROXY instead of replacing it, and restores it for the relaunched app", async () => {+ const user = { PATH: '/usr/bin', NO_PROXY: 'corp.internal' }+ const env = await systemProxyEnv(user, pac({ 'github.com': 'PROXY 10.0.0.7:7890' }), ['github.com'])++ expect(env.NO_PROXY).toBe(['corp.internal', ...LOCAL_BYPASS].join(','))+ expect(env.no_proxy).toBe(env.NO_PROXY)+ expect(restoreUserProxyEnv({ ...user, ...env })).toEqual(user)+ })++ it('never reads a proxy an earlier update marked as the user setting', async () => {+ const first = await systemProxyEnv({}, pac({ 'github.com': 'PROXY 10.0.0.7:7890' }), ['github.com'])+ // The system proxy moved; an env still carrying the first answer must not pin it.+ const next = await systemProxyEnv(first, pac({ 'github.com': 'PROXY 10.0.0.42:8080' }), ['github.com'])++ expect(next.HTTPS_PROXY).toBe('http://10.0.0.42:8080')})})diff --git a/apps/desktop/electron/updater/system-proxy-env.ts b/apps/desktop/electron/updater/system-proxy-env.tsindex d49251dfe26..3c9c45a2ba6 100644--- a/apps/desktop/electron/updater/system-proxy-env.ts+++ b/apps/desktop/electron/updater/system-proxy-env.ts@@ -10,9 +10,25 @@ import { session } from 'electron'* resolves the system proxy (PAC included), so ask it for the hosts the update* reaches and hand the answer to the children as proxy env. Explicit proxy env* always wins: it is returned untouched.+ *+ * The env is for the update's children only. The hand-off script, the staged+ * updater and `hermes update` start the relaunched Desktop and gateways, which+ * would otherwise inherit it as if the user had set it: every LAN host the PAC+ * sends direct would be proxied, and the next update would read the stale value+ * as an explicit setting. So every variable the Desktop adds is named in+ * UPDATE_PROXY_MARKER and every NO_PROXY it extends is saved under SAVED_PREFIX;+ * restoreUserProxyEnv (and its ports in posix.sh, windows.ps1 and gateway+ * start) puts the user's own env back.*/const PROXY_ENV_KEYS = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy']+const PROXY_SET_KEYS = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy']+const NO_PROXY_KEYS = ['NO_PROXY', 'no_proxy']++/** Comma list of the variables the Desktop added to an update child's env. */+export const UPDATE_PROXY_MARKER = 'HERMES_UPDATE_SYSTEM_PROXY'+/** `${SAVED_PREFIX}NO_PROXY` holds the user's own NO_PROXY that the Desktop extended. */+export const SAVED_PREFIX = 'HERMES_UPDATE_USER_'// git + the GitHub API and assets, the release pointer, npm, PyPI + uv, Electron downloads.export const UPDATE_HOSTS = [@@ -28,63 +44,138 @@ export const UPDATE_HOSTS = ['releases.astral.sh']-const LOCAL_BYPASS = ['localhost', '127.0.0.1', '::1']+// Loopback, RFC 1918 and mDNS names never go through a remote proxy. curl (git)+// and uv read the CIDR entries; urllib and npm match the names.+export const LOCAL_BYPASS = [+ 'localhost',+ '127.0.0.1',+ '::1',+ '127.0.0.0/8',+ '10.0.0.0/8',+ '172.16.0.0/12',+ '192.168.0.0/16',+ '.local'+]++function pacKind(answer: string): [string, string] {+ const [kind = '', hostPort = ''] = (answer.split(';')[0] ?? '').trim().split(/\s+/)-const PAC_SCHEMES: Record<string, string> = {- PROXY: 'http',- HTTPS: 'https',- SOCKS: 'socks5h',- SOCKS5: 'socks5h',- SOCKS4: 'socks4'+ return [kind.toUpperCase(), hostPort]}-/** Chromium's PAC-style answer ("PROXY host:port; DIRECT") as a proxy URL; null for DIRECT. */+/**+ * Chromium's PAC-style answer ("PROXY host:port; DIRECT") as a proxy URL every+ * update child can use; null for DIRECT and for kinds they cannot use. Python's+ * urllib speaks neither SOCKS nor TLS to a proxy (it sends a plaintext CONNECT),+ * npm reads no SOCKS env, httpx refuses socks4, and the update's own git calls+ * drop injected git config, so only a plain PROXY answer is exportable.+ */export function proxyUrlFromPac(answer: string): string | null {- const [kind = '', hostPort = ''] = (answer.split(';')[0] ?? '').trim().split(/\s+/)- const scheme = PAC_SCHEMES[kind.toUpperCase()]+ const [kind, hostPort] = pacKind(answer)++ return kind === 'PROXY' && hostPort ? `http://${hostPort}` : null+}++/** Undo what systemProxyEnv added: drop the marked variables, restore saved NO_PROXY values. */+export function restoreUserProxyEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {+ for (const key of (env[UPDATE_PROXY_MARKER] ?? '').split(',')) {+ if ([...PROXY_SET_KEYS, ...NO_PROXY_KEYS].includes(key)) {+ delete env[key]+ }+ }++ for (const key of NO_PROXY_KEYS) {+ const saved = env[`${SAVED_PREFIX}${key}`]++ if (saved !== undefined) {+ env[key] = saved+ delete env[`${SAVED_PREFIX}${key}`]+ }+ }- return scheme && hostPort ? `${scheme}://${hostPort}` : null+ delete env[UPDATE_PROXY_MARKER]++ return env+}++/** The user's own NO_PROXY entries, extended (never replaced) by the local bypass and DIRECT update hosts. */+function noProxyEnv(userEnv: NodeJS.ProcessEnv, direct: string[]): { env: NodeJS.ProcessEnv; added: string[] } {+ const user = `${userEnv.no_proxy ?? ''},${userEnv.NO_PROXY ?? ''}`+ const entries = user.split(',').map((entry: string): string => entry.trim())+ const value = [...new Set([...entries.filter(Boolean), ...LOCAL_BYPASS, ...direct])].join(',')+ const env: NodeJS.ProcessEnv = {}+ const added: string[] = []++ for (const key of NO_PROXY_KEYS) {+ env[key] = value++ if (userEnv[key] === undefined) {+ added.push(key)+ } else {+ env[`${SAVED_PREFIX}${key}`] = userEnv[key]+ }+ }++ return { env, added }}export async function systemProxyEnv(env: NodeJS.ProcessEnv,resolveProxy: (url: string) => Promise<string>,- hosts: string[] = UPDATE_HOSTS+ hosts: string[] = UPDATE_HOSTS,+ note: (message: string) => void = () => {}): Promise<NodeJS.ProcessEnv> {- if (PROXY_ENV_KEYS.some((key: string): boolean => Boolean(env[key]?.trim()))) {+ // A value an earlier update marked as the Desktop's is never the user's own.+ const userEnv = restoreUserProxyEnv({ ...env })++ if (PROXY_ENV_KEYS.some((key: string): boolean => Boolean(userEnv[key]?.trim()))) {return {}}+ // Each host is asked on its own: a PAC can send each one a different way.const answers = await Promise.all(- hosts.map(async (host: string) => ({- host,+ hosts.map(async (host: string) => {// A PAC script that fails to load leaves Chromium itself going direct.- proxy: proxyUrlFromPac(await resolveProxy(`https://${host}/`).catch((): string => 'DIRECT'))- }))+ const raw = await resolveProxy(`https://${host}/`).catch((): string => 'DIRECT')++ return { host, kind: pacKind(raw)[0] || 'DIRECT', proxy: proxyUrlFromPac(raw) }+ }))- const proxy = answers.find(answer => answer.proxy)?.proxy+ const routed = answers.filter(answer => answer.kind !== 'DIRECT')+ const proxies = new Set(routed.map(answer => answer.proxy))- if (!proxy) {+ if (!routed.length) {return {}}- const direct = answers.filter(answer => !answer.proxy).map(answer => answer.host)- const noProxy = env.NO_PROXY ?? env.no_proxy ?? [...LOCAL_BYPASS, ...direct].join(',')+ // One env proxy serves every host, so it is exported only when the system+ // sends each update host either through that one plain proxy or direct.+ if (proxies.size > 1 || proxies.has(null)) {+ const answered = routed.map(answer => `${answer.host}=${answer.kind}`).join(', ')++ note(`[updates] system proxy not passed to the update: ${answered} (only one plain PROXY answer can be)`)++ return {}+ }++ const proxy = routed[0].proxy as string+ const direct = answers.filter(answer => answer.kind === 'DIRECT').map(answer => answer.host)+ const noProxy = noProxyEnv(userEnv, direct)return {- HTTPS_PROXY: proxy,- https_proxy: proxy,- HTTP_PROXY: proxy,- http_proxy: proxy,- NO_PROXY: noProxy,- no_proxy: noProxy+ ...Object.fromEntries(PROXY_SET_KEYS.map((key: string) => [key, proxy])),+ ...noProxy.env,+ [UPDATE_PROXY_MARKER]: [...PROXY_SET_KEYS, ...noProxy.added].join(',')}}/** The system proxy env for an update child; empty outside Electron (unit tests, scripts). */-export async function updateProxyEnv(env: NodeJS.ProcessEnv = process.env): Promise<NodeJS.ProcessEnv> {+export async function updateProxyEnv(+ env: NodeJS.ProcessEnv = process.env,+ note?: (message: string) => void+): Promise<NodeJS.ProcessEnv> {const defaultSession = session?.defaultSession- return defaultSession ? systemProxyEnv(env, url => defaultSession.resolveProxy(url)) : {}+ return defaultSession ? systemProxyEnv(env, url => defaultSession.resolveProxy(url), UPDATE_HOSTS, note) : {}}diff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.pyindex b0b779ba927..12222c74642 100644--- a/gateway/run_bootstrap.py+++ b/gateway/run_bootstrap.py@@ -757,6 +757,8 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =)# Set here (not at import) so incidental gateway.run imports from CLI code don't poison it.os.environ["HERMES_EXEC_ASK"] = "1"+ from hermes_cli.update_proxy_env import restore_user_proxy_env+ restore_user_proxy_env() # a gateway an update restarted keeps the user's proxy env, not the update's_start_gateway_resolve_terminal_cwd()from hermes_cli.resource_limits import apply_nofile_soft_limitdiff --git a/hermes_cli/update_proxy_env.py b/hermes_cli/update_proxy_env.pynew file mode 100644index 00000000000..15cc73b31d5--- /dev/null+++ b/hermes_cli/update_proxy_env.py@@ -0,0 +1,34 @@+"""Undo the system proxy the Desktop handed to an update's children.++The Desktop resolves the OS proxy (PAC included) and gives it to the update's+git, urllib, npm and uv children as HTTPS_PROXY/HTTP_PROXY with an extended+NO_PROXY (apps/desktop/electron/updater/system-proxy-env.ts). ``hermes update``+then restarts gateways and backends that inherit that env; for them it is not+the user's setting, and every host the PAC sends direct (LAN model servers,+internal names) would go through the proxy. ``HERMES_UPDATE_SYSTEM_PROXY`` names+the variables the Desktop added and ``HERMES_UPDATE_USER_<KEY>`` holds a user's+own NO_PROXY it extended; a long-lived process restores its env from them at+start. Same algorithm as restoreUserProxyEnv, posix.sh and windows.ps1.+"""+from __future__ import annotations++import os+from typing import MutableMapping++MARKER = "HERMES_UPDATE_SYSTEM_PROXY"+SAVED_PREFIX = "HERMES_UPDATE_USER_"+_ADDED_KEYS = ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "NO_PROXY", "no_proxy")+_NO_PROXY_KEYS = ("NO_PROXY", "no_proxy")+++def restore_user_proxy_env(environ: MutableMapping[str, str] | None = None) -> None:+ """Drop the proxy variables the Desktop added and restore the user's own NO_PROXY."""+ env = os.environ if environ is None else environ+ for key in env.get(MARKER, "").split(","):+ if key in _ADDED_KEYS:+ env.pop(key, None)+ for key in _NO_PROXY_KEYS:+ saved = env.pop(SAVED_PREFIX + key, None)+ if saved is not None:+ env[key] = saved+ env.pop(MARKER, None)diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex f31a6c1d610..d9f9d1babe5 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -1410,6 +1410,8 @@ def start_server(until the ready sentinel is written so its SDK import can't hold the GILagainst the pre-bind path."""+ from hermes_cli.update_proxy_env import restore_user_proxy_env+ restore_user_proxy_env() # a backend an update replayed keeps the user's proxy env, not the update's_apply_ssh_session_token(ssh_session_token or "")_apply_ssh_owner_nonce(ssh_owner_nonce)diff --git a/scripts/desktop-update/posix.sh b/scripts/desktop-update/posix.shindex 34b9b4c6f2b..92daa67d1a3 100755--- a/scripts/desktop-update/posix.sh+++ b/scripts/desktop-update/posix.sh@@ -682,6 +682,20 @@ deliver_outcome() { # the truth-determining half: swap bundles / gate the relaunfi}+restore_user_proxy_env() { # port of restoreUserProxyEnv (electron/updater/system-proxy-env.ts):+ # the Desktop gave its system proxy to the update only; the relaunched app gets the user's own env.+ local key saved keys+ IFS=, read -r -a keys <<< "${HERMES_UPDATE_SYSTEM_PROXY:-}"+ for key in ${keys[@]+"${keys[@]}"}; do+ case "$key" in HTTPS_PROXY|https_proxy|HTTP_PROXY|http_proxy|NO_PROXY|no_proxy) unset "$key" ;; esac+ done+ for key in NO_PROXY no_proxy; do+ saved="HERMES_UPDATE_USER_$key"+ if printenv "$saved" >/dev/null; then export "$key=$(printenv "$saved")"; unset "$saved"; fi+ done+ unset HERMES_UPDATE_SYSTEM_PROXY+}+launch_app() { # attempted BEFORE the terminal event (launch acceptance is# part of the outcome — gille's review). Returns nonzero when a launch# was due but did not verifiably happen; caller downgrades to manual.@@ -699,7 +713,7 @@ launch_app() { # attempted BEFORE the terminal event (launch acceptance is/usr/bin/xattr -dr com.apple.quarantine "$RELAUNCH_TARGET" 2>/dev/null || true# `open` talks to launchd and FAILS LOUDLY on a broken/unlaunchable# bundle — its exit code IS launch acceptance here.- /usr/bin/open "$RELAUNCH_TARGET" || { log "WARNING: open rejected the app"; return 1; }+ ( restore_user_proxy_env; /usr/bin/open "$RELAUNCH_TARGET" ) || { log "WARNING: open rejected the app"; return 1; }elif [ "$GATE" = "relaunch" ]; then# setsid only proves the wrapper shell started, so verify acceptance:# spawn, then confirm the child is still alive shortly after — an@@ -707,6 +721,7 @@ launch_app() { # attempted BEFORE the terminal event (launch acceptance is# within the window and downgrades to manual instead of lying.(cd "${RELAUNCH_CWD:-/}" 2>/dev/null || cd /# The relaunched app must not inherit the hand-off's update env.+ restore_user_proxy_envenv -u HERMES_UPDATE_STATUS_FILE -u HERMES_UPDATE_STARTED_AT -u HERMES_UPDATE_HANDOFF_PID -u PYTHONUNBUFFERED \setsid "$RELAUNCH_TARGET" ${RELAUNCH_ARGS[@]+"${RELAUNCH_ARGS[@]}"} >/dev/null 2>&1 &echo $! > "$STATUS.launchpid") || { log "WARNING: relaunch spawn failed"; return 1; }diff --git a/scripts/desktop-update/windows.ps1 b/scripts/desktop-update/windows.ps1index 9a3b4bc76d1..ddf5323f046 100644--- a/scripts/desktop-update/windows.ps1+++ b/scripts/desktop-update/windows.ps1@@ -762,6 +762,21 @@ function Get-DesktopWorkingDirectory {return [Environment]::GetFolderPath('UserProfile')}+function Restore-UserProxyEnv {+ # Port of restoreUserProxyEnv (electron/updater/system-proxy-env.ts): the Desktop handed its+ # system proxy to the update only. HERMES_UPDATE_SYSTEM_PROXY names the variables it added and+ # HERMES_UPDATE_USER_NO_PROXY holds the user's own NO_PROXY it extended.+ foreach ($key in ("$env:HERMES_UPDATE_SYSTEM_PROXY" -split ',')) {+ if (@('HTTPS_PROXY', 'HTTP_PROXY', 'NO_PROXY') -contains $key) { Remove-Item "Env:$key" -ErrorAction SilentlyContinue }+ }+ $saved = [Environment]::GetEnvironmentVariable('HERMES_UPDATE_USER_NO_PROXY', 'Process')+ if ($null -ne $saved) {+ [Environment]::SetEnvironmentVariable('NO_PROXY', $saved, 'Process')+ Remove-Item Env:HERMES_UPDATE_USER_NO_PROXY -ErrorAction SilentlyContinue+ }+ Remove-Item Env:HERMES_UPDATE_SYSTEM_PROXY -ErrorAction SilentlyContinue+}+function Start-DesktopRelaunch {# Returns $true only when a launch VERIFIABLY happened (WMI accepted and# the pid exists, or the fallback spawn returned a live process). The@@ -892,6 +907,8 @@ function Start-DesktopRelaunch {Write-HandoffLog "WARNING: explorer relaunch failed: $($_.Exception.Message); falling back"}}+ # Only the tethered rung below inherits this script's env; the relaunched app gets the user's own.+ Restore-UserProxyEnvif (-not $spawned) {try {# Fallback keeps the old behavior (console tie-in and all) --diff --git a/tests/hermes_cli/test_update_proxy_env.py b/tests/hermes_cli/test_update_proxy_env.pynew file mode 100644index 00000000000..2a6ea44591a--- /dev/null+++ b/tests/hermes_cli/test_update_proxy_env.py@@ -0,0 +1,19 @@+import os++from hermes_cli.update_proxy_env import restore_user_proxy_env+++def test_marked_update_proxy_env_is_undone_and_the_users_own_env_kept():+ user = {"PATH": "/usr/bin", "no_proxy": "corp.internal", "ALL_PROXY": "socks5h://user:1080"}+ env = {**user, "HTTPS_PROXY": "http://10.0.0.7:7890", "https_proxy": "http://10.0.0.7:7890",+ "NO_PROXY": "corp.internal,localhost,10.0.0.0/8", "no_proxy": "corp.internal,localhost,10.0.0.0/8",+ "HERMES_UPDATE_SYSTEM_PROXY": "HTTPS_PROXY,https_proxy,NO_PROXY,PATH",+ "HERMES_UPDATE_USER_no_proxy": "corp.internal"}++ restore_user_proxy_env(env)++ assert env == user # a key outside the proxy set (PATH) is never dropped+ unmarked = {"HTTPS_PROXY": "http://mine:3128", "NO_PROXY": "lan"}+ restore_user_proxy_env(unmarked)+ assert unmarked == {"HTTPS_PROXY": "http://mine:3128", "NO_PROXY": "lan"}+ assert "HERMES_UPDATE_SYSTEM_PROXY" not in os.environdiff --git a/tests/scripts/desktop_update/test_desktop_update_relaunch_proxy_env.py b/tests/scripts/desktop_update/test_desktop_update_relaunch_proxy_env.pynew file mode 100644index 00000000000..0e28f79891d--- /dev/null+++ b/tests/scripts/desktop_update/test_desktop_update_relaunch_proxy_env.py@@ -0,0 +1,55 @@+"""posix.sh relaunches the Desktop with the user's proxy env, not the one the update was given.++The Desktop hands its resolved system proxy to the update's children only+(apps/desktop/electron/updater/system-proxy-env.ts) and marks it:+HERMES_UPDATE_SYSTEM_PROXY names the variables it added, HERMES_UPDATE_USER_<KEY>+holds a NO_PROXY of the user's that it extended. The relaunched app inheriting+that env would proxy every LAN host the PAC sends direct, and the next update+would read the stale proxy as the user's own setting.+"""+from __future__ import annotations++from pathlib import Path++import pytest++from tests.scripts.desktop_update.test_desktop_update_posix_marker import _install, _run+from tests.waiting import wait_until++pytestmark = pytest.mark.platforms("linux")++_DESKTOP_PROXY_ENV = {+ "HTTPS_PROXY": "http://10.0.0.7:7890",+ "https_proxy": "http://10.0.0.7:7890",+ "HTTP_PROXY": "http://10.0.0.7:7890",+ "http_proxy": "http://10.0.0.7:7890",+ "NO_PROXY": "corp.internal,localhost,127.0.0.1,::1,10.0.0.0/8",+ "no_proxy": "corp.internal,localhost,127.0.0.1,::1,10.0.0.0/8",+ "HERMES_UPDATE_SYSTEM_PROXY": "HTTPS_PROXY,https_proxy,HTTP_PROXY,http_proxy,no_proxy",+ "HERMES_UPDATE_USER_NO_PROXY": "corp.internal",+}+++def test_relaunched_desktop_gets_the_users_proxy_env_back(tmp_path, monkeypatch):+ for key in ("HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "NO_PROXY"):+ monkeypatch.delenv(key, raising=False)+ monkeypatch.delenv(key.lower(), raising=False)+ home, install = _install(tmp_path)+ unpacked = install / "apps/desktop/release/linux-unpacked"+ unpacked.mkdir(parents=True)+ app = unpacked / "hermes"+ dump = tmp_path / "relaunched-env.txt"+ app.write_text(f"#!/bin/sh\necho $$ > {dump}.pid\n"+ f"env | grep -i -E '_proxy=|^HERMES_UPDATE_(SYSTEM_PROXY|USER_)' > {dump}.part; mv {dump}.part {dump}\n"+ # Outlive posix.sh's 1.5 s launch-acceptance check, then exit before teardown.+ "sleep 2\n",+ encoding="utf-8")+ app.chmod(0o755)++ result = _run(tmp_path, home, install, "--relaunch-target", str(app), **_DESKTOP_PROXY_ENV)++ assert result.returncode == 0, result.stdout + result.stderr+ pid = dump.with_name(dump.name + ".pid").read_text(encoding="utf-8").strip()+ wait_until(lambda: not Path(f"/proc/{pid}").exists(), timeout=10, what="the relaunched app to exit")+ relaunched = dict(line.split("=", 1) for line in dump.read_text(encoding="utf-8").splitlines())+ assert relaunched == {"NO_PROXY": "corp.internal"}