From fd824c5e3279208abb7807c24c3b48d93b973a4a Mon Sep 17 00:00:00 2001 From: JounQin Date: Thu, 12 Nov 2026 19:19:50 +0000 Subject: [PATCH 1/7] fix: refuse a host account config logged in as another user --- .changeset/host-account-identity.md | 6 +++++ README.md | 6 +++-- packages/host/src/commands/host.ts | 36 ++++++++++++++++++++++++++ test/unit/host.test.ts | 40 +++++++++++++++++++++++++++++ 4 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 .changeset/host-account-identity.md diff --git a/.changeset/host-account-identity.md b/.changeset/host-account-identity.md new file mode 100644 index 00000000..7b1edd54 --- /dev/null +++ b/.changeset/host-account-identity.md @@ -0,0 +1,6 @@ +--- +"gcb-host": patch +--- + +Refuse `--as-user ` when `~/.config/gh-` is logged in as another active user, instead +of silently performing the person action as that other account. diff --git a/README.md b/README.md index b11a19e0..1d0dcc46 100644 --- a/README.md +++ b/README.md @@ -506,8 +506,10 @@ submit requests as the selected account within the allowlist. `--as-user ` selects `~/.config/gh-` on the host, matching the login exactly including case; create that directory once with `GH_CONFIG_DIR="$HOME/.config/gh-octocat" gh auth login`. The directory must -already exist, and inherited `GH_TOKEN`/`GITHUB_TOKEN`/`GH_ENTERPRISE_TOKEN`/`GITHUB_ENTERPRISE_TOKEN`/`GH_HOST` are ignored -for that request. Any existing account directory can be named, so this is a selector rather than a +already exist, and its active `github.com` user must be that login; a directory symlinked to the +default gh config with another active user is refused rather than running as that other account. +Inherited `GH_TOKEN`/`GITHUB_TOKEN`/`GH_ENTERPRISE_TOKEN`/`GITHUB_ENTERPRISE_TOKEN`/`GH_HOST` are +ignored for that request. Any existing account directory can be named, so this is a selector rather than a gate. A request with no `--as-user` uses the broker route and does not select the host broker's login. The host broker never runs a shell, and the program it calls is configuration rather than a hard-coded `gh`: `--command /path/to/gh`, or diff --git a/packages/host/src/commands/host.ts b/packages/host/src/commands/host.ts index 01179b25..4d6f970b 100644 --- a/packages/host/src/commands/host.ts +++ b/packages/host/src/commands/host.ts @@ -17,6 +17,7 @@ import { lstatSync, mkdirSync, mkdtempSync, + readFileSync, rmSync, statSync, writeFileSync, @@ -62,6 +63,7 @@ import { validateArgs, warn, } from 'gcb-core' +import { parseDocument } from 'yaml' import { loadConfig, resolveConfigPath } from '../config.ts' import { applyProxyChoice, fetcherFor, parseProxy, type ProxyChoice } from '../http.ts' @@ -633,6 +635,39 @@ async function sweep( return answered } +/** + * Refuse an account directory whose active GitHub login is not the requested one. + * + * `GH_CONFIG_DIR` selects a config directory, not a user inside it; a symlink to the default config + * (or a directory with a different active user) would otherwise run the person action as somebody + * else. Only the github.com active user is checked; a missing or unreadable hosts.yml falls through + * to gh, which reports its own error. + */ +function assertAccountUser(dir: string, account: string): void { + let parsed: unknown + try { + parsed = parseDocument(readFileSync(join(dir, 'hosts.yml'), 'utf8')).toJS() + } catch { + return + } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + return + } + const github = (parsed as Record)['github.com'] + if (typeof github !== 'object' || github === null || Array.isArray(github)) { + return + } + const active = (github as Record)['user'] + if (typeof active !== 'string' || active === '') { + return + } + if (active.toLowerCase() !== account.toLowerCase()) { + throw new Error( + `gh config for account ${JSON.stringify(account)} is logged in as ${JSON.stringify(active)}; run gh auth switch --user ${account} in ${dir} (or log that account in there)`, + ) + } +} + /** Environment for one gh call: the selected account or inherited config, plus the proxy choice. */ function forkEnv(proxy: ProxyChoice, account: string | undefined, host: string): NodeJS.ProcessEnv { const env = hostEnv(proxy, account) @@ -655,6 +690,7 @@ function hostEnv(proxy: ProxyChoice, account?: string): NodeJS.ProcessEnv { delete env['GH_ENTERPRISE_TOKEN'] delete env['GITHUB_ENTERPRISE_TOKEN'] delete env['GH_HOST'] + assertAccountUser(dir, account) env['GH_CONFIG_DIR'] = dir } applyProxyChoice(env, proxy) diff --git a/test/unit/host.test.ts b/test/unit/host.test.ts index 1958b373..e0cf30ee 100644 --- a/test/unit/host.test.ts +++ b/test/unit/host.test.ts @@ -2023,6 +2023,46 @@ describe('a claim that someone else holds', () => { }) }) +it('refuses an account directory logged in as another user', async () => { + const root = mkdtempSync(join(tmpdir(), 'host-broker-account-mismatch-')) + const repo = join(root, 'checkout') + mkdirSync(join(repo, '.git'), { recursive: true }) + writeFileSync(join(repo, '.git', 'HEAD'), 'ref: refs/heads/main\n', 'utf8') + const dir = channelDir(join(repo, '.git')) + const marker = join(root, 'ran') + const command = join(root, 'not-gh') + writeFileSync(command, '#!/bin/sh\ntouch ' + marker + '\n', 'utf8') + chmodSync(command, 0o755) + const configDir = join(root, '.config', 'gh-alice') + mkdirSync(configDir, { recursive: true }) + writeFileSync( + join(configDir, 'hosts.yml'), + 'github.com:\n users:\n mallory:\n oauth_token: not-a-secret\n user: mallory\n', + 'utf8', + ) + const previous = process.env['HOME'] + process.env['HOME'] = root + try { + const id = writeRequest(dir, { + head: 'feat/ok', + base: 'main', + title: 'x', + body: '', + account: 'alice', + }) + assert.equal(await runHostBroker(['--repo', repo, '--command', command, '--once']), 0) + assert.match(readResult(dir, id)?.error ?? '', /logged in as .*mallory/u) + assert.equal(existsSync(marker), false, 'the program did not run') + } finally { + if (previous === undefined) { + delete process.env['HOME'] + } else { + process.env['HOME'] = previous + } + rmSync(root, { recursive: true, force: true }) + } +}) + describe('the host broker account selection', () => { it('uses ~/.config/gh- and clears inherited tokens', async () => { const root = mkdtempSync(join(tmpdir(), 'host-broker-account-')) From 02f0f1bf477a02e6a469b17c090035c28a662cb7 Mon Sep 17 00:00:00 2001 From: JounQin Date: Thu, 12 Nov 2026 19:34:24 +0000 Subject: [PATCH 2/7] fix: honor an inherited GH_TOKEN without an account dir --- README.md | 7 +++-- packages/host/src/commands/host.ts | 25 +++++++++------- test/unit/host.test.ts | 47 ++++++++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 1d0dcc46..ef5ffd47 100644 --- a/README.md +++ b/README.md @@ -508,8 +508,11 @@ selects `~/.config/gh-` on the host, matching the login exactly including directory once with `GH_CONFIG_DIR="$HOME/.config/gh-octocat" gh auth login`. The directory must already exist, and its active `github.com` user must be that login; a directory symlinked to the default gh config with another active user is refused rather than running as that other account. -Inherited `GH_TOKEN`/`GITHUB_TOKEN`/`GH_ENTERPRISE_TOKEN`/`GITHUB_ENTERPRISE_TOKEN`/`GH_HOST` are -ignored for that request. Any existing account directory can be named, so this is a selector rather than a +If the directory does not exist, an inherited `GH_TOKEN`/`GITHUB_TOKEN` is used as-is instead, so a +host broker started from a shell that exports its identity needs no per-account directory. When a +directory is used, inherited +`GH_TOKEN`/`GITHUB_TOKEN`/`GH_ENTERPRISE_TOKEN`/`GITHUB_ENTERPRISE_TOKEN`/`GH_HOST` are ignored for +that request. Any existing account directory can be named, so this is a selector rather than a gate. A request with no `--as-user` uses the broker route and does not select the host broker's login. The host broker never runs a shell, and the program it calls is configuration rather than a hard-coded `gh`: `--command /path/to/gh`, or diff --git a/packages/host/src/commands/host.ts b/packages/host/src/commands/host.ts index 4d6f970b..dd519ccc 100644 --- a/packages/host/src/commands/host.ts +++ b/packages/host/src/commands/host.ts @@ -681,17 +681,22 @@ function hostEnv(proxy: ProxyChoice, account?: string): NodeJS.ProcessEnv { const env = { ...process.env } if (account !== undefined) { const dir = join(homedir(), '.config', `gh-${account}`) - if (!existsSync(dir) || !statSync(dir).isDirectory()) { - throw new Error(`no gh config for account ${JSON.stringify(account)} at ${dir}`) + if (existsSync(dir) && statSync(dir).isDirectory()) { + // Tokens in the host broker's own environment would override the selected account's config. + delete env['GH_TOKEN'] + delete env['GITHUB_TOKEN'] + delete env['GH_ENTERPRISE_TOKEN'] + delete env['GITHUB_ENTERPRISE_TOKEN'] + delete env['GH_HOST'] + assertAccountUser(dir, account) + env['GH_CONFIG_DIR'] = dir + } else if (env['GH_TOKEN'] === undefined && env['GITHUB_TOKEN'] === undefined) { + throw new Error( + `no gh config for account ${JSON.stringify(account)} at ${dir}, and no inherited GH_TOKEN/GITHUB_TOKEN`, + ) } - // Tokens in the host broker's own environment would override the selected account's config. - delete env['GH_TOKEN'] - delete env['GITHUB_TOKEN'] - delete env['GH_ENTERPRISE_TOKEN'] - delete env['GITHUB_ENTERPRISE_TOKEN'] - delete env['GH_HOST'] - assertAccountUser(dir, account) - env['GH_CONFIG_DIR'] = dir + // Without an account directory the inherited token is the identity. gh gives GH_TOKEN priority + // over GH_CONFIG_DIR, so leave it in place rather than inventing a directory for it. } applyProxyChoice(env, proxy) return env diff --git a/test/unit/host.test.ts b/test/unit/host.test.ts index e0cf30ee..00b20b3b 100644 --- a/test/unit/host.test.ts +++ b/test/unit/host.test.ts @@ -2063,6 +2063,53 @@ it('refuses an account directory logged in as another user', async () => { } }) +it('uses an inherited GH_TOKEN when no account directory exists', async () => { + const root = mkdtempSync(join(tmpdir(), 'host-broker-account-token-')) + const repo = join(root, 'checkout') + mkdirSync(join(repo, '.git'), { recursive: true }) + writeFileSync(join(repo, '.git', 'HEAD'), 'ref: refs/heads/main\n', 'utf8') + const dir = channelDir(join(repo, '.git')) + const envFile = join(root, 'env') + const command = join(root, 'not-gh') + writeFileSync( + command, + '#!/bin/sh\nprintf \'%s|%s\\n\' "$GH_TOKEN" "$GH_CONFIG_DIR" > ' + + envFile + + '\necho "https://github.com/acme/widget/pull/7"\n', + 'utf8', + ) + chmodSync(command, 0o755) + const previous = { + HOME: process.env['HOME'], + GH_TOKEN: process.env['GH_TOKEN'], + GITHUB_TOKEN: process.env['GITHUB_TOKEN'], + } + process.env['HOME'] = root + process.env['GH_TOKEN'] = 'inherited-token' + delete process.env['GITHUB_TOKEN'] + try { + const id = writeRequest(dir, { + head: 'feat/ok', + base: 'main', + title: 'x', + body: '', + account: 'alice', + }) + assert.equal(await runHostBroker(['--repo', repo, '--command', command, '--once']), 0) + assert.equal(readResult(dir, id)?.error, undefined) + assert.equal(readFileSync(envFile, 'utf8').trim(), 'inherited-token|') + } finally { + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) { + delete process.env[key] + } else { + process.env[key] = value + } + } + rmSync(root, { recursive: true, force: true }) + } +}) + describe('the host broker account selection', () => { it('uses ~/.config/gh- and clears inherited tokens', async () => { const root = mkdtempSync(join(tmpdir(), 'host-broker-account-')) From 4c98e0230e52ee39055575e361c2103916c8fc2e Mon Sep 17 00:00:00 2001 From: JounQin Date: Thu, 12 Nov 2026 19:43:53 +0000 Subject: [PATCH 3/7] fix: select a matching host account without switching --- README.md | 18 ++-- packages/host/src/commands/host.ts | 129 +++++++++++++++++++---------- test/unit/host.test.ts | 80 +++++++++++++++++- 3 files changed, 174 insertions(+), 53 deletions(-) diff --git a/README.md b/README.md index ef5ffd47..4f4fac93 100644 --- a/README.md +++ b/README.md @@ -506,13 +506,17 @@ submit requests as the selected account within the allowlist. `--as-user ` selects `~/.config/gh-` on the host, matching the login exactly including case; create that directory once with `GH_CONFIG_DIR="$HOME/.config/gh-octocat" gh auth login`. The directory must -already exist, and its active `github.com` user must be that login; a directory symlinked to the -default gh config with another active user is refused rather than running as that other account. -If the directory does not exist, an inherited `GH_TOKEN`/`GITHUB_TOKEN` is used as-is instead, so a -host broker started from a shell that exports its identity needs no per-account directory. When a -directory is used, inherited -`GH_TOKEN`/`GITHUB_TOKEN`/`GH_ENTERPRISE_TOKEN`/`GITHUB_ENTERPRISE_TOKEN`/`GH_HOST` are ignored for -that request. Any existing account directory can be named, so this is a selector rather than a +already exist. Selection is deterministic: + +1. If the directory's active `github.com` user is that login, it is used; inherited tokens are + cleared so they cannot override it. +2. If the active user differs, an inherited `GH_TOKEN`/`GITHUB_TOKEN` is used next, so a host + broker started from a shell that exports its identity works without a directory. +3. Otherwise `gh auth token --user ` supplies that account's token for this request only; + the active account is not switched. +4. If none of those names the account, the request is refused. + +This also refuses a directory symlinked to a config whose active account is somebody else. Any existing account directory can be named, so this is a selector rather than a gate. A request with no `--as-user` uses the broker route and does not select the host broker's login. The host broker never runs a shell, and the program it calls is configuration rather than a hard-coded `gh`: `--command /path/to/gh`, or diff --git a/packages/host/src/commands/host.ts b/packages/host/src/commands/host.ts index dd519ccc..60c78f77 100644 --- a/packages/host/src/commands/host.ts +++ b/packages/host/src/commands/host.ts @@ -11,7 +11,7 @@ * It has no other power than the catalogued actions: it cannot push or merge, and it never runs a * shell; the program it calls is configuration, and it is called with an argument list built here. */ -import { execFile, spawn } from 'node:child_process' +import { execFile, execFileSync, spawn } from 'node:child_process' import { existsSync, lstatSync, @@ -635,61 +635,101 @@ async function sweep( return answered } -/** - * Refuse an account directory whose active GitHub login is not the requested one. - * - * `GH_CONFIG_DIR` selects a config directory, not a user inside it; a symlink to the default config - * (or a directory with a different active user) would otherwise run the person action as somebody - * else. Only the github.com active user is checked; a missing or unreadable hosts.yml falls through - * to gh, which reports its own error. - */ -function assertAccountUser(dir: string, account: string): void { +/** The active github.com user in one gh config directory, when it can be read. */ +function activeAccount(dir: string): string | undefined { let parsed: unknown try { parsed = parseDocument(readFileSync(join(dir, 'hosts.yml'), 'utf8')).toJS() } catch { - return + return undefined } if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { - return + return undefined } const github = (parsed as Record)['github.com'] if (typeof github !== 'object' || github === null || Array.isArray(github)) { - return + return undefined } const active = (github as Record)['user'] - if (typeof active !== 'string' || active === '') { - return - } - if (active.toLowerCase() !== account.toLowerCase()) { - throw new Error( - `gh config for account ${JSON.stringify(account)} is logged in as ${JSON.stringify(active)}; run gh auth switch --user ${account} in ${dir} (or log that account in there)`, - ) + return typeof active === 'string' && active !== '' ? active : undefined +} + +/** Ask gh for one named account's token without switching the active account. */ +function accountToken( + command: string, + dir: string, + host: string, + account: string, +): string | undefined { + const env: NodeJS.ProcessEnv = { ...process.env, GH_CONFIG_DIR: dir } + delete env['GH_TOKEN'] + delete env['GITHUB_TOKEN'] + delete env['GH_ENTERPRISE_TOKEN'] + delete env['GITHUB_ENTERPRISE_TOKEN'] + delete env['GH_HOST'] + try { + const token = execFileSync(command, ['auth', 'token', '--hostname', host, '--user', account], { + env, + encoding: 'utf8', + timeout: 5_000, + stdio: ['ignore', 'pipe', 'ignore'], + }).trim() + return token === '' ? undefined : token + } catch { + return undefined } } /** Environment for one gh call: the selected account or inherited config, plus the proxy choice. */ -function forkEnv(proxy: ProxyChoice, account: string | undefined, host: string): NodeJS.ProcessEnv { - const env = hostEnv(proxy, account) +function forkEnv( + proxy: ProxyChoice, + account: string | undefined, + host: string, + command = 'gh', +): NodeJS.ProcessEnv { + const env = hostEnv(proxy, account, command, host) // gh chooses between GH_TOKEN and GH_ENTERPRISE_TOKEN by host; forcing GH_HOST is what keeps an // inherited token from selecting another instance. Named accounts already had their tokens removed. env['GH_HOST'] = host return env } -function hostEnv(proxy: ProxyChoice, account?: string): NodeJS.ProcessEnv { +function hostEnv( + proxy: ProxyChoice, + account?: string, + command = 'gh', + host = 'github.com', +): NodeJS.ProcessEnv { const env = { ...process.env } if (account !== undefined) { const dir = join(homedir(), '.config', `gh-${account}`) if (existsSync(dir) && statSync(dir).isDirectory()) { - // Tokens in the host broker's own environment would override the selected account's config. - delete env['GH_TOKEN'] - delete env['GITHUB_TOKEN'] - delete env['GH_ENTERPRISE_TOKEN'] - delete env['GITHUB_ENTERPRISE_TOKEN'] - delete env['GH_HOST'] - assertAccountUser(dir, account) - env['GH_CONFIG_DIR'] = dir + const active = activeAccount(dir) + if (active === undefined || active.toLowerCase() === account.toLowerCase()) { + // The directory is the selected account; inherited tokens must not override it. + delete env['GH_TOKEN'] + delete env['GITHUB_TOKEN'] + delete env['GH_ENTERPRISE_TOKEN'] + delete env['GITHUB_ENTERPRISE_TOKEN'] + delete env['GH_HOST'] + env['GH_CONFIG_DIR'] = dir + } else if (env['GH_TOKEN'] !== undefined || env['GITHUB_TOKEN'] !== undefined) { + // A token exported for this broker is the identity; keep it and use the directory for + // settings only. + env['GH_CONFIG_DIR'] = dir + } else { + const token = accountToken(command, dir, host, account) + if (token === undefined) { + throw new Error( + `gh config for account ${JSON.stringify(account)} is logged in as ${JSON.stringify(active)}, and gh auth token --user ${account} found no token`, + ) + } + env['GH_TOKEN'] = token + delete env['GITHUB_TOKEN'] + delete env['GH_ENTERPRISE_TOKEN'] + delete env['GITHUB_ENTERPRISE_TOKEN'] + env['GH_CONFIG_DIR'] = dir + } } else if (env['GH_TOKEN'] === undefined && env['GITHUB_TOKEN'] === undefined) { throw new Error( `no gh config for account ${JSON.stringify(account)} at ${dir}, and no inherited GH_TOKEN/GITHUB_TOKEN`, @@ -845,12 +885,12 @@ async function resolvePushTarget( if (!allowedPush && context.blockFor(host)?.allowForkPush === true) { let apiEnv: NodeJS.ProcessEnv try { - apiEnv = forkEnv(request.proxy, request.account, host) + apiEnv = forkEnv(request.proxy, request.account, host, context.command) } catch (error) { if (request.account === undefined) { return { error: (error as Error).message } } - apiEnv = forkEnv(request.proxy, undefined, host) + apiEnv = forkEnv(request.proxy, undefined, host, context.command) } const { stdout } = await run( context.command, @@ -934,7 +974,12 @@ async function resolvePushTarget( ] try { const cleanEnv = withoutGitLocation({ - ...forkEnv(request.proxy, transport === 'ssh' ? undefined : request.account, host), + ...forkEnv( + request.proxy, + transport === 'ssh' ? undefined : request.account, + host, + context.command, + ), GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: process.platform === 'win32' ? 'NUL' : '/dev/null', GIT_TERMINAL_PROMPT: '0', @@ -1026,7 +1071,7 @@ async function openOne( cwd: repo, timeout: CREATE_TIMEOUT_MS, maxBuffer: 1 << 20, - env: forkEnv(request.proxy, request.account, host), + env: forkEnv(request.proxy, request.account, host, command), }) const match = /https:\/\/[^\s]+\/[^\s/]+\/[^\s/]+/.exec(stdout) if (match?.[0] !== undefined) { @@ -1241,14 +1286,14 @@ async function openOne( return { error: (error as Error).message } } try { - return await runAction(forkEnv(request.proxy, request.account, host)) + return await runAction(forkEnv(request.proxy, request.account, host, command)) } catch (error) { return { error: (error as Error).message } } } return personRun(host, request.repo, allowedByFork ? () => true : allowed, async host => - runAction(forkEnv(request.proxy, request.account, host)), + runAction(forkEnv(request.proxy, request.account, host, command)), ) } @@ -1270,7 +1315,7 @@ async function openOne( cwd: repo, timeout: CREATE_TIMEOUT_MS, maxBuffer: 1 << 20, - env: forkEnv(request.proxy, request.account, host), + env: forkEnv(request.proxy, request.account, host, command), }, ) let answer: unknown = null @@ -1317,7 +1362,7 @@ async function openOne( cwd: repo, timeout: CREATE_TIMEOUT_MS, maxBuffer: 1 << 20, - env: forkEnv(request.proxy, request.account, host), + env: forkEnv(request.proxy, request.account, host, command), }, ).then(({ stdout }) => pullRequestUrl(stdout) ?? { number: request.number }) return request.body === undefined ? invoke() : withBodyFile(request.body, invoke) @@ -1357,7 +1402,7 @@ async function openOne( cwd: repo, timeout: CREATE_TIMEOUT_MS, maxBuffer: 1 << 20, - env: forkEnv(request.proxy, request.account, host), + env: forkEnv(request.proxy, request.account, host, command), }, ).then(({ stdout }) => { const match = /https:\/\/[^\s]+\/pull\/\d+(?:#pullrequestreview-\d+)?/.exec(stdout) @@ -1411,8 +1456,8 @@ async function openOne( maxBuffer: 1 << 20, env: target === undefined - ? hostEnv(request.proxy, request.account) - : forkEnv(request.proxy, request.account, 'github.com'), + ? hostEnv(request.proxy, request.account, command) + : forkEnv(request.proxy, request.account, 'github.com', command), }, ) const found = pullRequestUrl(stdout) diff --git a/test/unit/host.test.ts b/test/unit/host.test.ts index 00b20b3b..744788c1 100644 --- a/test/unit/host.test.ts +++ b/test/unit/host.test.ts @@ -2031,7 +2031,11 @@ it('refuses an account directory logged in as another user', async () => { const dir = channelDir(join(repo, '.git')) const marker = join(root, 'ran') const command = join(root, 'not-gh') - writeFileSync(command, '#!/bin/sh\ntouch ' + marker + '\n', 'utf8') + writeFileSync( + command, + '#!/bin/sh\ncase "$1" in auth) exit 1;; esac\ntouch ' + marker + '\n', + 'utf8', + ) chmodSync(command, 0o755) const configDir = join(root, '.config', 'gh-alice') mkdirSync(configDir, { recursive: true }) @@ -2040,8 +2044,12 @@ it('refuses an account directory logged in as another user', async () => { 'github.com:\n users:\n mallory:\n oauth_token: not-a-secret\n user: mallory\n', 'utf8', ) - const previous = process.env['HOME'] + const previousHome = process.env['HOME'] + const previousToken = process.env['GH_TOKEN'] + const previousGithubToken = process.env['GITHUB_TOKEN'] process.env['HOME'] = root + delete process.env['GH_TOKEN'] + delete process.env['GITHUB_TOKEN'] try { const id = writeRequest(dir, { head: 'feat/ok', @@ -2054,10 +2062,74 @@ it('refuses an account directory logged in as another user', async () => { assert.match(readResult(dir, id)?.error ?? '', /logged in as .*mallory/u) assert.equal(existsSync(marker), false, 'the program did not run') } finally { - if (previous === undefined) { + if (previousToken === undefined) { + delete process.env['GH_TOKEN'] + } else { + process.env['GH_TOKEN'] = previousToken + } + if (previousGithubToken === undefined) { + delete process.env['GITHUB_TOKEN'] + } else { + process.env['GITHUB_TOKEN'] = previousGithubToken + } + if (previousHome === undefined) { delete process.env['HOME'] } else { - process.env['HOME'] = previous + process.env['HOME'] = previousHome + } + rmSync(root, { recursive: true, force: true }) + } +}) + +it('uses gh auth token --user when the active user differs', async () => { + const root = mkdtempSync(join(tmpdir(), 'host-broker-account-token-user-')) + const repo = join(root, 'checkout') + mkdirSync(join(repo, '.git'), { recursive: true }) + writeFileSync(join(repo, '.git', 'HEAD'), 'ref: refs/heads/main\n', 'utf8') + const dir = channelDir(join(repo, '.git')) + const envFile = join(root, 'env') + const command = join(root, 'not-gh') + writeFileSync( + command, + '#!/bin/sh\nif [ "$1" = auth ]; then echo token-from-gh; exit 0; fi\nprintf \'%s|%s\\n\' "$GH_TOKEN" "$GH_CONFIG_DIR" > ' + + envFile + + '\necho "https://github.com/acme/widget/pull/7"\n', + 'utf8', + ) + chmodSync(command, 0o755) + const configDir = join(root, '.config', 'gh-alice') + mkdirSync(configDir, { recursive: true }) + writeFileSync( + join(configDir, 'hosts.yml'), + 'github.com:\n users:\n mallory:\n oauth_token: not-a-secret\n user: mallory\n', + 'utf8', + ) + const previous = { + HOME: process.env['HOME'], + GH_TOKEN: process.env['GH_TOKEN'], + GITHUB_TOKEN: process.env['GITHUB_TOKEN'], + } + process.env['HOME'] = root + delete process.env['GH_TOKEN'] + delete process.env['GITHUB_TOKEN'] + try { + const id = writeRequest(dir, { + head: 'feat/ok', + base: 'main', + title: 'x', + body: '', + account: 'alice', + }) + assert.equal(await runHostBroker(['--repo', repo, '--command', command, '--once']), 0) + assert.equal(readResult(dir, id)?.error, undefined) + assert.equal(readFileSync(envFile, 'utf8').trim(), 'token-from-gh|' + configDir) + } finally { + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) { + delete process.env[key] + } else { + process.env[key] = value + } } rmSync(root, { recursive: true, force: true }) } From dc9899594363d7c6d9b2f8d1cc343e9299f4a1d7 Mon Sep 17 00:00:00 2001 From: JounQin Date: Thu, 12 Nov 2026 20:18:19 +0000 Subject: [PATCH 4/7] fix: preserve host gh args and empty token handling --- README.md | 3 +- packages/host/src/commands/host.ts | 58 +++++++++++++++++++----------- test/unit/host.test.ts | 4 +-- 3 files changed, 42 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 4f4fac93..b375e3d7 100644 --- a/README.md +++ b/README.md @@ -516,7 +516,8 @@ already exist. Selection is deterministic: the active account is not switched. 4. If none of those names the account, the request is refused. -This also refuses a directory symlinked to a config whose active account is somebody else. Any existing account directory can be named, so this is a selector rather than a +A directory symlinked to a config whose active account is somebody else is not used directly; +steps 2–4 decide whether the request can proceed. Any existing account directory can be named, so this is a selector rather than a gate. A request with no `--as-user` uses the broker route and does not select the host broker's login. The host broker never runs a shell, and the program it calls is configuration rather than a hard-coded `gh`: `--command /path/to/gh`, or diff --git a/packages/host/src/commands/host.ts b/packages/host/src/commands/host.ts index 60c78f77..284e71d3 100644 --- a/packages/host/src/commands/host.ts +++ b/packages/host/src/commands/host.ts @@ -654,9 +654,21 @@ function activeAccount(dir: string): string | undefined { return typeof active === 'string' && active !== '' ? active : undefined } +/** Whether the inherited environment names a usable token, not merely an empty variable. */ +function hasInheritedToken(env: NodeJS.ProcessEnv): boolean { + for (const key of ['GH_TOKEN', 'GITHUB_TOKEN']) { + const value = env[key] + if (typeof value === 'string' && value.trim() !== '') { + return true + } + } + return false +} + /** Ask gh for one named account's token without switching the active account. */ function accountToken( command: string, + extra: readonly string[], dir: string, host: string, account: string, @@ -668,12 +680,16 @@ function accountToken( delete env['GITHUB_ENTERPRISE_TOKEN'] delete env['GH_HOST'] try { - const token = execFileSync(command, ['auth', 'token', '--hostname', host, '--user', account], { - env, - encoding: 'utf8', - timeout: 5_000, - stdio: ['ignore', 'pipe', 'ignore'], - }).trim() + const token = execFileSync( + command, + [...extra, 'auth', 'token', '--hostname', host, '--user', account], + { + env, + encoding: 'utf8', + timeout: 5_000, + stdio: ['ignore', 'pipe', 'ignore'], + }, + ).trim() return token === '' ? undefined : token } catch { return undefined @@ -686,8 +702,9 @@ function forkEnv( account: string | undefined, host: string, command = 'gh', + extra: readonly string[] = [], ): NodeJS.ProcessEnv { - const env = hostEnv(proxy, account, command, host) + const env = hostEnv(proxy, account, command, host, extra) // gh chooses between GH_TOKEN and GH_ENTERPRISE_TOKEN by host; forcing GH_HOST is what keeps an // inherited token from selecting another instance. Named accounts already had their tokens removed. env['GH_HOST'] = host @@ -699,6 +716,7 @@ function hostEnv( account?: string, command = 'gh', host = 'github.com', + extra: readonly string[] = [], ): NodeJS.ProcessEnv { const env = { ...process.env } if (account !== undefined) { @@ -713,12 +731,12 @@ function hostEnv( delete env['GITHUB_ENTERPRISE_TOKEN'] delete env['GH_HOST'] env['GH_CONFIG_DIR'] = dir - } else if (env['GH_TOKEN'] !== undefined || env['GITHUB_TOKEN'] !== undefined) { + } else if (hasInheritedToken(env)) { // A token exported for this broker is the identity; keep it and use the directory for // settings only. env['GH_CONFIG_DIR'] = dir } else { - const token = accountToken(command, dir, host, account) + const token = accountToken(command, extra, dir, host, account) if (token === undefined) { throw new Error( `gh config for account ${JSON.stringify(account)} is logged in as ${JSON.stringify(active)}, and gh auth token --user ${account} found no token`, @@ -730,7 +748,7 @@ function hostEnv( delete env['GITHUB_ENTERPRISE_TOKEN'] env['GH_CONFIG_DIR'] = dir } - } else if (env['GH_TOKEN'] === undefined && env['GITHUB_TOKEN'] === undefined) { + } else if (!hasInheritedToken(env)) { throw new Error( `no gh config for account ${JSON.stringify(account)} at ${dir}, and no inherited GH_TOKEN/GITHUB_TOKEN`, ) @@ -885,12 +903,12 @@ async function resolvePushTarget( if (!allowedPush && context.blockFor(host)?.allowForkPush === true) { let apiEnv: NodeJS.ProcessEnv try { - apiEnv = forkEnv(request.proxy, request.account, host, context.command) + apiEnv = forkEnv(request.proxy, request.account, host, context.command, context.extra) } catch (error) { if (request.account === undefined) { return { error: (error as Error).message } } - apiEnv = forkEnv(request.proxy, undefined, host, context.command) + apiEnv = forkEnv(request.proxy, undefined, host, context.command, context.extra) } const { stdout } = await run( context.command, @@ -1071,7 +1089,7 @@ async function openOne( cwd: repo, timeout: CREATE_TIMEOUT_MS, maxBuffer: 1 << 20, - env: forkEnv(request.proxy, request.account, host, command), + env: forkEnv(request.proxy, request.account, host, command, extra), }) const match = /https:\/\/[^\s]+\/[^\s/]+\/[^\s/]+/.exec(stdout) if (match?.[0] !== undefined) { @@ -1286,14 +1304,14 @@ async function openOne( return { error: (error as Error).message } } try { - return await runAction(forkEnv(request.proxy, request.account, host, command)) + return await runAction(forkEnv(request.proxy, request.account, host, command, extra)) } catch (error) { return { error: (error as Error).message } } } return personRun(host, request.repo, allowedByFork ? () => true : allowed, async host => - runAction(forkEnv(request.proxy, request.account, host, command)), + runAction(forkEnv(request.proxy, request.account, host, command, extra)), ) } @@ -1315,7 +1333,7 @@ async function openOne( cwd: repo, timeout: CREATE_TIMEOUT_MS, maxBuffer: 1 << 20, - env: forkEnv(request.proxy, request.account, host, command), + env: forkEnv(request.proxy, request.account, host, command, extra), }, ) let answer: unknown = null @@ -1362,7 +1380,7 @@ async function openOne( cwd: repo, timeout: CREATE_TIMEOUT_MS, maxBuffer: 1 << 20, - env: forkEnv(request.proxy, request.account, host, command), + env: forkEnv(request.proxy, request.account, host, command, extra), }, ).then(({ stdout }) => pullRequestUrl(stdout) ?? { number: request.number }) return request.body === undefined ? invoke() : withBodyFile(request.body, invoke) @@ -1402,7 +1420,7 @@ async function openOne( cwd: repo, timeout: CREATE_TIMEOUT_MS, maxBuffer: 1 << 20, - env: forkEnv(request.proxy, request.account, host, command), + env: forkEnv(request.proxy, request.account, host, command, extra), }, ).then(({ stdout }) => { const match = /https:\/\/[^\s]+\/pull\/\d+(?:#pullrequestreview-\d+)?/.exec(stdout) @@ -1456,8 +1474,8 @@ async function openOne( maxBuffer: 1 << 20, env: target === undefined - ? hostEnv(request.proxy, request.account, command) - : forkEnv(request.proxy, request.account, 'github.com', command), + ? hostEnv(request.proxy, request.account, command, 'github.com', extra) + : forkEnv(request.proxy, request.account, 'github.com', command, extra), }, ) const found = pullRequestUrl(stdout) diff --git a/test/unit/host.test.ts b/test/unit/host.test.ts index 744788c1..4f2d20c3 100644 --- a/test/unit/host.test.ts +++ b/test/unit/host.test.ts @@ -2048,8 +2048,8 @@ it('refuses an account directory logged in as another user', async () => { const previousToken = process.env['GH_TOKEN'] const previousGithubToken = process.env['GITHUB_TOKEN'] process.env['HOME'] = root - delete process.env['GH_TOKEN'] - delete process.env['GITHUB_TOKEN'] + process.env['GH_TOKEN'] = '' + process.env['GITHUB_TOKEN'] = '' try { const id = writeRequest(dir, { head: 'feat/ok', From 62af432f1ed351119bd2efd498b41a2fef4ab9ab Mon Sep 17 00:00:00 2001 From: JounQin Date: Thu, 12 Nov 2026 20:24:14 +0000 Subject: [PATCH 5/7] fix: scope host account identity to the requested host --- README.md | 13 +++++++------ packages/host/src/commands/host.ts | 24 +++++++++++++++--------- test/unit/host.test.ts | 2 ++ 3 files changed, 24 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index b375e3d7..0e4183c3 100644 --- a/README.md +++ b/README.md @@ -508,12 +508,13 @@ selects `~/.config/gh-` on the host, matching the login exactly including directory once with `GH_CONFIG_DIR="$HOME/.config/gh-octocat" gh auth login`. The directory must already exist. Selection is deterministic: -1. If the directory's active `github.com` user is that login, it is used; inherited tokens are - cleared so they cannot override it. -2. If the active user differs, an inherited `GH_TOKEN`/`GITHUB_TOKEN` is used next, so a host - broker started from a shell that exports its identity works without a directory. -3. Otherwise `gh auth token --user ` supplies that account's token for this request only; - the active account is not switched. +1. If the directory's active user for the requested host is that login, it is used; inherited + tokens are cleared so they cannot override it. +2. If the active user differs, an inherited token for that host (`GH_TOKEN`/`GITHUB_TOKEN` for + github.com, the enterprise equivalents otherwise) is used next, so a host broker started from + a shell that exports its identity works without a directory. +3. Otherwise `gh auth token --hostname --user ` supplies that account's token for + this request only; the active account is not switched. 4. If none of those names the account, the request is refused. A directory symlinked to a config whose active account is somebody else is not used directly; diff --git a/packages/host/src/commands/host.ts b/packages/host/src/commands/host.ts index 284e71d3..02b96554 100644 --- a/packages/host/src/commands/host.ts +++ b/packages/host/src/commands/host.ts @@ -636,7 +636,7 @@ async function sweep( } /** The active github.com user in one gh config directory, when it can be read. */ -function activeAccount(dir: string): string | undefined { +function activeAccount(dir: string, host = 'github.com'): string | undefined { let parsed: unknown try { parsed = parseDocument(readFileSync(join(dir, 'hosts.yml'), 'utf8')).toJS() @@ -646,17 +646,23 @@ function activeAccount(dir: string): string | undefined { if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { return undefined } - const github = (parsed as Record)['github.com'] - if (typeof github !== 'object' || github === null || Array.isArray(github)) { + const entry = Object.entries(parsed as Record).find( + ([key]) => key.toLowerCase() === host.toLowerCase(), + )?.[1] + if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) { return undefined } - const active = (github as Record)['user'] + const active = (entry as Record)['user'] return typeof active === 'string' && active !== '' ? active : undefined } /** Whether the inherited environment names a usable token, not merely an empty variable. */ -function hasInheritedToken(env: NodeJS.ProcessEnv): boolean { - for (const key of ['GH_TOKEN', 'GITHUB_TOKEN']) { +function hasInheritedToken(env: NodeJS.ProcessEnv, host = 'github.com'): boolean { + const keys = + host.toLowerCase() === 'github.com' + ? ['GH_TOKEN', 'GITHUB_TOKEN'] + : ['GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN'] + for (const key of keys) { const value = env[key] if (typeof value === 'string' && value.trim() !== '') { return true @@ -722,7 +728,7 @@ function hostEnv( if (account !== undefined) { const dir = join(homedir(), '.config', `gh-${account}`) if (existsSync(dir) && statSync(dir).isDirectory()) { - const active = activeAccount(dir) + const active = activeAccount(dir, host) if (active === undefined || active.toLowerCase() === account.toLowerCase()) { // The directory is the selected account; inherited tokens must not override it. delete env['GH_TOKEN'] @@ -731,7 +737,7 @@ function hostEnv( delete env['GITHUB_ENTERPRISE_TOKEN'] delete env['GH_HOST'] env['GH_CONFIG_DIR'] = dir - } else if (hasInheritedToken(env)) { + } else if (hasInheritedToken(env, host)) { // A token exported for this broker is the identity; keep it and use the directory for // settings only. env['GH_CONFIG_DIR'] = dir @@ -748,7 +754,7 @@ function hostEnv( delete env['GITHUB_ENTERPRISE_TOKEN'] env['GH_CONFIG_DIR'] = dir } - } else if (!hasInheritedToken(env)) { + } else if (!hasInheritedToken(env, host)) { throw new Error( `no gh config for account ${JSON.stringify(account)} at ${dir}, and no inherited GH_TOKEN/GITHUB_TOKEN`, ) diff --git a/test/unit/host.test.ts b/test/unit/host.test.ts index 4f2d20c3..6034e62e 100644 --- a/test/unit/host.test.ts +++ b/test/unit/host.test.ts @@ -2155,10 +2155,12 @@ it('uses an inherited GH_TOKEN when no account directory exists', async () => { HOME: process.env['HOME'], GH_TOKEN: process.env['GH_TOKEN'], GITHUB_TOKEN: process.env['GITHUB_TOKEN'], + GH_CONFIG_DIR: process.env['GH_CONFIG_DIR'], } process.env['HOME'] = root process.env['GH_TOKEN'] = 'inherited-token' delete process.env['GITHUB_TOKEN'] + delete process.env['GH_CONFIG_DIR'] try { const id = writeRequest(dir, { head: 'feat/ok', From 2bb1e31e157f02475ff3f48c4fbcb592e8f4d135 Mon Sep 17 00:00:00 2001 From: JounQin Date: Thu, 12 Nov 2026 20:37:44 +0000 Subject: [PATCH 6/7] fix: use host-specific gh token variables --- README.md | 5 +++-- packages/host/src/commands/host.ts | 18 ++++++++++++------ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 0e4183c3..93f945da 100644 --- a/README.md +++ b/README.md @@ -511,8 +511,9 @@ already exist. Selection is deterministic: 1. If the directory's active user for the requested host is that login, it is used; inherited tokens are cleared so they cannot override it. 2. If the active user differs, an inherited token for that host (`GH_TOKEN`/`GITHUB_TOKEN` for - github.com, the enterprise equivalents otherwise) is used next, so a host broker started from - a shell that exports its identity works without a directory. + github.com and `*.ghe.com`, the enterprise equivalents for GitHub Enterprise Server) is used + next, so a host broker started from a shell that exports its identity works without a + directory. 3. Otherwise `gh auth token --hostname --user ` supplies that account's token for this request only; the active account is not switched. 4. If none of those names the account, the request is refused. diff --git a/packages/host/src/commands/host.ts b/packages/host/src/commands/host.ts index 02b96554..c7b16402 100644 --- a/packages/host/src/commands/host.ts +++ b/packages/host/src/commands/host.ts @@ -657,11 +657,16 @@ function activeAccount(dir: string, host = 'github.com'): string | undefined { } /** Whether the inherited environment names a usable token, not merely an empty variable. */ +/** Whether a host uses GH_TOKEN (github.com and Enterprise Cloud) or GH_ENTERPRISE_TOKEN (GHES). */ +function dotComHost(host: string): boolean { + const lower = host.toLowerCase() + return lower === 'github.com' || lower.endsWith('.ghe.com') +} + function hasInheritedToken(env: NodeJS.ProcessEnv, host = 'github.com'): boolean { - const keys = - host.toLowerCase() === 'github.com' - ? ['GH_TOKEN', 'GITHUB_TOKEN'] - : ['GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN'] + const keys = dotComHost(host) + ? ['GH_TOKEN', 'GITHUB_TOKEN'] + : ['GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN'] for (const key of keys) { const value = env[key] if (typeof value === 'string' && value.trim() !== '') { @@ -748,15 +753,16 @@ function hostEnv( `gh config for account ${JSON.stringify(account)} is logged in as ${JSON.stringify(active)}, and gh auth token --user ${account} found no token`, ) } - env['GH_TOKEN'] = token + delete env['GH_TOKEN'] delete env['GITHUB_TOKEN'] delete env['GH_ENTERPRISE_TOKEN'] delete env['GITHUB_ENTERPRISE_TOKEN'] + env[dotComHost(host) ? 'GH_TOKEN' : 'GH_ENTERPRISE_TOKEN'] = token env['GH_CONFIG_DIR'] = dir } } else if (!hasInheritedToken(env, host)) { throw new Error( - `no gh config for account ${JSON.stringify(account)} at ${dir}, and no inherited GH_TOKEN/GITHUB_TOKEN`, + `no gh config for account ${JSON.stringify(account)} at ${dir}, and no inherited token for ${host}`, ) } // Without an account directory the inherited token is the identity. gh gives GH_TOKEN priority From b26982896a028f9d2f46bea2bdb04c35f23fdd49 Mon Sep 17 00:00:00 2001 From: JounQin Date: Thu, 12 Nov 2026 21:20:52 +0000 Subject: [PATCH 7/7] fix: pass extra args in push credentials and pin token test --- packages/host/src/commands/host.ts | 1 + test/unit/host.test.ts | 13 +++++++++++++ 2 files changed, 14 insertions(+) diff --git a/packages/host/src/commands/host.ts b/packages/host/src/commands/host.ts index c7b16402..ff04de60 100644 --- a/packages/host/src/commands/host.ts +++ b/packages/host/src/commands/host.ts @@ -1009,6 +1009,7 @@ async function resolvePushTarget( transport === 'ssh' ? undefined : request.account, host, context.command, + context.extra, ), GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: process.platform === 'win32' ? 'NUL' : '/dev/null', diff --git a/test/unit/host.test.ts b/test/unit/host.test.ts index 6034e62e..a2572d13 100644 --- a/test/unit/host.test.ts +++ b/test/unit/host.test.ts @@ -1723,6 +1723,12 @@ describe('the host action route', () => { status: 200, headers: { 'content-type': 'application/json' }, })) as typeof fetch + const previousTokens = { + GH_TOKEN: process.env['GH_TOKEN'], + GITHUB_TOKEN: process.env['GITHUB_TOKEN'], + } + delete process.env['GH_TOKEN'] + delete process.env['GITHUB_TOKEN'] try { const id = writeRequest(dir, { kind: 'action', @@ -1738,6 +1744,13 @@ describe('the host action route', () => { assert.match(readResult(dir, id)?.error ?? '', /no gh config for account/u) } finally { globalThis.fetch = originalFetch + for (const [key, value] of Object.entries(previousTokens)) { + if (value === undefined) { + delete process.env[key] + } else { + process.env[key] = value + } + } rmSync(root, { recursive: true, force: true }) } })