The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): a group-writable private-group profile home attaches without being chmodded back
Teknium62a4946e84a6
diff --git a/apps/desktop/electron/local-gateway-python.test.ts b/apps/desktop/electron/local-gateway-python.test.tsindex 7086981437c..b59a431d6cd 100644--- a/apps/desktop/electron/local-gateway-python.test.ts+++ b/apps/desktop/electron/local-gateway-python.test.ts@@ -46,6 +46,38 @@ test.skipIf(process.platform === 'win32')('Python ticket bridge pins profile, owawait expect(mintGatewayTicketWithPython(backend, cwd, endpoint, 'interactive')).rejects.toThrow('Gateway ticket')}+ // The profile home gets Python's full home policy: a private-group 0775 home mints, the same+ // home with a named-user ACL (group bits become the mask) is refused with its reason.+ // The expected verdict is Python's own home_mode_unsafe for this host's group (a CI runner's+ // primary group need not be private), so this is a parity check, not a host assumption.+ override = {}+ const { execFileSync } = await import('node:child_process')++ const unsafe = () => execFileSync(python, ['-c', 'import sys; from pathlib import Path; '+ + 'from hermes_cli.gateway_runtime_discovery import home_mode_unsafe as u; p = Path(sys.argv[1]); '+ + 'print(int(u(p.lstat(), p)))', home], { env: { ...process.env, PYTHONPATH: root }, encoding: 'utf8' }).trim() === '1'++ const expectVerdict = async () => {+ const mint = mintGatewayTicketWithPython(backend, cwd, endpoint, 'interactive')++ await (unsafe() ? expect(mint).rejects.toMatchObject({ reason: 'unsafe_control_permissions' })+ : expect(mint).resolves.toBe('private-grant'))+ }++ await fs.chmod(home, 0o775)+ await expectVerdict()+ let acl = false++ try { execFileSync('setfacl', ['-m', 'u:nobody:rwx', home]); acl = true } catch { acl = false }++ if (acl) {+ expect(unsafe(), 'a named-user ACL makes the group bits a mask').toBe(true)+ await expectVerdict()+ execFileSync('setfacl', ['-b', home])+ }++ await fs.chmod(home, 0o700)+// A served secondary carries the multiplexer's control_home: the ticket is minted by THAT// home's socket (the profile home has none), still bound to the secondary's identity.override = {}diff --git a/apps/desktop/electron/local-gateway-python.ts b/apps/desktop/electron/local-gateway-python.tsindex 8e09a902bef..a3d1485791d 100644--- a/apps/desktop/electron/local-gateway-python.ts+++ b/apps/desktop/electron/local-gateway-python.ts@@ -12,17 +12,26 @@ interface TicketEndpoint {// Reuse the runtime's SID-validated, deadline-bounded pipe client. No Node pipe// connection may bypass GetNamedPipeServerProcessId / token-owner validation.+// POSIX: the profile home gets the full home policy (private-group + ACL proof that Node cannot+// make); the control home is checked again by connect_private. A refusal reports its reason.const TICKET_SCRIPT = `-import json, sys+import json, os, sysfrom pathlib import Pathfrom types import SimpleNamespacefrom hermes_cli.gateway_client import _session_ticket+from hermes_cli.gateway_runtime_discovery import DiscoveryError, _private_noderequest = json.loads(sys.stdin.buffer.read(65537))endpoint = SimpleNamespace(**{'control_home': None, **request['endpoint']})home = Path(endpoint.profile_id)if str(home.resolve()) != endpoint.profile_id or endpoint.runtime_protocol != 1:raise ValueError('invalid ticket endpoint')-ticket = _session_ticket(home, endpoint, purpose=request['purpose'])+try:+ if os.name != 'nt':+ _private_node(home, kind='directory', home=True)+ ticket = _session_ticket(home, endpoint, purpose=request['purpose'])+except DiscoveryError as exc:+ sys.stdout.write(json.dumps({'error': exc.reason}))+ sys.exit(3)sys.stdout.write(json.dumps({'ticket': ticket}))`@@ -41,7 +50,14 @@ export function mintGatewayTicketWithPython(}))let stdout = ''- const fail = () => reject(new Error('Gateway ticket bootstrap failed'))++ const fail = () => {+ let reason: unknown++ try { reason = JSON.parse(stdout).error } catch { reason = undefined }+ reject(Object.assign(new Error('Gateway ticket bootstrap failed'), typeof reason === 'string' ? { reason } : {}))+ }+const timer = setTimeout(() => { child.kill(); fail() }, 10_000)child.on('error', fail)child.stdin.on('error', fail)diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.tsindex 0a47115ccf2..9c114f27734 100644--- a/apps/desktop/electron/local-gateway.test.ts+++ b/apps/desktop/electron/local-gateway.test.ts@@ -380,8 +380,9 @@ test.skipIf(process.platform === 'win32')('a supported home mode mints its tickeexpect(await mintLocalGatewayTicket(endpoint)).toBe('grant')}- for (const mode of [0o757, 0o703]) {+ for (const mode of [0o757, 0o703, 0o775]) {await fs.chmod(home, mode)+ // 0775 with no Python client configured: group-write Node cannot prove private is refused.await expect(mintLocalGatewayTicket(endpoint)).rejects.toThrow('Unsafe gateway control path')}} finally {@@ -413,3 +414,44 @@ test('main issues native-gateway REST calls only through the shared descriptor texpect(source.slice(transport, transportEnd)).toContain('headers: descriptor.headers')expect(outside.match(/fetchJson\([^)]*\{[^}]*gatewayDescriptor\b/g) ?? []).toEqual([])})++// A group-writable home (umask-002 user-private-group default) is decided by the runtime's own+// home policy, which Node cannot evaluate: the mint goes through the Python ticket client, and a+// refusal there names the fix instead of failing as a stale gateway.+test.skipIf(process.platform === 'win32')('a group-writable home mints through the Python policy; a shared group names the fix', async () => {+ const fs = await import('node:fs/promises')+ const os = await import('node:os')+ const path = await import('node:path')+ const { configurePythonGatewayTicketClient, isStaleLocalGatewayError, mintLocalGatewayTicket } = await import('./local-gateway')+ const home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-group-home-')))+ const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }+ const calls: string[] = []+ let verdict: 'grant' | 'shared' = 'grant'++ configurePythonGatewayTicketClient(async (ep, purpose) => {+ calls.push(`${ep.profile_id}:${purpose}`)++ if (verdict === 'shared') {throw Object.assign(new Error('Gateway ticket bootstrap failed'), { reason: 'unsafe_control_permissions' })}++ return 'python-grant'+ })++ try {+ await fs.chmod(home, 0o775)+ expect(await mintLocalGatewayTicket(endpoint, 'native-http')).toBe('python-grant')+ expect(calls).toEqual([`${home}:native-http`])++ verdict = 'shared'+ const failure = await mintLocalGatewayTicket(endpoint).catch(error => error)+ expect(failure.message).toBe(`Profile home is writable by a group other accounts share: run chmod g-w '${home}'`)+ expect(isStaleLocalGatewayError(failure)).toBe(false)++ await fs.chmod(home, 0o757)+ await expect(mintLocalGatewayTicket(endpoint)).rejects.toThrow('Unsafe gateway control path')+ expect(calls).toHaveLength(2)+ } finally {+ configurePythonGatewayTicketClient(undefined as never)+ await fs.chmod(home, 0o700)+ await fs.rm(home, { recursive: true, force: true })+ }+})diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.tsindex ed5ef90d99e..9683a327390 100644--- a/apps/desktop/electron/local-gateway.ts+++ b/apps/desktop/electron/local-gateway.ts@@ -247,14 +247,17 @@ export function createLocalGatewayDials() {// A profile home keeps the operator's mode (Python `home_mode_unsafe`: HERMES_HOME_MODE 0750/0701,// a 0755 home): read/search bits grant nothing against the 0600 socket; only write by another user-// could swap it. Python admits group-write solely for a proven-private group without an ACL, which-// Node cannot establish (no xattrs/NSS), so it is refused here, as Python treats the unprovable.-// The socket, pointer and fallback directory stay owner-only.-async function privateNode(file: string, kind: 'directory' | 'socket' | 'file' | 'home') {+// could swap it. Group-write is safe only for a proven-private group without an ACL, which Node+// cannot establish (no xattrs/NSS): a group-writable home returns true so the caller hands the+// ticket to the Python bridge, which applies that exact policy. The socket, pointer and fallback+// directory stay owner-only.+async function privateNode(file: string, kind: 'directory' | 'socket' | 'file' | 'home'): Promise<boolean> {const node = await fs.lstat(file)const valid = { directory: node.isDirectory(), home: node.isDirectory(), socket: node.isSocket(), file: node.isFile() }[kind]- if (!valid || node.uid !== process.getuid?.() || (node.mode & (kind === 'home' ? 0o022 : 0o077))) {throw new Error('Unsafe gateway control path')}+ if (!valid || node.uid !== process.getuid?.() || (node.mode & (kind === 'home' ? 0o002 : 0o077))) {throw new Error('Unsafe gateway control path')}++ return kind === 'home' && Boolean(node.mode & 0o020)}/** The endpoint a `?profile=<name>` request is scoped to on a shared host descriptor: the same@@ -284,10 +287,25 @@ export async function nativeGatewayHttpHeaders(descriptor: { gatewayEndpoint: Gareturn { 'X-Hermes-Gateway-Ticket': await mintLocalGatewayTicket(routedGatewayEndpoint(descriptor.gatewayEndpoint, url, launchHome), 'native-http') }}-let windowsTicketClient: ((endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http') => Promise<string>) | undefined+// The installed runtime's own ticket client: every Windows mint (SID-validated pipe), and a POSIX+// home whose group-write only Python can prove private.+let pythonTicketClient: ((endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http') => Promise<string>) | undefined-export function configureWindowsGatewayTicketClient(client: NonNullable<typeof windowsTicketClient>) {- windowsTicketClient = client+export function configurePythonGatewayTicketClient(client: NonNullable<typeof pythonTicketClient>) {+ pythonTicketClient = client+}++async function mintGroupWritableHome(endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http', homes: string[]) {+ if (!pythonTicketClient) {throw new Error('Unsafe gateway control path')}++ try {+ return await pythonTicketClient(endpoint, purpose)+ } catch (error) {+ if ((error as { reason?: string })?.reason !== 'unsafe_control_permissions') {throw error}+ const quoted = homes.map(home => `'${home.replace(/'/g, `'\\''`)}'`).join(' ')++ throw new Error(`Profile home is writable by a group other accounts share: run chmod g-w ${quoted}`)+ }}function isMissingNodeError(error: unknown): boolean {@@ -318,9 +336,9 @@ async function resolveControlSocket(home: string): Promise<string> {export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http' = 'interactive'): Promise<string> {if (process.platform === 'win32') {- if (!windowsTicketClient) {throw new Error('Gateway ticket client is not configured')}+ if (!pythonTicketClient) {throw new Error('Gateway ticket client is not configured')}- return windowsTicketClient(endpoint, purpose)+ return pythonTicketClient(endpoint, purpose)}const home = endpoint.profile_id@@ -329,11 +347,16 @@ export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint, purpose:// hermes_cli.gateway_runtime.control_home_for.const controlHome = endpoint.control_home || home+ const groupWritable: string[] = []+for (const dir of new Set([home, controlHome])) {if (await fs.realpath(dir) !== dir) {throw new Error('Noncanonical gateway profile')}- await privateNode(dir, 'home')++ if (await privateNode(dir, 'home')) {groupWritable.push(dir)}}+ if (groupWritable.length) {return mintGroupWritableHome(endpoint, purpose, groupWritable)}+let socketPath: stringtry { socketPath = await resolveControlSocket(controlHome) } catch (error) {diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 55ce50d9373..954f1fe21d7 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -1,10 +1,10 @@import { type ChildProcess, execFileSync, spawn } from 'node:child_process'import type { GatewayEndpoint } from './local-gateway'-import { configureWindowsGatewayTicketClient, createLocalGatewayDials, createStaleGatewayRestarter, ensureLocalGateway, gatewayOwnerProfile, mintLocalGatewayTicket, nativeGatewayHttpHeaders, redialLocalGateway, routedGatewayEndpoint, runGatewayEnsure } from './local-gateway'+import { configurePythonGatewayTicketClient, createLocalGatewayDials, createStaleGatewayRestarter, ensureLocalGateway, gatewayOwnerProfile, mintLocalGatewayTicket, nativeGatewayHttpHeaders, redialLocalGateway, routedGatewayEndpoint, runGatewayEnsure } from './local-gateway'import { mintGatewayTicketWithPython } from './local-gateway-python'const localGatewayDials = createLocalGatewayDials()-configureWindowsGatewayTicketClient(async (endpoint, purpose) => {+configurePythonGatewayTicketClient(async (endpoint, purpose) => {const backend = await ensureRuntime(await resolveHermesBackend([]), () => undefined)if (backend.kind !== 'python' || backend.shell) {diff --git a/evals/desktop_gateway_ticket_native/electron-main-multiplex.ts b/evals/desktop_gateway_ticket_native/electron-main-multiplex.tsindex 8dca88c4ab9..5335e4f1e8e 100644--- a/evals/desktop_gateway_ticket_native/electron-main-multiplex.ts+++ b/evals/desktop_gateway_ticket_native/electron-main-multiplex.ts@@ -2,7 +2,7 @@ import { app } from 'electron'import assert from 'node:assert/strict'import fs from 'node:fs'import WebSocket from 'ws'-import { configureWindowsGatewayTicketClient, ensureLocalGateway, mintLocalGatewayTicket, nativeGatewayHttpHeaders, runGatewayEnsure } from '../../apps/desktop/electron/local-gateway'+import { configurePythonGatewayTicketClient, ensureLocalGateway, mintLocalGatewayTicket, nativeGatewayHttpHeaders, runGatewayEnsure } from '../../apps/desktop/electron/local-gateway'import { mintGatewayTicketWithPython } from '../../apps/desktop/electron/local-gateway-python'/**@@ -56,7 +56,7 @@ async function sidebarPatch(connection: any, profile: string, sid: string, payloasync function main() {assert.ok(process.versions.electron, 'Must execute inside real Electron, not Node')assert.equal(process.type, 'browser', 'Must execute in Electron main')- configureWindowsGatewayTicketClient((endpoint, purpose) => mintGatewayTicketWithPython({ command: input.python, env: { PYTHONPATH: input.repo } }, input.repo, endpoint, purpose))+ configurePythonGatewayTicketClient((endpoint, purpose) => mintGatewayTicketWithPython({ command: input.python, env: { PYTHONPATH: input.repo } }, input.repo, endpoint, purpose))// 1. Desktop-side discovery for every profile: same instance, secondaries via the root's control socket.const connections: Record<string, any> = {}diff --git a/evals/desktop_gateway_ticket_native/electron-main.ts b/evals/desktop_gateway_ticket_native/electron-main.tsindex 68e679e50bf..5d8a8715a29 100644--- a/evals/desktop_gateway_ticket_native/electron-main.ts+++ b/evals/desktop_gateway_ticket_native/electron-main.ts@@ -2,7 +2,7 @@ import { app } from 'electron'import assert from 'node:assert/strict'import fs from 'node:fs'import WebSocket from 'ws'-import { configureWindowsGatewayTicketClient, mintLocalGatewayTicket, nativeGatewayHttpHeaders } from '../../apps/desktop/electron/local-gateway'+import { configurePythonGatewayTicketClient, mintLocalGatewayTicket, nativeGatewayHttpHeaders } from '../../apps/desktop/electron/local-gateway'import { mintGatewayTicketWithPython } from '../../apps/desktop/electron/local-gateway-python'const input = JSON.parse(fs.readFileSync(process.env.NATIVE_TICKET_INPUT!, 'utf8'))@@ -50,7 +50,7 @@ async function describe(ticket: string, replay = false) {async function main() {assert.ok(process.versions.electron, 'Must execute inside real Electron, not Node')assert.equal(process.type, 'browser', 'Must execute in Electron main')- configureWindowsGatewayTicketClient((endpoint, purpose) =>+ configurePythonGatewayTicketClient((endpoint, purpose) =>mintGatewayTicketWithPython({ command: input.python, env: { PYTHONPATH: input.repo } }, input.repo, endpoint, purpose))const descriptor = { gatewayEndpoint: input.endpoint, baseUrl: input.endpoint.api_origin }const configUrl = descriptor.baseUrl + '/api/config'