fix(gitlab): bound and coalesce auth probes (#9476)

This commit is contained in:
OrcaWin
2026-07-19 16:54:31 -07:00
committed by GitHub
parent 245d79cc8c
commit b320bcb374
10 changed files with 427 additions and 138 deletions
+9 -13
View File
@@ -248,13 +248,9 @@ export async function getProjectSlug(
connectionId?: string | null,
options: HostedReviewExecutionOptions = {}
): Promise<ProjectRef | null> {
const knownHosts = await getGlabKnownHosts(connectionId)
return getProjectRef(
repoPath,
knownHosts,
connectionId,
...hostedReviewLocalGitOptionArgs(options)
)
const localGitArgs = hostedReviewLocalGitOptionArgs(options)
const knownHosts = await getGlabKnownHosts(connectionId, localGitArgs[0])
return getProjectRef(repoPath, knownHosts, connectionId, ...localGitArgs)
}
/**
@@ -268,9 +264,9 @@ export async function getMergeRequest(
connectionId?: string | null,
options: HostedReviewExecutionOptions = {}
): Promise<MRInfo | null> {
const knownHosts = await getGlabKnownHosts(connectionId)
const localGitArgs = hostedReviewLocalGitOptionArgs(options)
const localGitOptions = localGitArgs[0] ?? {}
const knownHosts = await getGlabKnownHosts(connectionId, localGitOptions)
const projectRef = await getProjectRef(repoPath, knownHosts, connectionId, ...localGitArgs)
await acquire()
try {
@@ -323,9 +319,9 @@ export async function getMergeRequestForBranch(
if (!branchName && linkedMRIid == null) {
return null
}
const knownHosts = await getGlabKnownHosts(connectionId)
const localGitArgs = hostedReviewLocalGitOptionArgs(options)
const localGitOptions = localGitArgs[0] ?? {}
const knownHosts = await getGlabKnownHosts(connectionId, localGitOptions)
const projectRef = await getProjectRef(repoPath, knownHosts, connectionId, ...localGitArgs)
if (!projectRef) {
return null
@@ -425,7 +421,7 @@ export async function listMergeRequests(
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<ListMergeRequestsResult> {
const knownHosts = await getGlabKnownHosts(connectionId)
const knownHosts = await getGlabKnownHosts(connectionId, localGitOptions)
// Why: MRs sit on `origin` in the fork model (the user's fork is where
// they push branches and submit MRs). Mirror github's `getOwnerRepo`
// call site by going through the upstream/origin preference resolver
@@ -623,7 +619,7 @@ export async function listWorkItems(
localGitOptions: LocalGitExecOptions = {}
): Promise<GitLabPagedResult<GitLabWorkItem>> {
const issueState = mrStateToIssueState(state)
const knownHosts = await getGlabKnownHosts(connectionId)
const knownHosts = await getGlabKnownHosts(connectionId, localGitOptions)
const { source: projectRef } = await resolveIssueSource(
repoPath,
preference,
@@ -759,7 +755,7 @@ export async function listTodos(
): Promise<GitLabTodo[]> {
const projectRef = await getProjectRef(
repoPath,
await getGlabKnownHosts(connectionId),
await getGlabKnownHosts(connectionId, localGitOptions),
connectionId,
localGitOptions
)
@@ -838,7 +834,7 @@ async function withProjectRef<T>(
await resolveIssueSource(
repoPath,
preference,
await getGlabKnownHosts(connectionId),
await getGlabKnownHosts(connectionId, localGitOptions),
connectionId,
localGitOptions
)
+110
View File
@@ -0,0 +1,110 @@
import { glabExecFileAsync } from '../git/runner'
import { getSshGitProviderGeneration } from '../providers/ssh-git-dispatch'
import { DEFAULT_GITLAB_HOSTS, normalizeGitLabHost } from './project-ref-parser'
export type LocalGitExecOptions = {
wslDistro?: string
}
const GLAB_KNOWN_HOSTS_TIMEOUT_MS = 10_000
const knownHostsCacheByExecutionContext = new Map<string, readonly string[]>()
const knownHostsInFlightByExecutionContext = new Map<string, Promise<readonly string[]>>()
function knownHostsExecutionKey(
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): string {
if (connectionId) {
// Why: reconnecting can replace the SSH/relay execution host under the same id.
return `connection:${connectionId}:${getSshGitProviderGeneration(connectionId)}`
}
return localGitOptions.wslDistro ? `wsl:${localGitOptions.wslDistro}` : 'native'
}
/** @internal - exposed for tests only */
export function _resetKnownHostsCache(): void {
knownHostsCacheByExecutionContext.clear()
knownHostsInFlightByExecutionContext.clear()
}
export function rememberGlabKnownHost(
host: string,
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): void {
const normalizedHost = normalizeGitLabHost(host)
const key = knownHostsExecutionKey(connectionId, localGitOptions)
const cached = knownHostsCacheByExecutionContext.get(key)
if (!cached || cached.map(normalizeGitLabHost).includes(normalizedHost)) {
return
}
knownHostsCacheByExecutionContext.set(key, [...cached, normalizedHost])
}
export async function getGlabKnownHosts(
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<readonly string[]> {
const key = knownHostsExecutionKey(connectionId, localGitOptions)
const cached = knownHostsCacheByExecutionContext.get(key)
if (cached) {
return cached
}
const inFlight = knownHostsInFlightByExecutionContext.get(key)
if (inFlight) {
return inFlight
}
const probe = probeGlabKnownHosts(key, connectionId, localGitOptions)
knownHostsInFlightByExecutionContext.set(key, probe)
try {
return await probe
} finally {
if (knownHostsInFlightByExecutionContext.get(key) === probe) {
knownHostsInFlightByExecutionContext.delete(key)
}
}
}
async function probeGlabKnownHosts(
key: string,
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<readonly string[]> {
try {
// Why: auth config belongs to the executing host; do not share native, WSL,
// or reconnected SSH/relay results, and bound an otherwise global probe.
const { stdout, stderr } = await glabExecFileAsync(['auth', 'status'], {
timeout: GLAB_KNOWN_HOSTS_TIMEOUT_MS,
...(!connectionId && localGitOptions.wslDistro
? { wslDistro: localGitOptions.wslDistro }
: {})
})
const hosts = parseGlabAuthStatusHosts(`${stdout}\n${stderr}`)
const merged = Array.from(new Set([...DEFAULT_GITLAB_HOSTS, ...hosts]))
knownHostsCacheByExecutionContext.set(key, merged)
return merged
} catch {
// Keep failures uncached so auth or tunnel recovery is discovered later.
return [...DEFAULT_GITLAB_HOSTS]
}
}
export function parseGlabAuthStatusHosts(output: string): string[] {
const hosts = new Set<string>()
// Why: self-hosted GitLab can run on a non-default port; preserve it so
// services on the same hostname remain distinct downstream.
for (const match of output.matchAll(/logged in to ([a-zA-Z0-9.-]+(?::\d+)?)/gi)) {
hosts.add(match[1].toLowerCase())
}
for (const line of output.split('\n')) {
const bareLine = line.trim()
const hostLine = bareLine.endsWith(':') ? bareLine.slice(0, -1) : bareLine
if (
line === bareLine &&
/^[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?(?::\d+)?$/.test(hostLine)
) {
hosts.add(hostLine.toLowerCase())
}
}
return Array.from(hosts)
}
@@ -2,6 +2,11 @@ import { gitExecFileAsync, glabExecFileAsync } from '../git/runner'
import type { IssueSourcePreference } from '../../shared/types'
import { getSshGitProvider } from '../providers/ssh-git-dispatch'
import { clearProjectRefInFlight, runProjectRefProbeOnce } from './project-ref-inflight'
import {
parseGlabAuthStatusHosts,
rememberGlabKnownHost,
type LocalGitExecOptions
} from './gitlab-known-host-probe'
import {
DEFAULT_GITLAB_HOSTS,
normalizeGitLabHost,
@@ -12,26 +17,16 @@ import {
export { DEFAULT_GITLAB_HOSTS, parseGitLabProjectRef }
export type { ProjectRef }
export type LocalGitExecOptions = {
wslDistro?: string
}
export {
_resetKnownHostsCache,
getGlabKnownHosts,
parseGlabAuthStatusHosts
} from './gitlab-known-host-probe'
export type { LocalGitExecOptions } from './gitlab-known-host-probe'
const PROJECT_REF_CACHE_MAX_ENTRIES = 512
const projectRefCache = new Map<string, ProjectRef | null>()
// Why: known hosts are cached PER connection. A repo on an SSH connection
// authenticates against a different glab context than the local one, so a
// process-global cache would leak one connection's hosts into another (and
// poison a connection that probes before its tunnel is ready). The local
// context uses the `'local'` key.
const LOCAL_CONNECTION_KEY = 'local'
const knownHostsCacheByConnection = new Map<string, readonly string[]>()
function connectionCacheKey(connectionId?: string | null): string {
return connectionId ?? LOCAL_CONNECTION_KEY
}
/** @internal - exposed for tests only */
export function _resetProjectRefCache(): void {
projectRefCache.clear()
@@ -43,11 +38,6 @@ export function _getProjectRefCacheSize(): number {
return projectRefCache.size
}
/** @internal - exposed for tests only */
export function _resetKnownHostsCache(): void {
knownHostsCacheByConnection.clear()
}
function rememberProjectRefCacheEntry(cacheKey: string, value: ProjectRef | null): void {
projectRefCache.set(cacheKey, value)
while (projectRefCache.size > PROJECT_REF_CACHE_MAX_ENTRIES) {
@@ -118,7 +108,7 @@ async function resolveProjectRefForRemote(
localGitOptions
))
) {
rememberGlabKnownHost(remoteCandidate.host, connectionId)
rememberGlabKnownHost(remoteCandidate.host, connectionId, localGitOptions)
rememberProjectRefCacheEntry(cacheKey, remoteCandidate)
return remoteCandidate
}
@@ -230,16 +220,6 @@ export function glabHostnameArgs(
return connectionId && projectRef?.host ? ['--hostname', projectRef.host] : []
}
function rememberGlabKnownHost(host: string, connectionId?: string | null): void {
const normalizedHost = normalizeGitLabHost(host)
const key = connectionCacheKey(connectionId)
const cached = knownHostsCacheByConnection.get(key)
if (!cached || cached.map(normalizeGitLabHost).includes(normalizedHost)) {
return
}
knownHostsCacheByConnection.set(key, [...cached, normalizedHost])
}
async function isGlabConfiguredForRemoteHost(
repoPath: string,
projectRef: Pick<ProjectRef, 'host'>,
@@ -262,50 +242,3 @@ async function isGlabConfiguredForRemoteHost(
return hosts.includes(normalizeGitLabHost(projectRef.host))
}
}
export async function getGlabKnownHosts(connectionId?: string | null): Promise<readonly string[]> {
const key = connectionCacheKey(connectionId)
const cached = knownHostsCacheByConnection.get(key)
if (cached) {
return cached
}
try {
// Why: `glab auth status` is host-scoped, not cwd-scoped — glab reads its
// own config to list authenticated hosts. The connectionId is threaded so
// the RESULT is cached per connection (a connected repo can have a
// different set of authenticated self-hosted hosts than the local one),
// mirroring how project-ref resolution caches per connection.
const { stdout, stderr } = await glabExecFileAsync(['auth', 'status'])
const hosts = parseGlabAuthStatusHosts(`${stdout}\n${stderr}`)
const merged = Array.from(new Set([...DEFAULT_GITLAB_HOSTS, ...hosts]))
knownHostsCacheByConnection.set(key, merged)
return merged
} catch {
// Auth check failed (glab not installed, no auth, tunnel not ready,
// etc.) — fall back to the canonical default for THIS call, but do NOT
// cache the fallback. A later probe (e.g. after the SSH tunnel comes
// up) must be able to discover the real self-hosted host.
return [...DEFAULT_GITLAB_HOSTS]
}
}
export function parseGlabAuthStatusHosts(output: string): string[] {
const hosts = new Set<string>()
// Why: self-hosted GitLab can run on a non-default port (e.g.
// `gitlab.example.com:8443`); capture the optional `:port` so two services
// on the same hostname but different ports stay distinct downstream.
for (const m of output.matchAll(/logged in to ([a-zA-Z0-9.-]+(?::\d+)?)/gi)) {
hosts.add(m[1].toLowerCase())
}
for (const line of output.split('\n')) {
const bareLine = line.trim()
const hostLine = bareLine.endsWith(':') ? bareLine.slice(0, -1) : bareLine
if (
line === bareLine &&
/^[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?(?::\d+)?$/.test(hostLine)
) {
hosts.add(hostLine.toLowerCase())
}
}
return Array.from(hosts)
}
+97
View File
@@ -434,6 +434,7 @@ describe('getGlabKnownHosts', () => {
})
await expect(getGlabKnownHosts()).resolves.toEqual(['gitlab.com', 'gitlab.example.com'])
expect(glabExecFileAsyncMock).toHaveBeenCalledWith(['auth', 'status'], { timeout: 10_000 })
})
it('falls back to default when glab auth status fails', async () => {
@@ -453,6 +454,55 @@ describe('getGlabKnownHosts', () => {
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(1)
})
it('coalesces many simultaneous callers in one execution context', async () => {
let resolveProbe!: (value: { stdout: string; stderr: string }) => void
glabExecFileAsyncMock.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveProbe = resolve
})
)
const probes = Array.from({ length: 64 }, () => getGlabKnownHosts())
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(1)
resolveProbe({ stdout: 'Logged in to gitlab.concurrent.test as user\n', stderr: '' })
const results = await Promise.all(probes)
expect(results.every((result) => result === results[0])).toBe(true)
expect(results[0]).toEqual(['gitlab.com', 'gitlab.concurrent.test'])
})
it('keeps simultaneous native, WSL distro, and connection probes isolated', async () => {
glabExecFileAsyncMock
.mockResolvedValueOnce({ stdout: 'Logged in to ubuntu.test as user\n', stderr: '' })
.mockResolvedValueOnce({ stdout: 'Logged in to debian.test as user\n', stderr: '' })
.mockResolvedValueOnce({ stdout: 'Logged in to native.test as user\n', stderr: '' })
.mockResolvedValueOnce({ stdout: 'Logged in to ssh.test as user\n', stderr: '' })
const [ubuntu, ubuntuAgain, debian, native, ssh] = await Promise.all([
getGlabKnownHosts(undefined, { wslDistro: 'Ubuntu' }),
getGlabKnownHosts(undefined, { wslDistro: 'Ubuntu' }),
getGlabKnownHosts(undefined, { wslDistro: 'Debian' }),
getGlabKnownHosts(),
getGlabKnownHosts('conn-1')
])
expect(ubuntuAgain).toBe(ubuntu)
expect(ubuntu).toEqual(['gitlab.com', 'ubuntu.test'])
expect(debian).toEqual(['gitlab.com', 'debian.test'])
expect(native).toEqual(['gitlab.com', 'native.test'])
expect(ssh).toEqual(['gitlab.com', 'ssh.test'])
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(4)
expect(glabExecFileAsyncMock).toHaveBeenNthCalledWith(1, ['auth', 'status'], {
timeout: 10_000,
wslDistro: 'Ubuntu'
})
expect(glabExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['auth', 'status'], {
timeout: 10_000,
wslDistro: 'Debian'
})
})
it('recognizes a self-hosted host on a non-default port', async () => {
glabExecFileAsyncMock.mockResolvedValueOnce({
stdout: '✓ Logged in to gitlab.example.com:8080 as user\n',
@@ -500,4 +550,51 @@ describe('getGlabKnownHosts', () => {
])
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(2)
})
it('removes a timed-out probe from in-flight state so a later call retries', async () => {
let rejectProbe!: (error: Error) => void
glabExecFileAsyncMock
.mockImplementationOnce(
() =>
new Promise((_resolve, reject) => {
rejectProbe = reject
})
)
.mockResolvedValueOnce({ stdout: 'Logged in to recovered.test as user\n', stderr: '' })
const first = getGlabKnownHosts(undefined, { wslDistro: 'Ubuntu' })
const concurrent = getGlabKnownHosts(undefined, { wslDistro: 'Ubuntu' })
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(1)
rejectProbe(new Error('wsl.exe timed out.'))
await expect(Promise.all([first, concurrent])).resolves.toEqual([
['gitlab.com'],
['gitlab.com']
])
await expect(getGlabKnownHosts(undefined, { wslDistro: 'Ubuntu' })).resolves.toEqual([
'gitlab.com',
'recovered.test'
])
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(2)
})
it('does not reuse a successful result after an SSH provider reconnects', async () => {
const connectionId = 'conn-reconnected'
registerSshGitProvider(connectionId, {} as never)
glabExecFileAsyncMock
.mockResolvedValueOnce({ stdout: 'Logged in to old-tunnel.test as user\n', stderr: '' })
.mockResolvedValueOnce({ stdout: 'Logged in to new-tunnel.test as user\n', stderr: '' })
await expect(getGlabKnownHosts(connectionId)).resolves.toEqual([
'gitlab.com',
'old-tunnel.test'
])
registerSshGitProvider(connectionId, {} as never)
await expect(getGlabKnownHosts(connectionId)).resolves.toEqual([
'gitlab.com',
'new-tunnel.test'
])
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(2)
unregisterSshGitProvider(connectionId)
})
})
+1 -1
View File
@@ -214,7 +214,7 @@ describe('gitlab issue operations', () => {
await listIssues('/repo-root', 5, undefined, 'opened', undefined, 'conn-7')
expect(getGlabKnownHostsMock).toHaveBeenCalledWith('conn-7')
expect(getGlabKnownHostsMock).toHaveBeenCalledWith('conn-7', {})
})
it('creates an issue and returns its iid + web_url', async () => {
+7 -7
View File
@@ -44,7 +44,7 @@ export async function getIssue(
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<GitLabIssueInfo | null> {
const knownHosts = await getGlabKnownHosts(connectionId)
const knownHosts = await getGlabKnownHosts(connectionId, localGitOptions)
const projectRef = await getIssueProjectRef(repoPath, knownHosts, connectionId, localGitOptions)
// Why: don't fall back to a cwd-inferred `glab issue view` when the project
// can't be resolved — on an SSH connection cwd is not the repo dir, so glab
@@ -92,7 +92,7 @@ export async function listIssues(
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<IssueListResult> {
const knownHosts = await getGlabKnownHosts(connectionId)
const knownHosts = await getGlabKnownHosts(connectionId, localGitOptions)
const { source: projectRef } = await resolveIssueSource(
repoPath,
preference,
@@ -162,7 +162,7 @@ export async function createIssue(
if (!trimmedTitle) {
return { ok: false, error: 'Title is required' }
}
const knownHosts = await getGlabKnownHosts(connectionId)
const knownHosts = await getGlabKnownHosts(connectionId, localGitOptions)
const { source: projectRef } = await resolveIssueSource(
repoPath,
preference,
@@ -232,7 +232,7 @@ export async function updateIssue(
await resolveIssueSource(
repoPath,
preference,
await getGlabKnownHosts(connectionId),
await getGlabKnownHosts(connectionId, localGitOptions),
connectionId,
localGitOptions
)
@@ -369,7 +369,7 @@ export async function addIssueComment(
await resolveIssueSource(
repoPath,
preference,
await getGlabKnownHosts(connectionId),
await getGlabKnownHosts(connectionId, localGitOptions),
connectionId,
localGitOptions
)
@@ -427,7 +427,7 @@ export async function listLabels(
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<string[]> {
const knownHosts = await getGlabKnownHosts(connectionId)
const knownHosts = await getGlabKnownHosts(connectionId, localGitOptions)
const { source: projectRef } = await resolveIssueSource(
repoPath,
preference,
@@ -468,7 +468,7 @@ export async function listAssignableUsers(
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<GitLabAssignableUser[]> {
const knownHosts = await getGlabKnownHosts(connectionId)
const knownHosts = await getGlabKnownHosts(connectionId, localGitOptions)
const { source: projectRef } = await resolveIssueSource(
repoPath,
preference,
+1 -1
View File
@@ -361,7 +361,7 @@ export async function getWorkItemDetails(
await resolveIssueSource(
repoPath,
preference,
await getGlabKnownHosts(connectionId),
await getGlabKnownHosts(connectionId, localGitOptions),
connectionId,
localGitOptions
)