Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/gh-token-env.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"gcb-host": patch
---

Centralize the gh token environment variables and host classification. GHES action execution now
uses `GH_ENTERPRISE_TOKEN` instead of the ignored `GH_TOKEN`, and the host account selectors share
one token-key helper.
28 changes: 5 additions & 23 deletions packages/host/src/commands/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ import {
import { parseDocument } from 'yaml'

import { loadConfig, resolveConfigPath } from '../config.ts'
import { clearInheritedTokens, setHostToken, tokenKeys } from '../gh-env.ts'
import { applyProxyChoice, fetcherFor, parseProxy, type ProxyChoice } from '../http.ts'
import { hostConfig, parseAllowEntry, repoAllowed } from '../policy.ts'
import { isForkOfRepository, isPublicRepository } from '../public-repo.ts'
Expand Down Expand Up @@ -657,17 +658,8 @@ 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 = dotComHost(host)
? ['GH_TOKEN', 'GITHUB_TOKEN']
: ['GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN']
for (const key of keys) {
for (const key of tokenKeys(host)) {
const value = env[key]
if (typeof value === 'string' && value.trim() !== '') {
return true
Expand All @@ -685,10 +677,7 @@ function accountToken(
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']
clearInheritedTokens(env)
delete env['GH_HOST']
try {
const token = execFileSync(
Expand Down Expand Up @@ -736,10 +725,7 @@ function hostEnv(
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']
delete env['GITHUB_TOKEN']
delete env['GH_ENTERPRISE_TOKEN']
delete env['GITHUB_ENTERPRISE_TOKEN']
clearInheritedTokens(env)
delete env['GH_HOST']
env['GH_CONFIG_DIR'] = dir
} else if (hasInheritedToken(env, host)) {
Expand All @@ -753,11 +739,7 @@ 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`,
)
}
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
setHostToken(env, host, token)
env['GH_CONFIG_DIR'] = dir
}
} else if (!hasInheritedToken(env, host)) {
Expand Down
33 changes: 33 additions & 0 deletions packages/host/src/gh-env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* The two gh token families and the host classification that chooses between them.
*
* Github.com and GitHub Enterprise Cloud (`*.ghe.com`) use `GH_TOKEN`/`GITHUB_TOKEN`; GitHub
* Enterprise Server uses `GH_ENTERPRISE_TOKEN`/`GITHUB_ENTERPRISE_TOKEN`.
*/

const DOT_COM_TOKEN_KEYS = ['GH_TOKEN', 'GITHUB_TOKEN'] as const
const ENTERPRISE_TOKEN_KEYS = ['GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN'] as const

/** Whether the host uses the github.com token family, including Enterprise Cloud. */
export function dotComHost(host: string): boolean {
const lower = host.toLowerCase()
return lower === 'github.com' || lower.endsWith('.ghe.com')
}

/** The token environment variables gh reads for one host. */
export function tokenKeys(host: string): readonly [string, string] {
return dotComHost(host) ? DOT_COM_TOKEN_KEYS : ENTERPRISE_TOKEN_KEYS
}

/** Remove every inherited gh token, leaving the config directory or a new token to decide. */
export function clearInheritedTokens(env: NodeJS.ProcessEnv): void {
for (const key of [...DOT_COM_TOKEN_KEYS, ...ENTERPRISE_TOKEN_KEYS]) {
delete env[key]
}
}

/** Put one token in the variable gh reads for that host. */
export function setHostToken(env: NodeJS.ProcessEnv, host: string, token: string): void {
clearInheritedTokens(env)
env[tokenKeys(host)[0]] = token
}
3 changes: 2 additions & 1 deletion packages/host/src/gh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { StringDecoder } from 'node:string_decoder'

import { apiBodyJson, buildGhArgv, getGhAction, type ActionValues } from 'gcb-core'

import { setHostToken } from './gh-env.ts'
import { applyProxyChoice, PROXY_ENV_KEYS } from './http.ts'

/** The default stdout/stderr ceiling, in bytes per stream. */
Expand Down Expand Up @@ -236,7 +237,7 @@ export async function runGhAction(options: GhRunOptions): Promise<GhRunResult> {
}
}
if (!usesJq) {
env.GH_TOKEN = options.token
setHostToken(env, host, options.token)
}

const action = getGhAction(options.action)
Expand Down
16 changes: 16 additions & 0 deletions test/unit/gh.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,22 @@ describe('runGhAction', { skip: onWindows }, () => {
assert.doesNotMatch(result.stdout, /host-token/)
})

it('uses the enterprise token variable for a GHES host', async () => {
const gh = shim('printf "TOKEN=%s\\nGH=%s\\n" "$GH_ENTERPRISE_TOKEN" "$GH_TOKEN"')
const result = await runGhAction({
action: 'pr:view',
values: { number: 7 },
repo: 'acme/widget',
host: 'ghe.example',
token: 'app-token',
ghPath: gh,
env: { PATH: process.env.PATH },
})
assert.equal(result.code, 0)
assert.match(result.stdout, /TOKEN=app-token/u)
assert.match(result.stdout, /GH=/u)
})

it('refuses an issue-only action on a pull request', async () => {
const gh = shim('if [ "$1" = "api" ]; then echo true; exit 0; fi; echo SHOULD_NOT_RUN')
await assert.rejects(
Expand Down
Loading