Fix paste ownership, input bounds, and IPC validation

Supersedes #5745, #5746, and #5747.
This commit is contained in:
Jinwoo Hong
2026-06-19 17:14:55 -07:00
committed by GitHub
parent a5920b2183
commit 972078f2c4
592 changed files with 33303 additions and 3737 deletions
+13
View File
@@ -361,6 +361,19 @@ describe('parseGlabApiResponse', () => {
expect(parsed.body).toBe('[]')
})
it('splits large bodies without full-output separator matching', () => {
const matchSpy = vi.spyOn(String.prototype, 'match')
const body = '[{"iid":1}]'.repeat(10_000)
const parsed = parseGlabApiResponse(`HTTP/2.0 200 OK\r\nX-Total: 7\r\n\r\n${body}`)
expect(parsed.headers['x-total']).toBe('7')
expect(parsed.body).toBe(body)
const usedSeparatorMatch = matchSpy.mock.calls.some(
([pattern]) => pattern instanceof RegExp && pattern.source === '\\r?\\n\\r?\\n'
)
expect(usedSeparatorMatch).toBe(false)
})
it('lowercases header names for stable lookup', () => {
const stdout = 'HTTP/2.0 200 OK\nX-Total: 1\nContent-Type: application/json\n\n{}'
const parsed = parseGlabApiResponse(stdout)
+2 -24
View File
@@ -1,6 +1,7 @@
import { execFile } from 'child_process'
import { promisify } from 'util'
import { gitExecFileAsync, glabExecFileAsync } from '../git/runner'
import { parseGlabApiResponse, type GlabApiResponse } from './glab-api-response'
// Why: legacy generic execFile wrapper - only used by callers that don't need
// WSL-aware routing. Repo-scoped callers should use the runner exports below.
@@ -27,6 +28,7 @@ export type {
ProjectRef,
ResolvedIssueSource
} from './gitlab-project-ref-resolution'
export { parseGlabApiResponse, type GlabApiResponse } from './glab-api-response'
const MAX_CONCURRENT = 4
let running = 0
@@ -53,11 +55,6 @@ export function release(): void {
}
}
export type GlabApiResponse = {
body: string
headers: Record<string, string>
}
export async function glabApiWithHeaders(
args: string[],
options?: { cwd?: string }
@@ -65,22 +62,3 @@ export async function glabApiWithHeaders(
const { stdout } = await glabExecFileAsync(['api', '-i', ...args], options)
return parseGlabApiResponse(stdout)
}
/** @internal - exported for tests. */
export function parseGlabApiResponse(stdout: string): GlabApiResponse {
const sepMatch = stdout.match(/\r?\n\r?\n/)
if (!sepMatch || sepMatch.index === undefined) {
return { body: stdout, headers: {} }
}
const headerBlock = stdout.slice(0, sepMatch.index)
const body = stdout.slice(sepMatch.index + sepMatch[0].length)
const headers: Record<string, string> = {}
const lines = headerBlock.split(/\r?\n/)
for (const line of lines) {
const m = line.match(/^([A-Za-z][A-Za-z0-9-]*):\s*(.*)$/)
if (m) {
headers[m[1].toLowerCase()] = m[2].trim()
}
}
return { body, headers }
}
+46
View File
@@ -0,0 +1,46 @@
export type GlabApiResponse = {
body: string
headers: Record<string, string>
}
/** @internal - exported for tests through gl-utils. */
export function parseGlabApiResponse(stdout: string): GlabApiResponse {
// Why: response is HTTP status, headers, blank line, then body.
// Find the first blank line (CRLF or LF) as the boundary.
const separator = findHeaderBodySeparator(stdout)
if (!separator) {
return { body: stdout, headers: {} }
}
const headerBlock = stdout.slice(0, separator.index)
const body = stdout.slice(separator.bodyStart)
const headers: Record<string, string> = {}
// Skip the status line and parse the rest as key: value.
const lines = headerBlock.split(/\r?\n/)
for (const line of lines) {
const m = line.match(/^([A-Za-z][A-Za-z0-9-]*):\s*(.*)$/)
if (m) {
headers[m[1].toLowerCase()] = m[2].trim()
}
}
return { body, headers }
}
function findHeaderBodySeparator(stdout: string): { index: number; bodyStart: number } | null {
let lineStart = 0
for (let index = 0; index < stdout.length; index++) {
const code = stdout.charCodeAt(index)
if (code !== 10 && code !== 13) {
continue
}
const lineEnd = index
const nextLineStart =
stdout.charCodeAt(index) === 13 && stdout.charCodeAt(index + 1) === 10 ? index + 2 : index + 1
if (lineEnd === lineStart) {
return { index: lineStart, bodyStart: nextLineStart }
}
lineStart = nextLineStart
index = nextLineStart - 1
}
return null
}
+79
View File
@@ -0,0 +1,79 @@
import { glabExecFileAsync } from '../git/runner'
import { DEFAULT_GITLAB_HOSTS, normalizeGitLabHost, type ProjectRef } from './project-ref-parser'
let knownHostsCache: readonly string[] | null = null
export function rememberGlabKnownHost(host: string): void {
const normalizedHost = normalizeGitLabHost(host)
if (!knownHostsCache || knownHostsCache.map(normalizeGitLabHost).includes(normalizedHost)) {
return
}
knownHostsCache = [...knownHostsCache, normalizedHost]
}
export async function isGlabConfiguredForRemoteHost(
repoPath: string,
projectRef: Pick<ProjectRef, 'host'>,
connectionId?: string | null
): Promise<boolean> {
try {
const result = await glabExecFileAsync(
['auth', 'status', '--hostname', projectRef.host],
connectionId ? {} : { cwd: repoPath }
)
return result !== undefined
} catch (error) {
const execLike = error as { stdout?: unknown; stderr?: unknown; message?: unknown }
const output =
[execLike.stdout, execLike.stderr, execLike.message]
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
.join('\n') || String(error)
const hosts = parseGlabAuthStatusHosts(output).map(normalizeGitLabHost)
return hosts.includes(normalizeGitLabHost(projectRef.host))
}
}
/** @internal - exposed for tests only */
export function _resetKnownHostsCache(): void {
knownHostsCache = null
}
export async function getGlabKnownHosts(): Promise<readonly string[]> {
if (knownHostsCache) {
return knownHostsCache
}
try {
const { stdout, stderr } = await glabExecFileAsync(['auth', 'status'])
// Why: glab writes auth status to stderr in some versions, stdout in
// others. Concatenate so the parser sees both.
const hosts = parseGlabAuthStatusHosts(`${stdout}\n${stderr}`)
// Always include gitlab.com so a fresh-install user with no auth
// still recognizes the canonical host.
const merged = Array.from(new Set([...DEFAULT_GITLAB_HOSTS, ...hosts]))
knownHostsCache = merged
return merged
} catch {
// Auth check failed (glab not installed, no auth, etc.) - fall back
// to the canonical default. The caller will hit the auth error on
// the first real request anyway.
knownHostsCache = [...DEFAULT_GITLAB_HOSTS]
return knownHostsCache
}
}
// Why: glab auth status output is human-formatted and varies across versions.
// Match observed logged-in lines and host headers, dedupe, lowercase.
export function parseGlabAuthStatusHosts(output: string): string[] {
const hosts = new Set<string>()
for (const m of output.matchAll(/logged in to ([a-zA-Z0-9.-]+)/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])?$/.test(hostLine)) {
hosts.add(hostLine.toLowerCase())
}
}
return Array.from(hosts)
}