The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): constrain baked environment and validate registered feeds
ethernetedcb3346a737
diff --git a/apps/desktop/BUILDING.md b/apps/desktop/BUILDING.mdindex 85aa2c87774..7e4563ce069 100644--- a/apps/desktop/BUILDING.md+++ b/apps/desktop/BUILDING.md@@ -184,8 +184,11 @@ runtime overrides; `--bundle-env HERMES_HOME=` is a default, not a forced clear.For local commit builds, `HERMES_BUNDLE_ENV_JSON` accepts a JSON object whosestring values are defaults and whose `null` values are explicit clears. For example,-`{"HERMES_HOME":null,"HERMES_DATA_DIR_SUFFIX":"magic-test"}`. These settings are-not applied to the build runner itself.+`{"HERMES_HOME":null,"HERMES_DATA_DIR_SUFFIX":"magic-test"}`. Only+`HERMES_HOME`, `HERMES_DATA_DIR_SUFFIX`, `HERMES_DESKTOP_USER_DATA_DIR`,+`HERMES_SHARED_AUTH_DIR`, `HERMES_GUEST_ONBOARDING`, and `HERMES_SKIP_INTRO`+are accepted. Process-control variables such as `NODE_OPTIONS` and `PATH`+are rejected. These settings are not applied to the build runner itself.Commit archive keys still use the SHA, so use a fresh commit for differentdefaults: an existing artifact is never overwritten with different bytes.diff --git a/apps/desktop/electron/updater/app-installer-strategy.test.ts b/apps/desktop/electron/updater/app-installer-strategy.test.tsindex 1aad9ecfdcf..080ec81b18a 100644--- a/apps/desktop/electron/updater/app-installer-strategy.test.ts+++ b/apps/desktop/electron/updater/app-installer-strategy.test.ts@@ -97,6 +97,19 @@ describe('AppInstallerStrategy.apply', () => {expect(calls).toEqual(['relaunch-marker', 'teardown', 'quit'])})+ it.each(['http://external.example/update.appinstaller', 'https://user:[email protected]/update.appinstaller', 'https://registered.example/../update.appinstaller'])(+ 'rejects an unsafe registered source URI before staging: %s',+ async (sourceUri: string): Promise<void> => {+ const { deps, calls } = makeDeps({+ feedBaseUrl: '',+ run: async () => ({ code: 2, stdout: JSON.stringify({ available: true, source_uri: sourceUri }) })+ })++ await expect(new AppInstallerStrategy(deps).apply()).rejects.toThrow()+ expect(calls).toEqual([])+ }+ )+it('uses an exact descriptor without a Python check, and rejects unverified prepared packages before teardown', async (): Promise<void> => {const { deps, calls } = makeDeps({run: async (): Promise<never> => {diff --git a/apps/desktop/electron/updater/app-installer.ts b/apps/desktop/electron/updater/app-installer.tsindex fb5aefcf460..c95911f7052 100644--- a/apps/desktop/electron/updater/app-installer.ts+++ b/apps/desktop/electron/updater/app-installer.ts@@ -138,6 +138,10 @@ export class AppInstallerStrategy {if (!feedBaseUrl && !sourceUri) {const { code, stdout } = await this.deps.run(this.deps.python, this.deps.script)sourceUri = parseCheckOutput(code, stdout).sourceUri++ if (sourceUri) {+ channelPublicBase(sourceUri)+ }}if (!feedBaseUrl && !sourceUri) {diff --git a/apps/desktop/electron/updater/channel-protocol.ts b/apps/desktop/electron/updater/channel-protocol.tsindex 4fa892b2846..4e67c1bb627 100644--- a/apps/desktop/electron/updater/channel-protocol.ts+++ b/apps/desktop/electron/updater/channel-protocol.ts@@ -361,8 +361,14 @@ function request(fields: Fields): ChannelRequest {const environment = fields.object('bundleEnv')const bundleEnv: ChannelBuild['bundleEnv'] = {}+ // Match the build-time allowlist: a channel request cannot inject process flags.+ const allowed = new Set([+ 'HERMES_HOME', 'HERMES_DATA_DIR_SUFFIX', 'HERMES_DESKTOP_USER_DATA_DIR',+ 'HERMES_SHARED_AUTH_DIR', 'HERMES_GUEST_ONBOARDING', 'HERMES_SKIP_INTRO'+ ])+for (const key of environment.keys()) {- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {+ if (!allowed.has(key)) {throw new Error('Invalid bundle environment name')}diff --git a/apps/desktop/electron/updater/channel.test.ts b/apps/desktop/electron/updater/channel.test.tsindex 98b6dc11e84..4ddc56046ed 100644--- a/apps/desktop/electron/updater/channel.test.ts+++ b/apps/desktop/electron/updater/channel.test.ts@@ -175,6 +175,15 @@ async function retiredFixture(return { ...f, retired }}+test.each(['NODE_OPTIONS', 'PATH', 'HERMES_PYTHON'])(+ 'channel manifest rejects process-control bundle key %s',+ async (key: string): Promise<void> => {+ const f = await fixture()+ f.manifest.request.bundleEnv[key] = null+ expect((): void => { decodeChannelManifest(JSON.stringify(f.manifest)) }).toThrow('Invalid bundle environment name')+ }+)+test('receiver kind mirrors the identity comparison between retired channel and destination', async (): Promise<void> => {const f = await retiredFixture()diff --git a/apps/desktop/scripts/bundle-env.mjs b/apps/desktop/scripts/bundle-env.mjsindex ca739150875..8f617eecbbf 100644--- a/apps/desktop/scripts/bundle-env.mjs+++ b/apps/desktop/scripts/bundle-env.mjs@@ -1,5 +1,10 @@// Defaults must run before bundled modules resolve paths or onboarding flags.// An esbuild define would replace reads, not populate the child process env.+// Match scripts/releases/bundle_env.py and the channel request decoder.+const ALLOWED_KEYS = new Set([+ 'HERMES_HOME', 'HERMES_DATA_DIR_SUFFIX', 'HERMES_DESKTOP_USER_DATA_DIR',+ 'HERMES_SHARED_AUTH_DIR', 'HERMES_GUEST_ONBOARDING', 'HERMES_SKIP_INTRO'+])/** Validate a bundle environment object: plain object of identifiers to* strings (defaults) or null (clears). Shared by the banner writer and the@@ -10,8 +15,8 @@ export function validateBundleEnvironment(values) {throw new Error('Bundle environment must be a JSON object')}for (const [key, value] of Object.entries(values)) {- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || (value !== null && (typeof value !== 'string' || value.includes('\0')))) {- throw new Error('Bundle environment requires valid names and string values without NUL, or null to clear')+ if (!ALLOWED_KEYS.has(key) || (value !== null && (typeof value !== 'string' || value.includes('\0')))) {+ throw new Error('Bundle environment requires permitted desktop keys and string values without NUL, or null to clear')}}return /** @type {Record<string, string|null>} */ (values)diff --git a/apps/desktop/scripts/bundle-env.test.mjs b/apps/desktop/scripts/bundle-env.test.mjsindex 79f37d7569d..d39869f4966 100644--- a/apps/desktop/scripts/bundle-env.test.mjs+++ b/apps/desktop/scripts/bundle-env.test.mjs@@ -43,9 +43,9 @@ test('explicit clears beat inherited homes and prevent Windows registry fallbacktest('applyBundleEnvironment replays the banner semantics for defaults, runtime overrides and clears', async () => {const root = mkdtempSync(join(tmpdir(), 'hermes-bundle-pure-'))- const defaults = { KEEP: 'default', MISSING: 'default', CLEARED: null, OVERRIDDEN: 'default', SUFFIX: 'baked' }+ const defaults = { HERMES_HOME: null, HERMES_DATA_DIR_SUFFIX: 'baked', HERMES_GUEST_ONBOARDING: '1' }const keys = Object.keys(defaults)- const base = { KEEP: 'x', CLEARED: 'runtime', OVERRIDDEN: 'runtime', SUFFIX: 'explicit' }+ const base = { HERMES_HOME: 'runtime', HERMES_DATA_DIR_SUFFIX: 'explicit' }try {// The bundled banner must produce the same effective environment the pure// function computes, so the smoke driver can predict the app's home from@@ -55,11 +55,13 @@ test('applyBundleEnvironment replays the banner semantics for defaults, runtimewriteFileSync(entry, `import {values} from './reader.mjs'; console.log(JSON.stringify(values));`, 'utf8')const outfile = join(root, 'bundle.mjs')await build({ entryPoints: [entry], bundle: true, platform: 'node', format: 'esm', outfile, banner: { js: environmentDefaultsBanner(JSON.stringify(defaults)) } })- const viaBanner = JSON.parse(execFileSync(process.execPath, [outfile], { env: { ...process.env, ...base }, encoding: 'utf8' }))+ const env = { ...process.env, ...base }+ delete env.HERMES_GUEST_ONBOARDING+ const viaBanner = JSON.parse(execFileSync(process.execPath, [outfile], { env, encoding: 'utf8' }))const viaFunction = Object.fromEntries(keys.map(key => [key, applyBundleEnvironment(base, defaults)[key]]))expect(viaFunction).toEqual(viaBanner)expect(viaFunction).toEqual({- KEEP: 'x', MISSING: 'default', CLEARED: '', OVERRIDDEN: 'runtime', SUFFIX: 'explicit',+ HERMES_HOME: '', HERMES_DATA_DIR_SUFFIX: 'explicit', HERMES_GUEST_ONBOARDING: '1',})} finally {rmSync(root, { recursive: true, force: true })@@ -68,7 +70,7 @@ test('applyBundleEnvironment replays the banner semantics for defaults, runtimetest('baked defaults precede imported module initialization and reach children without overriding explicit env', async () => {const root = mkdtempSync(join(tmpdir(), 'hermes-bundle-env-'))- const defaults = { HERMES_GUEST_ONBOARDING: '1', HERMES_DATA_DIR_SUFFIX: 'magic-test', LITERAL: 'a=b "q"\n$(no)', EMPTY: '' }+ const defaults = { HERMES_GUEST_ONBOARDING: '1', HERMES_DATA_DIR_SUFFIX: 'magic-test', HERMES_SHARED_AUTH_DIR: 'a=b "q"\n$(no)', HERMES_SKIP_INTRO: '' }const env = { ...process.env }for (const key of Object.keys(defaults)) {delete env[key]@@ -82,7 +84,8 @@ test('baked defaults precede imported module initialization and reach children wconst run = extra => JSON.parse(execFileSync(process.execPath, [outfile], { env: { ...env, ...extra }, encoding: 'utf8' }))expect(run({})).toEqual({ values: defaults, child: defaults.HERMES_DATA_DIR_SUFFIX })expect(run({ HERMES_DATA_DIR_SUFFIX: '-explicit', HERMES_GUEST_ONBOARDING: '' })).toEqual({ values: { ...defaults, HERMES_DATA_DIR_SUFFIX: '-explicit', HERMES_GUEST_ONBOARDING: '' }, child: '-explicit' })- for (const bad of ['[]', 'null', '{"BAD-NAME":"x"}', '{"NAME":1}', '{"NAME":"\\u0000"}']) {+ for (const bad of ['[]', 'null', '{"BAD-NAME":"x"}', '{"HERMES_HOME":1}', '{"HERMES_HOME":"\\u0000"}',+ '{"NODE_OPTIONS":"--require=evil"}', '{"PATH":null}', '{"HERMES_PYTHON":"/untrusted/python"}']) {expect(() => environmentDefaultsBanner(bad)).toThrow()}} finally {diff --git a/scripts/releases/bundle_env.py b/scripts/releases/bundle_env.pyindex 61cfe95c43d..e4805afeb38 100644--- a/scripts/releases/bundle_env.py+++ b/scripts/releases/bundle_env.py@@ -3,15 +3,20 @@ from __future__ import annotationsfrom collections.abc import Sequenceimport json-import re++# Keep this list aligned with the Desktop bundle banner and channel decoder.+_ALLOWED = frozenset({+ "HERMES_HOME", "HERMES_DATA_DIR_SUFFIX", "HERMES_DESKTOP_USER_DATA_DIR",+ "HERMES_SHARED_AUTH_DIR", "HERMES_GUEST_ONBOARDING", "HERMES_SKIP_INTRO",+})def validate(values: object) -> dict[str, str | None]:if not isinstance(values, dict):raise ValueError("Bundle environment must be a JSON object")for key, value in values.items():- if not isinstance(key, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key):- raise ValueError("Bundle environment names must be valid environment identifiers")+ if not isinstance(key, str) or key not in _ALLOWED:+ raise ValueError(f"Bundle environment name is not permitted: {key}")if value is not None and (not isinstance(value, str) or "\0" in value):raise ValueError(f"Bundle environment value for {key} must be a string without NUL or null")return valuesdiff --git a/tests/ci/test_channel_build_publication.py b/tests/ci/test_channel_build_publication.pyindex e10d76664f1..a5c5289c5e7 100644--- a/tests/ci/test_channel_build_publication.py+++ b/tests/ci/test_channel_build_publication.py@@ -28,7 +28,7 @@ def request_for(base):return {"schema": 1, "buildId": "a" * 32, "channel": "unknown-at-build-time", "sequence": 7,"repository": "fixture/repo", "commit": "b" * 40, "sourceVersion": "1.2.3","version": "0.0.7", "windowsVersion": "0.0.7.0", "identity": preview_identity("unknown-at-build-time", "c" * 16),- "bundleEnv": {"FEATURE": "different from the prior request"}, "publicBase": base}+ "bundleEnv": {"HERMES_GUEST_ONBOARDING": "different from the prior request"}, "publicBase": base}@pytest.fixture@@ -110,7 +110,7 @@ def test_channel_handoff_binds_full_request_and_feed_bytes(tmp_path, r2_server,filename = file["url"].rsplit("/", 1)[-1]assert file["size"] == (build / filename).stat().st_sizechanged = copy.deepcopy(request)- changed["bundleEnv"]["FEATURE"] = "other packaging input"+ changed["bundleEnv"]["HERMES_GUEST_ONBOARDING"] = "other packaging input"with pytest.raises(ValueError, match="identity"):handoff.fetch_channel_build(changed, ["win32-x64"], tmp_path / "wrong", public_base=request["publicBase"])assert not (tmp_path / "wrong").exists()diff --git a/tests/ci/test_commit_build_staging.py b/tests/ci/test_commit_build_staging.pyindex c7ffe125a4c..2862a86c716 100644--- a/tests/ci/test_commit_build_staging.py+++ b/tests/ci/test_commit_build_staging.py@@ -66,7 +66,8 @@ def test_failed_commit_summary_publishes_downloads_or_run_links(tmp_path, r2_serbase = f'http://127.0.0.1:{r2_server.server_port}/hermes-releases'summary = tmp_path / 'summary.md'jobs = _workflow()['jobs']- bundle_env = {'HERMES_HOME': None, 'EMPTY': '', 'LABEL': '<script>\n"café" & value</script>'}+ bundle_env = {'HERMES_HOME': None, 'HERMES_SKIP_INTRO': '',+ 'HERMES_SHARED_AUTH_DIR': '<script>\n"café" & value</script>'}env = dict(HERMES_BUILD_COMMIT=sha, HERMES_PAYLOAD_TAG='', RELEASE_COMMIT=sha,GITHUB_REPOSITORY='fixture-owner/fixture-repo',HERMES_BUNDLE_ENV_JSON=json.dumps(bundle_env), CI_SECRET='must-not-appear',@@ -91,8 +92,8 @@ def test_failed_commit_summary_publishes_downloads_or_run_links(tmp_path, r2_serpage = response.read().decode()assert f'href="https://github.com/fixture-owner/fixture-repo/commit/{sha}"' in pageassert 'Bundle environment' in page and 'HERMES_HOME' in page and 'Unset' in page- assert '<code>EMPTY</code></td><td><code>""</code>' in page- assert html.escape(json.dumps(bundle_env['LABEL'], ensure_ascii=False)) in page+ assert '<code>HERMES_SKIP_INTRO</code></td><td><code>""</code>' in page+ assert html.escape(json.dumps(bundle_env['HERMES_SHARED_AUTH_DIR'], ensure_ascii=False)) in pageassert '<script>' not in page and 'must-not-appear' not in page and 'CI_SECRET' not in pagelinks = re.findall(r'\]\((https?://[^)]+)\)', text)download_links = [url for url in links if url.endswith('.msix')]diff --git a/tests/scripts/test_release_build_commit.py b/tests/scripts/test_release_build_commit.pyindex a2cac370fd2..3d5330aa280 100644--- a/tests/scripts/test_release_build_commit.py+++ b/tests/scripts/test_release_build_commit.py@@ -148,14 +148,15 @@ def test_commit_bundle_environment_is_literal_and_validated(fixture_repo):repo, _, invoke = fixture_repotip = git(repo, 'rev-parse', 'HEAD')values = {'HERMES_GUEST_ONBOARDING': '1', 'HERMES_DATA_DIR_SUFFIX': 'magic-test',- 'EMPTY': '', 'LITERAL': 'a=b "quote"\n$(not-a-command)'}+ 'HERMES_SKIP_INTRO': '', 'HERMES_SHARED_AUTH_DIR': 'a=b "quote"\n$(not-a-command)'}flags = [part for key, value in values.items() for part in ('--bundle-env', f'{key}={value}')]result, calls = invoke('--build-commit', tip, '--publish', *flags)assert result.returncode == 0, result.stderrdispatch = next(call for call in calls if call[1:3] == ['workflow', 'run'])assert json.loads(next(field.split('=', 1)[1] for field in dispatch if field.startswith('bundle_env='))) == valuesfor invalid in (['--bundle-env', 'MISSING'], ['--bundle-env', 'BAD-NAME=x'],- ['--bundle-env', 'DUP=x', '--bundle-env', 'DUP=y']):+ ['--bundle-env', 'NODE_OPTIONS=--require=evil'], ['--bundle-unset', 'PATH'],+ ['--bundle-env', 'HERMES_HOME=x', '--bundle-env', 'HERMES_HOME=y']):result, calls = invoke('--build-commit', tip, '--publish', *invalid)assert result.returncode != 0 and not callsresult, calls = invoke('--bundle-env', 'NAME=value')diff --git a/tests/scripts/test_release_channel_build.py b/tests/scripts/test_release_channel_build.pyindex 2f58aeb9130..c3ce99e8034 100644--- a/tests/scripts/test_release_channel_build.py+++ b/tests/scripts/test_release_channel_build.py@@ -31,7 +31,7 @@ def test_dispatch_names_channel_and_binds_to_pushed_source(source):calls = []options = dict(name="custom-branch", revision="main", remote="origin", repo=source,repository="example/hermes-agent", default_branch="main",- dispatch=calls.append, bundle_env={"FEATURE": "a"})+ dispatch=calls.append, bundle_env={"HERMES_GUEST_ONBOARDING": "1"})dry = prepare_build(**options)assert dry["commit"] == git(source, "rev-parse", "HEAD")assert dry["sourceVersion"] == "1.2.3"diff --git a/tests/scripts/test_release_channels.py b/tests/scripts/test_release_channels.pyindex b0fce598616..4a7def5ddc7 100644--- a/tests/scripts/test_release_channels.py+++ b/tests/scripts/test_release_channels.py@@ -109,8 +109,8 @@ def test_unknown_channel_created_over_http_retains_identity_and_immutable_requesreader.resolve("not-registered-in-code")record = pub.create("not-registered-in-code")assert reader.resolve(record["name"]).manifest is None- one = pub.allocate(record["name"], "a" * 40, "1.2.3", {"FEATURE": "one"})- two = pub.allocate(record["name"], "a" * 40, "1.2.3", {"FEATURE": "two"})+ one = pub.allocate(record["name"], "a" * 40, "1.2.3", {"HERMES_GUEST_ONBOARDING": "1"})+ two = pub.allocate(record["name"], "a" * 40, "1.2.3", {"HERMES_GUEST_ONBOARDING": "0"})assert one["identity"] == two["identity"] == record["identity"]assert one["buildId"] != two["buildId"]assert one["sequence"] < two["sequence"]