Fix GitHub Enterprise host identity loss across PR/work-item paths

- Thread `host` through mobile PR RPC params, IPC work-item lookups, and
  RPC schemas so GHES identity survives the renderer/mobile/main boundary
  instead of silently falling back to a same-named github.com repo.
- Qualify `--repo`/`-R` args for github.com too (not just GHES), since
  gh resolves bare shorthand against a process-level GH_HOST that can
  redirect pinned github.com commands.
- Cache `getOriginGitHubApiRepository` to avoid a per-call uncached
  `git remote get-url` round trip on connection-backed repos.
- Add a local-fork fallback in `getWorkItemDetails` so PRs living on a
  base repo (not visible via the origin slug) still resolve via cwd.
- Centralize the github.com-vs-GHES host predicate in
  `isDefaultGitHubHost` so cache keys, quota scoping, and identity
  checks can't drift out of sync.
This commit is contained in:
Jinjing
2026-07-19 18:03:48 -07:00
parent 8ad7686fe3
commit bcb895bf43
28 changed files with 288 additions and 79 deletions
+17 -2
View File
@@ -62,6 +62,14 @@ vi.mock('./github-enterprise-repository', () => ({
import { createGitHubPullRequest } from './client'
import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository'
// The origin-repository cache is module-level state; reset it so slugs
// resolved by one test cannot leak into the next.
beforeEach(() => {
_resetOriginGitHubApiRepositoryCache()
})
describe('createGitHubPullRequest', () => {
beforeEach(() => {
ghExecFileAsyncMock.mockReset()
@@ -303,7 +311,12 @@ describe('createGitHubPullRequest', () => {
url: 'https://github.com/acme/widgets/pull/45'
})
expect(getOwnerRepoForRemoteMock).toHaveBeenCalledWith('/remote/repo-root', 'origin', 'ssh-1')
expect(getOwnerRepoForRemoteMock).toHaveBeenCalledWith(
'/remote/repo-root',
'origin',
'ssh-1',
{}
)
const [args, options] = ghExecFileAsyncMock.mock.calls[0]
expect(args).toEqual(
expect.arrayContaining([
@@ -461,7 +474,9 @@ describe('createGitHubPullRequest', () => {
'--json',
'number,url'
],
{ cwd: '/repo-root' }
// Why: dotcom slugs resolve with host:'github.com' so creation stays
// pinned against a process-level GH_HOST.
{ cwd: '/repo-root', host: 'github.com' }
])
})
@@ -45,6 +45,14 @@ vi.mock('./github-enterprise-repository', () => ({
import { setPRFileViewed } from './client'
import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository'
// The origin-repository cache is module-level state; reset it so slugs
// resolved by one test cannot leak into the next.
beforeEach(() => {
_resetOriginGitHubApiRepositoryCache()
})
describe('setPRFileViewed', () => {
beforeEach(() => {
ghExecFileAsyncMock.mockReset()
+8
View File
@@ -80,6 +80,14 @@ vi.mock('./rate-limit', () => ({
import { getPRChecks, rerunPRChecks, _resetOwnerRepoCache } from './client'
import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository'
// The origin-repository cache is module-level state; reset it so slugs
// resolved by one test cannot leak into the next.
beforeEach(() => {
_resetOriginGitHubApiRepositoryCache()
})
function graphQLChecksResponse({
contexts = [],
checkSuites = [],
@@ -122,6 +122,14 @@ import {
updatePRTitle
} from './client'
import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository'
// The origin-repository cache is module-level state; reset it so slugs
// resolved by one test cannot leak into the next.
beforeEach(() => {
_resetOriginGitHubApiRepositoryCache()
})
describe('GitHub PR local runtime routing', () => {
beforeEach(() => {
execFileAsyncMock.mockReset()
+14 -3
View File
@@ -20,7 +20,7 @@ const {
getOwnerRepoForRemoteMock: vi.fn(),
resolveIssueSourceMock: vi.fn(),
gitExecFileAsyncMock: vi.fn(),
rateLimitGuardMock: vi.fn(() => ({ blocked: false })),
rateLimitGuardMock: vi.fn((_bucket?: unknown) => ({ blocked: false })),
noteRateLimitSpendMock: vi.fn(),
acquireMock: vi.fn(),
releaseMock: vi.fn()
@@ -65,8 +65,11 @@ vi.mock('./rate-limit', () => ({
rateLimitGuard: rateLimitGuardMock,
noteRateLimitSpend: noteRateLimitSpendMock,
getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })),
repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })),
noteRepositoryRateLimitSpend: vi.fn(),
// Mirror production: shared-scope calls delegate to the global guard/spend.
repositoryRateLimitGuard: vi.fn((_repo: unknown, bucket: string) => rateLimitGuardMock(bucket)),
noteRepositoryRateLimitSpend: vi.fn((_repo: unknown, bucket: string, cost?: number) =>
noteRateLimitSpendMock(bucket, cost)
),
spendsSharedGitHubComQuota: () => true
}))
@@ -79,6 +82,14 @@ import {
import { _resetGhCwdRepoNegativeCache } from './gh-cwd-repo-negative-cache'
import { GITHUB_WORK_ITEMS_QUERY_MAX_BYTES } from '../../shared/github-work-items-query-bounds'
import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository'
// The origin-repository cache is module-level state; reset it so slugs
// resolved by one test cannot leak into the next.
beforeEach(() => {
_resetOriginGitHubApiRepositoryCache()
})
describe('listWorkItems', () => {
beforeEach(() => {
execFileAsyncMock.mockReset()
+8
View File
@@ -135,6 +135,14 @@ import {
import { __resetPRConflictSummaryCachesForTests } from './conflict-summary'
import { resetMergedPRCommitMembershipCacheForTest } from './merged-pr-commit-membership'
import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository'
// The origin-repository cache is module-level state; reset it so slugs
// resolved by one test cannot leak into the next.
beforeEach(() => {
_resetOriginGitHubApiRepositoryCache()
})
describe('checkOrcaStarred', () => {
beforeEach(() => {
execFileAsyncMock.mockReset()
+14 -18
View File
@@ -86,7 +86,6 @@ import {
rememberGhCwdResolutionFailure
} from './gh-cwd-repo-negative-cache'
import type { GitHubRepoContext } from './github-repository-identity'
import { getEnterpriseGitHubRepoSlug } from './github-enterprise-repository'
import {
getOriginGitHubApiRepository,
githubHostExecOptions,
@@ -118,7 +117,6 @@ import {
import { mapGraphQLReactionGroups, type GitHubGraphQLReactionGroup } from './comment-reactions'
import {
getRateLimit,
noteRateLimitSpend,
noteRepositoryRateLimitSpend,
rateLimitGuard,
repositoryRateLimitGuard,
@@ -1516,7 +1514,7 @@ async function countWorkItemsForQuery(
)
// Why: over-counts gh cache hits, which is the safe direction — the search
// bucket is only 30/min and the next probe corrects the estimate.
noteRateLimitSpend('search')
noteRepositoryRateLimitSpend(ownerRepo, 'search', 1, localGitOptions)
return Number.parseInt(stdout.trim(), 10) || 0
}
@@ -1576,8 +1574,11 @@ export async function countWorkItems(
// 30/min, so a multi-repo Tasks page must stop counting when the budget is
// gone instead of converting the remaining repos into 403 spawns. getRateLimit
// is 30s-cached and single-flight, so priming here is one spawn per window.
await getRateLimit()
if (rateLimitGuard('search').blocked) {
// Only shared github.com traffic consults the snapshot; other scopes bypass.
if (spendsSharedGitHubComQuota(ownerRepo, localGitOptions)) {
await getRateLimit()
}
if (repositoryRateLimitGuard(ownerRepo, 'search', localGitOptions).blocked) {
return 0
}
@@ -1882,18 +1883,13 @@ export async function createGitHubPullRequest(
}
}
// Why: github.com-only slug parsing returns null for GHES, so fall back to the
// enterprise resolver (gh-authenticated custom host) before giving up (#8312).
// Creation targets origin: the head branch is unqualified, so `gh pr create`
// must run against the repo the branch was pushed to, not the fork parent
// (getOwnerRepo became upstream-first for PR reads in #7331).
const ownerRepo =
(await getOwnerRepoForRemote(
repoPath,
'origin',
connectionId,
...hostedReviewLocalGitOptionArgs(options)
)) ?? (await getEnterpriseGitHubRepoSlug(repoPath, connectionId, options))
// Why: creation targets the origin that owns the unqualified head branch;
// the shared resolver also preserves its execution host (#7331, #8312).
const ownerRepo = await getOriginGitHubApiRepository(
repoPath,
connectionId,
getHostedReviewLocalGitOptions(options)
)
if (!ownerRepo) {
return {
ok: false,
@@ -4371,7 +4367,7 @@ export async function getPRComments(
['pr', 'view', String(prNumber), '--json', 'comments'],
ghOptions
)
noteRateLimitSpend('graphql')
noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, ghOptions)
const data = JSON.parse(stdout) as {
comments: {
author: { login: string }
+56 -6
View File
@@ -1,21 +1,71 @@
import type { GitHubOwnerRepo } from '../../shared/types'
import { getOwnerRepo, type LocalGitExecOptions } from './gh-utils'
import { isDefaultGitHubHost } from '../../shared/github-repository-identity-key'
import { getOwnerRepoForRemote, type LocalGitExecOptions } from './gh-utils'
import { getEnterpriseGitHubRepoSlug } from './github-enterprise-repository'
export type GitHubApiRepository = GitHubOwnerRepo
// Why: the enterprise branch spawns an uncached `git remote get-url` (an SSH
// round trip on connection-backed repos) — hot paths like per-file contents
// and viewed-state toggles resolve per call, so cache like ownerRepoCache does.
const ORIGIN_REPO_CACHE_TTL_MS = 30_000
const originRepoCache = new Map<string, { value: GitHubApiRepository | null; expiresAt: number }>()
const originRepoInFlight = new Map<string, Promise<GitHubApiRepository | null>>()
function originRepoCacheKey(
repoPath: string,
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): string {
return `${connectionId ?? 'local'}\0${localGitOptions.wslDistro ?? ''}\0${repoPath}`
}
/** @internal - exposed for tests only */
export function _resetOriginGitHubApiRepositoryCache(): void {
originRepoCache.clear()
originRepoInFlight.clear()
}
export async function getOriginGitHubApiRepository(
repoPath: string,
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<GitHubApiRepository | null> {
const ownerRepo = await getOwnerRepo(repoPath, connectionId, localGitOptions)
// Why: this resolver represents the checkout origin; generic PR resolution
// prefers upstream on fork checkouts (#7331).
const ownerRepo = await getOwnerRepoForRemote(
repoPath,
'origin',
connectionId,
localGitOptions
)
if (ownerRepo) {
return { ...ownerRepo, host: 'github.com' }
}
const enterpriseOptions =
Object.keys(localGitOptions).length > 0 ? { localGitExecOptions: localGitOptions } : {}
return getEnterpriseGitHubRepoSlug(repoPath, connectionId, enterpriseOptions)
const cacheKey = originRepoCacheKey(repoPath, connectionId, localGitOptions)
const cached = originRepoCache.get(cacheKey)
if (cached && cached.expiresAt > Date.now()) {
return cached.value
}
const inFlight = originRepoInFlight.get(cacheKey)
if (inFlight) {
return inFlight
}
const probe = (async () => {
const enterpriseOptions =
Object.keys(localGitOptions).length > 0 ? { localGitExecOptions: localGitOptions } : {}
const slug = await getEnterpriseGitHubRepoSlug(repoPath, connectionId, enterpriseOptions)
originRepoCache.set(cacheKey, { value: slug, expiresAt: Date.now() + ORIGIN_REPO_CACHE_TTL_MS })
return slug
})()
originRepoInFlight.set(cacheKey, probe)
try {
return await probe
} finally {
if (originRepoInFlight.get(cacheKey) === probe) {
originRepoInFlight.delete(cacheKey)
}
}
}
export async function resolveGitHubApiRepository(
@@ -46,7 +96,7 @@ export async function resolveGitHubApiRepository(
}
export function isGitHubDotComRepository(repository: GitHubApiRepository): boolean {
return !repository.host || repository.host.toLowerCase() === 'github.com'
return isDefaultGitHubHost(repository.host)
}
// Why: the gh runner host-qualifies argv from `options.host`, so every known
+8
View File
@@ -37,6 +37,14 @@ import {
updateIssue
} from './issues'
import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository'
// The origin-repository cache is module-level state; reset it so slugs
// resolved by one test cannot leak into the next.
beforeEach(() => {
_resetOriginGitHubApiRepositoryCache()
})
describe('issue source operations', () => {
beforeEach(() => {
ghExecFileAsyncMock.mockReset()
+2 -2
View File
@@ -18,6 +18,7 @@ import type {
GitHubRateLimitBucket,
GitHubRateLimitSnapshot
} from '../../shared/types'
import { isDefaultGitHubHost } from '../../shared/github-repository-identity-key'
import { acquire, release } from './gh-utils'
import { ghExecFileAsync } from '../git/runner'
import {
@@ -168,8 +169,7 @@ export function spendsSharedGitHubComQuota(
repository: { host?: string } | null | undefined,
executionOptions?: { wslDistro?: string }
): boolean {
const host = repository?.host
return (!host || host.toLowerCase() === 'github.com') && !executionOptions?.wslDistro
return isDefaultGitHubHost(repository?.host) && !executionOptions?.wslDistro
}
export function repositoryRateLimitGuard(
@@ -61,6 +61,14 @@ vi.mock('./rate-limit', () => ({
import { getWorkItemDetails } from './work-item-details'
import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository'
// The origin-repository cache is module-level state; reset it so slugs
// resolved by one test cannot leak into the next.
beforeEach(() => {
_resetOriginGitHubApiRepositoryCache()
})
describe('getWorkItemDetails PR file viewed state', () => {
beforeEach(() => {
ghExecFileAsyncMock.mockReset()
@@ -48,6 +48,14 @@ vi.mock('./rate-limit', () => ({
import { getWorkItemDetails } from './work-item-details'
import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository'
// The origin-repository cache is module-level state; reset it so slugs
// resolved by one test cannot leak into the next.
beforeEach(() => {
_resetOriginGitHubApiRepositoryCache()
})
function pullRequestItem(number: number, title: string): Record<string, unknown> {
return {
id: `pr:${number}`,
@@ -78,6 +78,14 @@ vi.mock('./rate-limit', () => ({
import { getPRFileContents, getWorkItemDetails } from './work-item-details'
import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository'
// The origin-repository cache is module-level state; reset it so slugs
// resolved by one test cannot leak into the next.
beforeEach(() => {
_resetOriginGitHubApiRepositoryCache()
})
describe('getWorkItemDetails', () => {
beforeEach(() => {
ghExecFileAsyncMock.mockReset()
+14 -2
View File
@@ -1086,14 +1086,15 @@ export async function getWorkItemDetails(
: await getOriginGitHubApiRepository(repoPath, connectionId, localGitOptions)
// Why: SSH-backed gh runs without a cwd, so an unresolved PR repository must
// not fall through to gh's default host and show a same-number github.com PR.
if (connectionId && type === 'pr' && !originApiRepository) {
// Covers type-less lookups too — they can also reach the PR path below.
if (connectionId && type !== 'issue' && !originApiRepository) {
return null
}
// Why: connection-backed repos have no local cwd for gh to inspect, so GHES
// must use its host-qualified repository identity during the initial lookup.
const useExplicitEnterpriseRepository =
type === 'pr' && originApiRepository !== null && !isGitHubDotComRepository(originApiRepository)
const item: Omit<GitHubWorkItem, 'repoId'> | null = useExplicitEnterpriseRepository
let item: Omit<GitHubWorkItem, 'repoId'> | null = useExplicitEnterpriseRepository
? await getWorkItemByOwnerRepo(
repoPath,
originApiRepository,
@@ -1109,6 +1110,17 @@ export async function getWorkItemDetails(
connectionId,
...localGitOptionArgs(localGitOptions)
)
if (!item && useExplicitEnterpriseRepository && !connectionId) {
// Why: on a local fork checkout the PR lives on the base repo, which the
// origin slug can't see — the cwd lets gh resolve the actual remote.
item = await getWorkItem(
repoPath,
number,
type,
connectionId,
...localGitOptionArgs(localGitOptions)
)
}
if (!item) {
return null
}