mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-25 05:07:05 +00:00
fix(cli): keep LAN access for sessions that outlive their runner on macOS (#2328)
* fix(cli): keep LAN access for sessions that outlive their runner on macOS macOS attributes Local Network decisions to a process's responsible process, which a child inherits from its spawner. Sessions spawned by a runner that launchd started (directly, or through the npm launcher bin/hapi.cjs) inherit the runner's or the launcher's pid. Once that process exits (upgrade, version handoff) while the sessions are kept, every new process in their trees that connects to a LAN address fails with EHOSTUNREACH. When the spawner may hand its responsibility on, detached spawnHappyCLI children (sessions, runner handoff, runner start) are started with HAPI_DISCLAIM_RESPONSIBILITY=<spawner pid>. In a direct child of that pid, the entry hook removes the variable from the libc environment and re-executes process.execPath in place via posix_spawn(POSIX_SPAWN_SETEXEC) with responsibility_spawnattrs_setdisclaim, so the child becomes its own responsible process. The pid, stdio, process group, cwd and the rest of the environment are unchanged, so the runner's ChildProcess tracking keeps working. The spawner may hand its responsibility on when it is its own responsible process, or when its responsible process is its direct parent, is the npm launcher (which now passes HAPI_LAUNCHER_PID) and is itself its own responsible process. A spawner started from Terminal or over SSH keeps the inherited responsibility and with it the implicit LAN allowance macOS grants there. The lookup uses responsibility_get_pid_responsible_for_pid through bun:ffi; when it is unavailable the spawn is not disclaimed and this is logged once. Binaries without the hook ignore the variable, and a copy that leaks into a rolled-back tree is ignored because its parent is not the spawner. The private disclaim symbol may disappear: the hook then execs without it, and any other failure continues in-process; the reason is written to the hapi log. * fix(cli): print --help and --version when HAPI_HOME cannot be created The entry point imported runtime/responsibility to read the npm launcher's pid. That module imports the logger, whose configuration creates HAPI_HOME, so `hapi --help` and `hapi --version` failed before printing when that directory could not be created. Move the launcher pid into a dependency-free module, read it from there, and make the optional disclaim fallback note best effort. Add an entry point test that runs both flags with an unwritable HAPI_HOME.
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
// Runs the real entry hook, then reports. With `--missing-symbol` the disclaim
|
||||
// symbol lookup is pointed at a name that does not exist (fail-open check).
|
||||
import { handleDisclaimExecEntry, takeDisclaimFallbackNote } from '../disclaimExec'
|
||||
import { loadDarwinSpawnExec } from '../darwinSpawnExec'
|
||||
import { report } from './report'
|
||||
|
||||
const missingSymbol = process.argv.includes('--missing-symbol')
|
||||
await handleDisclaimExecEntry(missingSymbol
|
||||
? { loadNative: async () => () => loadDarwinSpawnExec({ disclaimSymbol: 'hapi_missing_symbol_for_test' }) }
|
||||
: {})
|
||||
report({ fallbackNote: takeDisclaimFallbackNote() })
|
||||
@@ -0,0 +1,23 @@
|
||||
// Prints this process's identity for the darwin re-exec tests.
|
||||
import { dlopen, FFIType } from 'bun:ffi'
|
||||
import { canDisclaimForChildren } from '../responsibility'
|
||||
import { DISCLAIM_RESPONSIBILITY_ENV } from '../disclaimExec'
|
||||
|
||||
const { symbols } = dlopen('/usr/lib/libSystem.B.dylib', {
|
||||
responsibility_get_pid_responsible_for_pid: { args: [FFIType.i32], returns: FFIType.i32 },
|
||||
getpgrp: { args: [], returns: FFIType.i32 }
|
||||
})
|
||||
|
||||
export function report(extra: Record<string, unknown> = {}): void {
|
||||
console.log(JSON.stringify({
|
||||
pid: process.pid,
|
||||
responsible: symbols.responsibility_get_pid_responsible_for_pid(process.pid),
|
||||
ownResponsible: canDisclaimForChildren(),
|
||||
pgid: symbols.getpgrp(),
|
||||
cwd: process.cwd(),
|
||||
probe: process.env.HAPI_DISCLAIM_TEST_PROBE ?? null,
|
||||
request: process.env[DISCLAIM_RESPONSIBILITY_ENV] ?? null,
|
||||
args: process.argv.slice(2),
|
||||
...extra
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Stand-in for a binary without the entry hook (e.g. an older release).
|
||||
import { report } from './report'
|
||||
|
||||
report()
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* bun:ffi binding for an in-place `posix_spawn(POSIX_SPAWN_SETEXEC)` on macOS.
|
||||
*
|
||||
* Kept separate from disclaimExec.ts so `bun:ffi` is only loaded when a disclaim
|
||||
* was actually requested (and never under Node/vitest).
|
||||
*/
|
||||
import { dlopen, FFIType, ptr, read, type Pointer } from 'bun:ffi'
|
||||
import type { SpawnExecNative } from './disclaimExec'
|
||||
|
||||
const LIBSYSTEM = '/usr/lib/libSystem.B.dylib'
|
||||
export const DISCLAIM_SYMBOL = 'responsibility_spawnattrs_setdisclaim'
|
||||
|
||||
const POSIX_SPAWN_SETSIGDEF = 0x04
|
||||
const POSIX_SPAWN_SETSIGMASK = 0x08
|
||||
const POSIX_SPAWN_SETEXEC = 0x40
|
||||
const SIGKILL = 9
|
||||
const SIGSTOP = 17
|
||||
|
||||
// Buffers whose addresses are handed to native code. Bun's FFI requires them to
|
||||
// stay reachable while native code may read them; exec only returns on failure.
|
||||
let pinned: unknown[] = []
|
||||
|
||||
function cString(value: string): Buffer {
|
||||
return Buffer.from(`${value}\0`, 'utf8')
|
||||
}
|
||||
|
||||
export function loadDarwinSpawnExec(options: { disclaimSymbol?: string } = {}): SpawnExecNative {
|
||||
const core = dlopen(LIBSYSTEM, {
|
||||
posix_spawnattr_init: { args: [FFIType.ptr], returns: FFIType.i32 },
|
||||
posix_spawnattr_destroy: { args: [FFIType.ptr], returns: FFIType.i32 },
|
||||
posix_spawnattr_setflags: { args: [FFIType.ptr, FFIType.i16], returns: FFIType.i32 },
|
||||
posix_spawnattr_setsigmask: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.i32 },
|
||||
posix_spawnattr_setsigdefault: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.i32 },
|
||||
posix_spawn: {
|
||||
args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr],
|
||||
returns: FFIType.i32
|
||||
},
|
||||
_NSGetEnviron: { args: [], returns: FFIType.ptr },
|
||||
getenv: { args: [FFIType.ptr], returns: FFIType.ptr },
|
||||
setenv: { args: [FFIType.ptr, FFIType.ptr, FFIType.i32], returns: FFIType.i32 },
|
||||
unsetenv: { args: [FFIType.ptr], returns: FFIType.i32 }
|
||||
}).symbols
|
||||
|
||||
// Private libSystem symbol: resolve it on its own so its absence only disables
|
||||
// the disclaim, not the exec.
|
||||
const disclaimSymbol = options.disclaimSymbol ?? DISCLAIM_SYMBOL
|
||||
let setDisclaim: ((attr: BigUint64Array, disclaim: number) => number) | null = null
|
||||
try {
|
||||
const optional = dlopen(LIBSYSTEM, {
|
||||
[disclaimSymbol]: { args: [FFIType.ptr, FFIType.i32], returns: FFIType.i32 }
|
||||
}).symbols as Record<string, (attr: BigUint64Array, disclaim: number) => number>
|
||||
setDisclaim = optional[disclaimSymbol] ?? null
|
||||
} catch {
|
||||
setDisclaim = null
|
||||
}
|
||||
|
||||
return {
|
||||
canDisclaim: setDisclaim !== null,
|
||||
// The libc environment is what the exec passes on; process.env writes do not reach it.
|
||||
unsetenv(name: string): boolean {
|
||||
const key = cString(name)
|
||||
core.unsetenv(key)
|
||||
return core.getenv(key) === null
|
||||
},
|
||||
setenv(name: string, value: string): void {
|
||||
core.setenv(cString(name), cString(value), 1)
|
||||
},
|
||||
exec(path: string, argv: readonly string[], disclaim: boolean): number {
|
||||
// posix_spawnattr_t is an opaque pointer on Darwin.
|
||||
const attr = new BigUint64Array(1)
|
||||
let rc = core.posix_spawnattr_init(attr)
|
||||
if (rc !== 0) {
|
||||
return rc
|
||||
}
|
||||
try {
|
||||
if (disclaim) {
|
||||
if (!setDisclaim) {
|
||||
return -1
|
||||
}
|
||||
rc = setDisclaim(attr, 1)
|
||||
if (rc !== 0) {
|
||||
return rc
|
||||
}
|
||||
}
|
||||
// Reset every catchable signal to its default action and clear the
|
||||
// mask, so the new image does not inherit the dispositions this Bun
|
||||
// runtime installed for itself.
|
||||
const emptyMask = new Uint32Array([0])
|
||||
const allCatchable = new Uint32Array([0xffffffff & ~((1 << (SIGKILL - 1)) | (1 << (SIGSTOP - 1)))])
|
||||
rc = core.posix_spawnattr_setsigmask(attr, emptyMask)
|
||||
|| core.posix_spawnattr_setsigdefault(attr, allCatchable)
|
||||
|| core.posix_spawnattr_setflags(attr, POSIX_SPAWN_SETEXEC | POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK)
|
||||
if (rc !== 0) {
|
||||
return rc
|
||||
}
|
||||
|
||||
const pathBuffer = cString(path)
|
||||
const strings = argv.map(cString)
|
||||
const argvArray = new BigUint64Array(strings.length + 1)
|
||||
strings.forEach((value, index) => {
|
||||
argvArray[index] = BigInt(ptr(value))
|
||||
})
|
||||
const environPointer = core._NSGetEnviron()
|
||||
if (!environPointer) {
|
||||
return -1
|
||||
}
|
||||
const environ = read.ptr(environPointer, 0) as Pointer
|
||||
pinned = [pathBuffer, strings, argvArray, attr, emptyMask, allCatchable]
|
||||
// Returns only on failure; on success this process image is replaced.
|
||||
return core.posix_spawn(null, pathBuffer, null, attr, argvArray, environ)
|
||||
} finally {
|
||||
pinned = []
|
||||
core.posix_spawnattr_destroy(attr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* Real re-exec through bun:ffi on macOS, in dev mode (bun runs the fixtures):
|
||||
* same pid, own responsible process, stdio pipe, process group, env and cwd
|
||||
* preserved, fail-open without the private symbol, a request addressed to
|
||||
* another process ignored, and a binary without the hook ignoring the request.
|
||||
* The compiled binary needs a separate smoke test on a Mac. LAN access itself
|
||||
* needs a LAN peer and is not exercised here. Needs HAPI_BUN_EXEC from the test
|
||||
* setup.
|
||||
*/
|
||||
import { spawn } from 'node:child_process'
|
||||
import { mkdtempSync, realpathSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { afterAll, describe, expect, it } from 'vitest'
|
||||
import { DISCLAIM_RESPONSIBILITY_ENV } from './disclaimExec'
|
||||
|
||||
const reexecEntry = resolve(__dirname, '__fixtures__/reexecEntry.ts')
|
||||
const withoutHook = resolve(__dirname, '__fixtures__/reportResponsibility.ts')
|
||||
|
||||
interface RunResult {
|
||||
spawnedPid: number | undefined
|
||||
code: number | null
|
||||
stdout: string
|
||||
stderr: string
|
||||
}
|
||||
|
||||
// The spawned bun process is a direct child of this test process.
|
||||
function run(args: string[], cwd: string, request: boolean | string): Promise<RunResult> {
|
||||
const env: NodeJS.ProcessEnv = { ...process.env, HAPI_DISCLAIM_TEST_PROBE: 'kept as is' }
|
||||
if (request !== false) {
|
||||
env[DISCLAIM_RESPONSIBILITY_ENV] = request === true ? String(process.pid) : request
|
||||
} else {
|
||||
delete env[DISCLAIM_RESPONSIBILITY_ENV]
|
||||
}
|
||||
return new Promise((resolvePromise, reject) => {
|
||||
const child = spawn(process.env.HAPI_BUN_EXEC!, args, {
|
||||
cwd,
|
||||
detached: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env
|
||||
})
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
child.stdout.on('data', (chunk) => { stdout += chunk })
|
||||
child.stderr.on('data', (chunk) => { stderr += chunk })
|
||||
child.on('error', reject)
|
||||
child.on('exit', (code) => resolvePromise({ spawnedPid: child.pid, code, stdout, stderr }))
|
||||
})
|
||||
}
|
||||
|
||||
describe.runIf(process.platform === 'darwin')('macOS responsibility re-exec', () => {
|
||||
const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'hapi-disclaim-')))
|
||||
afterAll(() => rmSync(cwd, { recursive: true, force: true }))
|
||||
|
||||
it('re-executes in place as its own responsible process, keeping pid, pipe, group, env and cwd', async () => {
|
||||
const result = await run([reexecEntry, 'a b', 'c'], cwd, true)
|
||||
|
||||
expect(result.code, result.stderr).toBe(0)
|
||||
expect(result.stderr).toBe('')
|
||||
const report = JSON.parse(result.stdout)
|
||||
expect(report.pid).toBe(result.spawnedPid)
|
||||
expect(report.responsible).toBe(report.pid)
|
||||
expect(report.ownResponsible).toBe(true)
|
||||
expect(report.pgid).toBe(report.pid)
|
||||
expect(report.cwd).toBe(cwd)
|
||||
expect(report.probe).toBe('kept as is')
|
||||
expect(report.request).toBeNull()
|
||||
expect(report.fallbackNote).toBeNull()
|
||||
expect(report.args).toEqual(['a b', 'c'])
|
||||
})
|
||||
|
||||
it('without a request the child keeps the spawner as responsible process', async () => {
|
||||
const result = await run([reexecEntry], cwd, false)
|
||||
|
||||
expect(result.code, result.stderr).toBe(0)
|
||||
const report = JSON.parse(result.stdout)
|
||||
expect(report.responsible).not.toBe(report.pid)
|
||||
expect(report.ownResponsible).toBe(false)
|
||||
})
|
||||
|
||||
it('ignores a request addressed to another process', async () => {
|
||||
const result = await run([reexecEntry], cwd, String(process.pid + 1))
|
||||
|
||||
expect(result.code, result.stderr).toBe(0)
|
||||
expect(result.stderr).toBe('')
|
||||
const report = JSON.parse(result.stdout)
|
||||
expect(report.responsible).not.toBe(report.pid)
|
||||
expect(report.request).toBeNull()
|
||||
})
|
||||
|
||||
it('fails open to a plain exec when the disclaim symbol is missing, and leaves a note for the log', async () => {
|
||||
const result = await run([reexecEntry, '--missing-symbol'], cwd, true)
|
||||
|
||||
expect(result.code, result.stderr).toBe(0)
|
||||
expect(result.stderr.trim().split('\n')).toEqual([
|
||||
'[hapi] macOS responsibility disclaim: disclaim symbol not found; executing without it'
|
||||
])
|
||||
const report = JSON.parse(result.stdout)
|
||||
expect(report.pid).toBe(result.spawnedPid)
|
||||
expect(report.responsible).not.toBe(report.pid)
|
||||
expect(report.request).toBeNull()
|
||||
expect(report.fallbackNote).toBe('disclaim symbol not found')
|
||||
expect(report.probe).toBe('kept as is')
|
||||
})
|
||||
|
||||
it('a binary without the hook ignores the request and runs normally (rollback)', async () => {
|
||||
const result = await run([withoutHook, 'x'], cwd, true)
|
||||
|
||||
expect(result.code, result.stderr).toBe(0)
|
||||
const report = JSON.parse(result.stdout)
|
||||
expect(report.pid).toBe(result.spawnedPid)
|
||||
expect(report.responsible).not.toBe(report.pid)
|
||||
expect(report.args).toEqual(['x'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,227 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
DISCLAIM_FALLBACK_ENV,
|
||||
DISCLAIM_RESPONSIBILITY_ENV,
|
||||
handleDisclaimExecEntry,
|
||||
isRequestForThisProcess,
|
||||
reexecArgv,
|
||||
runDisclaimExec,
|
||||
shouldDisclaimResponsibility,
|
||||
takeDisclaimFallbackNote,
|
||||
type SpawnExecNative
|
||||
} from './disclaimExec'
|
||||
|
||||
const EXE = '/Users/me/.local/bin/hapi-local'
|
||||
|
||||
type FakeNative = SpawnExecNative & { exec: ReturnType<typeof vi.fn>; setenv: ReturnType<typeof vi.fn> }
|
||||
|
||||
function fakeNative(options: { canDisclaim?: boolean; unsetOk?: boolean; execResults?: Array<number | 'replaced'> } = {}): FakeNative {
|
||||
const results = [...(options.execResults ?? [])]
|
||||
return {
|
||||
canDisclaim: options.canDisclaim ?? true,
|
||||
unsetenv: vi.fn((_name: string) => options.unsetOk ?? true),
|
||||
setenv: vi.fn((_name: string, _value: string) => {}),
|
||||
// A real exec never returns on success; 'replaced' stands for that by throwing.
|
||||
exec: vi.fn((_path: string, _argv: readonly string[], _disclaim: boolean) => {
|
||||
const next = results.shift() ?? 1
|
||||
if (next === 'replaced') {
|
||||
throw new Error('replaced')
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
describe('shouldDisclaimResponsibility', () => {
|
||||
const own = () => true
|
||||
const notOwn = () => false
|
||||
|
||||
it('applies only to detached darwin spawns from a process that may hand its responsibility on', () => {
|
||||
expect(shouldDisclaimResponsibility('darwin', true, own)).toBe(true)
|
||||
expect(shouldDisclaimResponsibility('darwin', true, notOwn)).toBe(false)
|
||||
expect(shouldDisclaimResponsibility('darwin', false, own)).toBe(false)
|
||||
expect(shouldDisclaimResponsibility('darwin', undefined, own)).toBe(false)
|
||||
expect(shouldDisclaimResponsibility('linux', true, own)).toBe(false)
|
||||
expect(shouldDisclaimResponsibility('win32', true, own)).toBe(false)
|
||||
})
|
||||
|
||||
it('does not consult the responsibility lookup off darwin or for attached spawns', () => {
|
||||
const lookup = vi.fn(() => true)
|
||||
shouldDisclaimResponsibility('linux', true, lookup)
|
||||
shouldDisclaimResponsibility('darwin', false, lookup)
|
||||
expect(lookup).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('reexecArgv', () => {
|
||||
it('drops the virtual bunfs entry of a compiled binary', () => {
|
||||
expect(reexecArgv(['bun', '/$bunfs/root/hapi', 'runner', 'start-sync'], EXE)).toEqual([EXE, 'runner', 'start-sync'])
|
||||
})
|
||||
|
||||
it('keeps the real entry script in dev mode', () => {
|
||||
expect(reexecArgv(['/opt/bun', '/repo/cli/src/index.ts', 'claude', 'a b'], '/opt/bun'))
|
||||
.toEqual(['/opt/bun', '/repo/cli/src/index.ts', 'claude', 'a b'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('runDisclaimExec', () => {
|
||||
const argv = [EXE, 'claude']
|
||||
|
||||
it('clears the request and execs with the disclaim, without logging', () => {
|
||||
const native = fakeNative({ execResults: ['replaced'] })
|
||||
const log = vi.fn()
|
||||
|
||||
expect(() => runDisclaimExec(EXE, argv, () => native, log)).toThrow('replaced')
|
||||
expect(native.unsetenv).toHaveBeenCalledWith(DISCLAIM_RESPONSIBILITY_ENV)
|
||||
expect(native.exec).toHaveBeenCalledWith(EXE, argv, true)
|
||||
expect(log).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fails open to a plain exec when the disclaim symbol is missing, with one log line and a note', () => {
|
||||
const native = fakeNative({ canDisclaim: false, execResults: ['replaced'] })
|
||||
const log = vi.fn()
|
||||
|
||||
expect(() => runDisclaimExec(EXE, argv, () => native, log)).toThrow('replaced')
|
||||
expect(native.exec.mock.calls).toEqual([[EXE, argv, false]])
|
||||
expect(log).toHaveBeenCalledTimes(1)
|
||||
expect(log.mock.calls[0][0]).toContain('disclaim symbol not found')
|
||||
expect(native.setenv).toHaveBeenCalledWith(DISCLAIM_FALLBACK_ENV, 'disclaim symbol not found')
|
||||
})
|
||||
|
||||
it('fails open to a plain exec when the disclaimed exec returns an error', () => {
|
||||
const native = fakeNative({ execResults: [22, 'replaced'] })
|
||||
const log = vi.fn()
|
||||
|
||||
expect(() => runDisclaimExec(EXE, argv, () => native, log)).toThrow('replaced')
|
||||
expect(native.exec.mock.calls.map((call) => call[2])).toEqual([true, false])
|
||||
expect(log).toHaveBeenCalledTimes(1)
|
||||
expect(log.mock.calls[0][0]).toContain('code 22')
|
||||
})
|
||||
|
||||
it('does not exec when the request cannot be cleared, so the new image cannot loop', () => {
|
||||
const native = fakeNative({ unsetOk: false })
|
||||
const log = vi.fn()
|
||||
|
||||
runDisclaimExec(EXE, argv, () => native, log)
|
||||
|
||||
expect(native.exec).not.toHaveBeenCalled()
|
||||
expect(log).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('returns when the native binding cannot load', () => {
|
||||
const log = vi.fn()
|
||||
|
||||
runDisclaimExec(EXE, argv, () => {
|
||||
throw new Error('dlopen failed')
|
||||
}, log)
|
||||
|
||||
expect(log).toHaveBeenCalledTimes(1)
|
||||
expect(log.mock.calls[0][0]).toContain('dlopen failed')
|
||||
})
|
||||
|
||||
it('returns when every exec fails', () => {
|
||||
const native = fakeNative({ execResults: [1, 2] })
|
||||
const log = vi.fn()
|
||||
|
||||
runDisclaimExec(EXE, argv, () => native, log)
|
||||
|
||||
expect(native.exec).toHaveBeenCalledTimes(2)
|
||||
expect(log).toHaveBeenCalledTimes(2)
|
||||
expect(log.mock.calls[1][0]).toContain('continuing in-process')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isRequestForThisProcess', () => {
|
||||
it('accepts only the pid of the direct parent', () => {
|
||||
expect(isRequestForThisProcess('4242', 4242)).toBe(true)
|
||||
expect(isRequestForThisProcess('4242', 4243)).toBe(false)
|
||||
expect(isRequestForThisProcess('1', 1)).toBe(false)
|
||||
expect(isRequestForThisProcess('', 4242)).toBe(false)
|
||||
expect(isRequestForThisProcess('4242x', 4242)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleDisclaimExecEntry', () => {
|
||||
const argv = ['bun', '/$bunfs/root/hapi', 'runner', 'start-sync']
|
||||
const PARENT = 4242
|
||||
|
||||
it('does nothing without a request', async () => {
|
||||
const loadNative = vi.fn()
|
||||
const env: NodeJS.ProcessEnv = { KEEP: 'x' }
|
||||
|
||||
await handleDisclaimExecEntry({ env, argv, platform: 'darwin', ppid: PARENT, loadNative })
|
||||
|
||||
expect(loadNative).not.toHaveBeenCalled()
|
||||
expect(env).toEqual({ KEEP: 'x' })
|
||||
})
|
||||
|
||||
it('drops a request off darwin without exec', async () => {
|
||||
const loadNative = vi.fn()
|
||||
const env: NodeJS.ProcessEnv = { [DISCLAIM_RESPONSIBILITY_ENV]: String(PARENT) }
|
||||
|
||||
await handleDisclaimExecEntry({ env, argv, platform: 'linux', ppid: PARENT, loadNative })
|
||||
|
||||
expect(loadNative).not.toHaveBeenCalled()
|
||||
expect(env).toEqual({})
|
||||
})
|
||||
|
||||
it.each(['1', '9999'])('drops a request addressed to another process (%s), e.g. one leaked through an older binary', async (value) => {
|
||||
const loadNative = vi.fn()
|
||||
const env: NodeJS.ProcessEnv = { [DISCLAIM_RESPONSIBILITY_ENV]: value }
|
||||
|
||||
await handleDisclaimExecEntry({ env, argv, platform: 'darwin', ppid: PARENT, loadNative })
|
||||
|
||||
expect(loadNative).not.toHaveBeenCalled()
|
||||
expect(env).toEqual({})
|
||||
})
|
||||
|
||||
it('re-executes its own executable with its own arguments', async () => {
|
||||
// A real exec does not return; the fake fails both attempts so the call can be inspected.
|
||||
const native = fakeNative({ execResults: [5, 6] })
|
||||
const env: NodeJS.ProcessEnv = { [DISCLAIM_RESPONSIBILITY_ENV]: String(PARENT) }
|
||||
|
||||
await handleDisclaimExecEntry({
|
||||
env, argv, argv0: '/usr/local/bin/hapi', execPath: EXE, platform: 'darwin', ppid: PARENT,
|
||||
loadNative: async () => () => native, writeStderr: vi.fn()
|
||||
})
|
||||
|
||||
expect(native.exec.mock.calls[0]).toEqual([EXE, ['/usr/local/bin/hapi', 'runner', 'start-sync'], true])
|
||||
expect(env[DISCLAIM_RESPONSIBILITY_ENV]).toBeUndefined()
|
||||
})
|
||||
|
||||
it('continues in-process with the request cleared and a fallback note for the log', async () => {
|
||||
const env: NodeJS.ProcessEnv = { [DISCLAIM_RESPONSIBILITY_ENV]: String(PARENT) }
|
||||
const writeStderr = vi.fn()
|
||||
|
||||
await handleDisclaimExecEntry({
|
||||
env, argv, execPath: EXE, platform: 'darwin', ppid: PARENT, writeStderr,
|
||||
loadNative: async () => {
|
||||
throw new Error('no bun:ffi')
|
||||
}
|
||||
})
|
||||
|
||||
expect(env[DISCLAIM_RESPONSIBILITY_ENV]).toBeUndefined()
|
||||
expect(writeStderr).toHaveBeenCalledTimes(1)
|
||||
const note = takeDisclaimFallbackNote(env)
|
||||
expect(note).toContain('no bun:ffi')
|
||||
expect(env[DISCLAIM_FALLBACK_ENV]).toBeUndefined()
|
||||
})
|
||||
|
||||
it('continues in-process when the native binding throws mid-way', async () => {
|
||||
const native = fakeNative()
|
||||
native.unsetenv = vi.fn(() => {
|
||||
throw new TypeError('ffi call failed')
|
||||
})
|
||||
const env: NodeJS.ProcessEnv = { [DISCLAIM_RESPONSIBILITY_ENV]: String(PARENT) }
|
||||
const writeStderr = vi.fn()
|
||||
|
||||
await expect(handleDisclaimExecEntry({
|
||||
env, argv, execPath: EXE, platform: 'darwin', ppid: PARENT, writeStderr,
|
||||
loadNative: async () => () => native
|
||||
})).resolves.toBeUndefined()
|
||||
|
||||
expect(native.exec).not.toHaveBeenCalled()
|
||||
expect(writeStderr).toHaveBeenCalledTimes(1)
|
||||
expect(takeDisclaimFallbackNote(env)).toContain('ffi call failed')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* macOS responsibility disclaim for detached HAPI processes.
|
||||
*
|
||||
* macOS attributes a process's privacy decisions (Local Network, TCC) to its
|
||||
* "responsible process", inherited from the spawner. A session spawned by a
|
||||
* launchd-managed runner therefore stays tied to that runner's pid. Once the
|
||||
* runner is replaced (upgrade, handoff) and that pid is gone, macOS can no
|
||||
* longer resolve the responsible app, and every new process in the session tree
|
||||
* that connects to a LAN address fails with EHOSTUNREACH.
|
||||
*
|
||||
* When the spawner may hand its responsibility on (see responsibility.ts), a
|
||||
* detached child is started with `HAPI_DISCLAIM_RESPONSIBILITY=<spawner pid>`.
|
||||
* The entry hook below honours it only in a direct child of that pid, removes
|
||||
* the variable, and re-executes `process.execPath` in place (same pid, stdio,
|
||||
* cwd, and otherwise the same environment) with
|
||||
* `responsibility_spawnattrs_setdisclaim`, so the child becomes its own
|
||||
* responsible process. A binary that predates this hook ignores the variable and
|
||||
* starts normally, which keeps rollbacks working; a copy of the variable that
|
||||
* leaks further down such a tree is ignored by later binaries because their
|
||||
* parent is not the spawner.
|
||||
*/
|
||||
export const DISCLAIM_RESPONSIBILITY_ENV = 'HAPI_DISCLAIM_RESPONSIBILITY'
|
||||
/** Set for the re-executed image when the disclaim degraded, so it can log why. */
|
||||
export const DISCLAIM_FALLBACK_ENV = 'HAPI_DISCLAIM_FALLBACK'
|
||||
|
||||
export interface SpawnExecNative {
|
||||
/** Whether the private disclaim symbol was found. */
|
||||
canDisclaim: boolean
|
||||
/** Removes a variable from the libc environment; true when it is gone. */
|
||||
unsetenv(name: string): boolean
|
||||
setenv(name: string, value: string): void
|
||||
/** Replaces the current process image; returns only on failure (non-zero code). */
|
||||
exec(path: string, argv: readonly string[], disclaim: boolean): number
|
||||
}
|
||||
|
||||
export function shouldDisclaimResponsibility(
|
||||
platform: NodeJS.Platform,
|
||||
detached: boolean | undefined,
|
||||
canDisclaimForChildren: () => boolean
|
||||
): boolean {
|
||||
return platform === 'darwin' && detached === true && canDisclaimForChildren()
|
||||
}
|
||||
|
||||
/** The request is addressed to direct children of the spawner only. */
|
||||
export function isRequestForThisProcess(value: string, ppid: number): boolean {
|
||||
return /^\d+$/.test(value) && Number(value) > 1 && Number(value) === ppid
|
||||
}
|
||||
|
||||
/**
|
||||
* argv for re-executing this same invocation. Compiled binaries report a virtual
|
||||
* `/$bunfs/...` entry as argv[1] that the executable supplies itself; in dev mode
|
||||
* argv[1] is the real entry script (Bun has already applied `--cwd`, so the
|
||||
* current directory is the one it needs).
|
||||
*/
|
||||
export function reexecArgv(argv: readonly string[], argv0: string): string[] {
|
||||
const compiled = (argv[1] ?? '').startsWith('/$bunfs/')
|
||||
return compiled ? [argv0, ...argv.slice(2)] : [argv0, ...argv.slice(1)]
|
||||
}
|
||||
|
||||
/**
|
||||
* Fails open: without the disclaim it execs the same command plainly, and if no
|
||||
* exec is possible it returns so the caller continues in-process. Each fallback
|
||||
* step writes one line through `log`.
|
||||
*/
|
||||
export function runDisclaimExec(
|
||||
execPath: string,
|
||||
argv: readonly string[],
|
||||
loadNative: () => SpawnExecNative,
|
||||
log: (line: string) => void
|
||||
): void {
|
||||
let native: SpawnExecNative
|
||||
try {
|
||||
native = loadNative()
|
||||
} catch (error) {
|
||||
log(`macOS responsibility disclaim unavailable (${error instanceof Error ? error.message : String(error)}); continuing without it`)
|
||||
return
|
||||
}
|
||||
// The exec'd image must not see the request again, or it would re-exec forever.
|
||||
if (!native.unsetenv(DISCLAIM_RESPONSIBILITY_ENV)) {
|
||||
log(`macOS responsibility disclaim: could not clear ${DISCLAIM_RESPONSIBILITY_ENV}; continuing without it`)
|
||||
return
|
||||
}
|
||||
|
||||
let reason: string
|
||||
if (native.canDisclaim) {
|
||||
const rc = native.exec(execPath, argv, true)
|
||||
reason = `disclaimed exec failed (code ${rc})`
|
||||
} else {
|
||||
reason = 'disclaim symbol not found'
|
||||
}
|
||||
log(`macOS responsibility disclaim: ${reason}; executing without it`)
|
||||
native.setenv(DISCLAIM_FALLBACK_ENV, reason)
|
||||
const rc = native.exec(execPath, argv, false)
|
||||
log(`macOS responsibility disclaim: exec failed (code ${rc}); continuing in-process without it`)
|
||||
}
|
||||
|
||||
export interface DisclaimEntryOptions {
|
||||
env?: NodeJS.ProcessEnv
|
||||
argv?: readonly string[]
|
||||
argv0?: string
|
||||
execPath?: string
|
||||
platform?: NodeJS.Platform
|
||||
ppid?: number
|
||||
loadNative?: () => Promise<() => SpawnExecNative>
|
||||
writeStderr?: (line: string) => void
|
||||
}
|
||||
|
||||
async function loadDarwinNative(): Promise<() => SpawnExecNative> {
|
||||
const { loadDarwinSpawnExec } = await import('./darwinSpawnExec')
|
||||
return loadDarwinSpawnExec
|
||||
}
|
||||
|
||||
/**
|
||||
* Entry hook; runs before the CLI module graph loads so the re-exec happens
|
||||
* before any side effects (log files, sockets, timers). Returns when this process
|
||||
* should continue as the CLI; it never throws.
|
||||
*/
|
||||
export async function handleDisclaimExecEntry(options: DisclaimEntryOptions = {}): Promise<void> {
|
||||
const env = options.env ?? process.env
|
||||
const requested = env[DISCLAIM_RESPONSIBILITY_ENV]
|
||||
if (requested === undefined) {
|
||||
return
|
||||
}
|
||||
// Never hand the request on to this process's own children.
|
||||
delete env[DISCLAIM_RESPONSIBILITY_ENV]
|
||||
if ((options.platform ?? process.platform) !== 'darwin'
|
||||
|| !isRequestForThisProcess(requested, options.ppid ?? process.ppid)) {
|
||||
return
|
||||
}
|
||||
|
||||
const writeStderr = options.writeStderr ?? ((line: string) => process.stderr.write(`[hapi] ${line}\n`))
|
||||
const notes: string[] = []
|
||||
const log = (line: string) => {
|
||||
notes.push(line)
|
||||
writeStderr(line)
|
||||
}
|
||||
// Fail open: whatever goes wrong, this process continues as the CLI.
|
||||
try {
|
||||
let loadNative: () => SpawnExecNative
|
||||
try {
|
||||
loadNative = await (options.loadNative ?? loadDarwinNative)()
|
||||
} catch (error) {
|
||||
loadNative = () => {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
runDisclaimExec(
|
||||
options.execPath ?? process.execPath,
|
||||
reexecArgv(options.argv ?? process.argv, options.argv0 ?? process.argv0),
|
||||
loadNative,
|
||||
log
|
||||
)
|
||||
} catch (error) {
|
||||
log(`macOS responsibility disclaim failed (${error instanceof Error ? error.message : String(error)}); continuing in-process without it`)
|
||||
}
|
||||
env[DISCLAIM_FALLBACK_ENV] = notes.join('; ')
|
||||
}
|
||||
|
||||
/** Reads and clears the fallback note left by the entry hook, if any. */
|
||||
export function takeDisclaimFallbackNote(env: NodeJS.ProcessEnv = process.env): string | null {
|
||||
const note = env[DISCLAIM_FALLBACK_ENV]
|
||||
if (note === undefined) {
|
||||
return null
|
||||
}
|
||||
delete env[DISCLAIM_FALLBACK_ENV]
|
||||
return note
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* The npm launcher (`bin/hapi.cjs`) passes its own pid so the binary can tell
|
||||
* whether launchd started it through the launcher (see responsibility.ts).
|
||||
*
|
||||
* This module imports nothing: the CLI entry reads the value before any module
|
||||
* with side effects loads, so `hapi --help` still works when HAPI_HOME cannot be
|
||||
* created.
|
||||
*/
|
||||
|
||||
/** Set by the npm launcher to its own pid; read once at startup and never passed on. */
|
||||
export const LAUNCHER_PID_ENV = 'HAPI_LAUNCHER_PID'
|
||||
|
||||
let launcherPid: number | null = null
|
||||
|
||||
function parsePid(value: string | undefined): number | null {
|
||||
if (!value || !/^\d+$/.test(value)) {
|
||||
return null
|
||||
}
|
||||
const pid = Number(value)
|
||||
return pid > 1 ? pid : null
|
||||
}
|
||||
|
||||
/** Reads and removes the launcher pid, so no child of this process inherits it. */
|
||||
export function captureLauncherPid(env: NodeJS.ProcessEnv = process.env): void {
|
||||
launcherPid = parsePid(env[LAUNCHER_PID_ENV])
|
||||
delete env[LAUNCHER_PID_ENV]
|
||||
}
|
||||
|
||||
export function getLauncherPid(): number | null {
|
||||
return launcherPid
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { captureLauncherPid, getLauncherPid, LAUNCHER_PID_ENV } from './launcherPid'
|
||||
import { ownsResponsibility } from './responsibility'
|
||||
|
||||
// pid -> responsible pid
|
||||
function table(entries: Record<number, number>): (pid: number) => number {
|
||||
return (pid) => entries[pid] ?? pid
|
||||
}
|
||||
|
||||
describe('ownsResponsibility', () => {
|
||||
it('is true for a process that is its own responsible process (started by launchd)', () => {
|
||||
expect(ownsResponsibility({ pid: 100, ppid: 1, launcherPid: null, responsibleFor: table({ 100: 100 }) })).toBe(true)
|
||||
})
|
||||
|
||||
it('is true under the npm launcher when that launcher is the parent and its own responsible process', () => {
|
||||
expect(ownsResponsibility({ pid: 100, ppid: 50, launcherPid: 50, responsibleFor: table({ 100: 50, 50: 50 }) })).toBe(true)
|
||||
})
|
||||
|
||||
it('is false under the npm launcher started from Terminal or SSH', () => {
|
||||
// Terminal (10) is responsible for both the launcher (50) and the binary (100).
|
||||
expect(ownsResponsibility({ pid: 100, ppid: 50, launcherPid: 50, responsibleFor: table({ 100: 10, 50: 10 }) })).toBe(false)
|
||||
})
|
||||
|
||||
it('is false when the responsible process is not the declared launcher or not the parent', () => {
|
||||
const facts = { pid: 100, responsibleFor: table({ 100: 50, 50: 50 }) }
|
||||
expect(ownsResponsibility({ ...facts, ppid: 50, launcherPid: null })).toBe(false)
|
||||
expect(ownsResponsibility({ ...facts, ppid: 50, launcherPid: 51 })).toBe(false)
|
||||
expect(ownsResponsibility({ ...facts, ppid: 60, launcherPid: 50 })).toBe(false)
|
||||
})
|
||||
|
||||
it('is false for a process under a supervisor such as pm2', () => {
|
||||
// pm2 (20) -> launcher (50) -> binary (100); pm2 is responsible for both.
|
||||
expect(ownsResponsibility({ pid: 100, ppid: 50, launcherPid: 50, responsibleFor: table({ 100: 20, 50: 20 }) })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('captureLauncherPid', () => {
|
||||
afterEach(() => captureLauncherPid({}))
|
||||
|
||||
it('removes the launcher pid from the environment so children never inherit it', () => {
|
||||
const env: NodeJS.ProcessEnv = { [LAUNCHER_PID_ENV]: '50', KEEP: 'x' }
|
||||
|
||||
captureLauncherPid(env)
|
||||
|
||||
expect(env).toEqual({ KEEP: 'x' })
|
||||
})
|
||||
|
||||
it.each([
|
||||
['50', 50],
|
||||
['1', null],
|
||||
['stale', null],
|
||||
[undefined, null],
|
||||
])('reads %s as launcher pid %s', (value, expected) => {
|
||||
captureLauncherPid(value === undefined ? {} : { [LAUNCHER_PID_ENV]: value })
|
||||
|
||||
expect(getLauncherPid()).toBe(expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('canDisclaimForChildren', () => {
|
||||
const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(process, 'platform', platform)
|
||||
vi.resetModules()
|
||||
vi.doUnmock('@/ui/logger')
|
||||
})
|
||||
|
||||
it('fails open and logs once when the lookup is unavailable on darwin', async () => {
|
||||
const debug = vi.fn()
|
||||
vi.doMock('@/ui/logger', () => ({ logger: { debug } }))
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true })
|
||||
vi.resetModules()
|
||||
const { canDisclaimForChildren } = await import('./responsibility')
|
||||
|
||||
// Vitest runs under Node, where bun:ffi is not available.
|
||||
expect(canDisclaimForChildren()).toBe(false)
|
||||
expect(canDisclaimForChildren()).toBe(false)
|
||||
expect(debug).toHaveBeenCalledTimes(1)
|
||||
expect(debug.mock.calls[0][0]).toMatch(/^\[WARN\] \[DISCLAIM\] macOS responsibility lookup unavailable/)
|
||||
})
|
||||
|
||||
it('stays silent off darwin', async () => {
|
||||
const debug = vi.fn()
|
||||
vi.doMock('@/ui/logger', () => ({ logger: { debug } }))
|
||||
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true })
|
||||
vi.resetModules()
|
||||
const { canDisclaimForChildren } = await import('./responsibility')
|
||||
|
||||
expect(canDisclaimForChildren()).toBe(false)
|
||||
expect(debug).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Whether this process may hand its macOS responsibility to the detached
|
||||
* processes it spawns (see disclaimExec.ts).
|
||||
*
|
||||
* That is the case when this process is its own responsible process, as a
|
||||
* runner started directly by launchd is, or when its responsible process is the
|
||||
* npm launcher (`bin/hapi.cjs`) that launchd started and that started this
|
||||
* process. In both cases the inherited responsible pid goes away when the runner
|
||||
* or its launcher exits. A process started from Terminal or over SSH has
|
||||
* Terminal or sshd-session as its responsible process, and macOS grants their
|
||||
* descendants LAN access implicitly; those keep the inherited responsibility.
|
||||
*
|
||||
* Observed on macOS 27: once a process's responsible process has exited,
|
||||
* `responsibility_get_pid_responsible_for_pid` reports the process itself. Such a
|
||||
* spawner then counts as its own responsible process. Its tree has already lost
|
||||
* LAN access for new processes, so disclaiming its children is no worse.
|
||||
*/
|
||||
import { logger } from '@/ui/logger'
|
||||
import { getLauncherPid } from './launcherPid'
|
||||
|
||||
type ResponsibleFor = (pid: number) => number
|
||||
|
||||
let lookup: ResponsibleFor | null | undefined
|
||||
|
||||
export interface ResponsibilityFacts {
|
||||
pid: number
|
||||
ppid: number
|
||||
launcherPid: number | null
|
||||
responsibleFor: ResponsibleFor
|
||||
}
|
||||
|
||||
export function ownsResponsibility(facts: ResponsibilityFacts): boolean {
|
||||
const responsible = facts.responsibleFor(facts.pid)
|
||||
if (responsible === facts.pid) {
|
||||
return true
|
||||
}
|
||||
return facts.launcherPid !== null
|
||||
&& responsible === facts.launcherPid
|
||||
&& responsible === facts.ppid
|
||||
&& facts.responsibleFor(responsible) === responsible
|
||||
}
|
||||
|
||||
function warnOnce(reason: string): void {
|
||||
logger.debug(`[WARN] [DISCLAIM] macOS responsibility lookup unavailable (${reason}); detached children keep the inherited responsible process`)
|
||||
}
|
||||
|
||||
function loadLookup(): ResponsibleFor | null {
|
||||
if (process.platform !== 'darwin') {
|
||||
return null
|
||||
}
|
||||
if (!process.versions.bun) {
|
||||
warnOnce('not running under Bun')
|
||||
return null
|
||||
}
|
||||
try {
|
||||
// Loaded lazily: this module is also imported under Node (tests), where
|
||||
// bun:ffi does not exist.
|
||||
const { dlopen, FFIType } = require('bun:ffi') as typeof import('bun:ffi')
|
||||
const { symbols } = dlopen('/usr/lib/libSystem.B.dylib', {
|
||||
responsibility_get_pid_responsible_for_pid: { args: [FFIType.i32], returns: FFIType.i32 }
|
||||
})
|
||||
return (pid) => symbols.responsibility_get_pid_responsible_for_pid(pid)
|
||||
} catch (error) {
|
||||
warnOnce(error instanceof Error ? error.message : String(error))
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** False whenever the answer is unknown, so callers fail open to no disclaim. */
|
||||
export function canDisclaimForChildren(): boolean {
|
||||
if (lookup === undefined) {
|
||||
lookup = loadLookup()
|
||||
}
|
||||
if (!lookup) {
|
||||
return false
|
||||
}
|
||||
try {
|
||||
return ownsResponsibility({ pid: process.pid, ppid: process.ppid, launcherPid: getLauncherPid(), responsibleFor: lookup })
|
||||
} catch (error) {
|
||||
warnOnce(error instanceof Error ? error.message : String(error))
|
||||
lookup = null
|
||||
return false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user