fix: pr-bug-scan validated finding from #6952 (#7180)

* fix: address pr-bug-scan validated finding from #6952

throwNodeNotFound() now re-raises AbortError when the shared signal is aborted, so a signal-cancelled node probe no longer launders into 'Node.js not found'; sequential fallback runs.

* fix(ssh): make session-limited (MaxSessions=1) relay deploys actually succeed

Review of #7180 verified the parent fallback end-to-end against a real
MaxSessions=1 sshd and found the connect still failed. Four gaps, in order
of discovery:

- isSshSessionLimitError missed stock OpenSSH, which refuses session
  channels over MaxSessions with SSH2_OPEN_CONNECT_FAILED (2) and 'open
  failed' — reason 4 never matched, so the fallback never triggered.
- execCommand settled aborted commands before the channel finished
  closing, so the sequential fallback reissued execs while sshd still
  counted the old session.
- SshConnection.waitForSshCallback rejected aborts mid-channel-open
  immediately, leaking a confirmed-late channel that held the only
  session slot; it now settles after the late channel closes (bounded)
  and drains its streams so ssh2 emits 'close'.
- Session channel opens now retry transient session-limit refusals
  (sshd frees the slot only after processing our close-ack, which the
  next open can beat by microseconds), and the remote orca CLI shim
  install is non-fatal like the managed-hook install — after the relay
  bridge occupies the sole session slot, raw-connection extras must
  degrade instead of failing the connection.

Verified live against Docker sshd (OpenSSH 9.2, MaxSessions=1): fresh
deploy (upload + native deps + launch), reconnect cycles, and a PTY
round-trip all succeed; unrestricted-sshd regression run also passes.

Co-authored-by: Orca <help@stably.ai>

* Handle ssh execution aborts immediately during retry backoff or hangs

- Cancel the session-limit retry delay immediately if the operation is
  aborted during backoff.
- Limit the wait time to a 5-second grace period when aborted during a
  channel open that is hung and never invokes its callback, rather than
  waiting for the full connection timeout.

---------

Co-authored-by: orca-bug-scan-bot <orca-bug-scan-bot@stably.ai>
Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com>
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
buf0-bot[bot]
2026-07-04 01:26:55 -07:00
committed by GitHub
co-authored by orca-bug-scan-bot Jinjing Orca
parent 8070e65778
commit f215a48064
11 changed files with 359 additions and 46 deletions
+134
View File
@@ -22,6 +22,7 @@ type MockSshClient = {
_sock: Socket | undefined
lastExecCommand?: string
lastConnectConfig?: unknown
exec: (cmd: string, cb: (err: Error | undefined, channel: unknown) => void) => void
}
let clientInstances: MockSshClient[] = []
@@ -707,6 +708,139 @@ describe('SshConnection', () => {
}
})
it('retries a session-limit-refused exec open and succeeds on a later attempt', async () => {
const conn = new SshConnection(createTarget(), createCallbacks())
await conn.connect()
const channel = { close: vi.fn() }
const execMock = vi
.fn<(cmd: string, cb: (err: Error | undefined, ch: unknown) => void) => void>()
.mockImplementationOnce((_cmd, cb) => {
cb(
Object.assign(new Error('(SSH) Channel open failure: open failed'), { reason: 2 }),
undefined
)
})
.mockImplementation((_cmd, cb) => cb(undefined, channel))
clientInstances[0].exec = execMock as never
await expect(conn.exec('printf ready')).resolves.toBe(channel)
expect(execMock).toHaveBeenCalledTimes(2)
})
it('surfaces the session-limit error once open retries are exhausted', async () => {
const conn = new SshConnection(createTarget(), createCallbacks())
await conn.connect()
const refusal = Object.assign(new Error('(SSH) Channel open failure: open failed'), {
reason: 2
})
const execMock = vi
.fn<(cmd: string, cb: (err: Error | undefined, ch: unknown) => void) => void>()
.mockImplementation((_cmd, cb) => cb(refusal, undefined))
clientInstances[0].exec = execMock as never
await expect(conn.exec('printf ready')).rejects.toBe(refusal)
expect(execMock).toHaveBeenCalledTimes(4)
})
it('does not retry non-session-limit exec open failures', async () => {
const conn = new SshConnection(createTarget(), createCallbacks())
await conn.connect()
const failure = new Error('Not connected')
const execMock = vi
.fn<(cmd: string, cb: (err: Error | undefined, ch: unknown) => void) => void>()
.mockImplementation((_cmd, cb) => cb(failure, undefined))
clientInstances[0].exec = execMock as never
await expect(conn.exec('printf ready')).rejects.toBe(failure)
expect(execMock).toHaveBeenCalledTimes(1)
})
it('bounds an aborted exec to the close grace when ssh2 never invokes the open callback', async () => {
const conn = new SshConnection(createTarget(), createCallbacks())
await conn.connect()
execBehavior = 'pending'
const controller = new AbortController()
vi.useFakeTimers()
try {
const outcomePromise = conn
.exec('printf ready', { signal: controller.signal })
.then(() => 'opened')
.catch((error: Error) => error.name)
controller.abort()
// Why: a hung socket must not pin the aborted caller for the full 30s
// connect timeout — the abort settles at the 5s grace bound instead.
await vi.advanceTimersByTimeAsync(5_000)
await expect(outcomePromise).resolves.toBe('AbortError')
} finally {
vi.useRealTimers()
}
})
it('rejects without waiting out the backoff when aborted during a session-limit retry delay', async () => {
const conn = new SshConnection(createTarget(), createCallbacks())
await conn.connect()
const controller = new AbortController()
const refusal = Object.assign(new Error('(SSH) Channel open failure: open failed'), {
reason: 2
})
const execMock = vi
.fn<(cmd: string, cb: (err: Error | undefined, ch: unknown) => void) => void>()
.mockImplementation((_cmd, cb) => cb(refusal, undefined))
clientInstances[0].exec = execMock as never
vi.useFakeTimers()
try {
const outcomePromise = conn
.exec('printf ready', { signal: controller.signal })
.then(() => 'opened')
.catch((error: Error) => error.name)
// Flush microtasks so the first refused attempt lands in the backoff.
await vi.advanceTimersByTimeAsync(0)
controller.abort()
// No timer advance: the abort alone must release the backoff delay.
await expect(outcomePromise).resolves.toBe('AbortError')
expect(execMock).toHaveBeenCalledTimes(1)
} finally {
vi.useRealTimers()
}
})
it('settles an abort during channel open only after the late channel closes', async () => {
const conn = new SshConnection(createTarget(), createCallbacks())
await conn.connect()
execBehavior = 'pending'
const controller = new AbortController()
const lateChannel = Object.assign(new EventEmitter(), {
close: vi.fn(),
resume: vi.fn(),
stderr: { resume: vi.fn() }
})
const outcomePromise = conn
.exec('printf ready', { signal: controller.signal })
.then(() => 'opened')
.catch((error: Error) => error.name)
await Promise.resolve()
controller.abort()
pendingExecCallback?.(undefined, lateChannel)
// Why: the sshd session slot is freed only when the channel finishes
// closing — settling before 'close' lets the next open race the close.
const early = await Promise.race([outcomePromise, Promise.resolve('pending')])
expect(early).toBe('pending')
expect(lateChannel.close).toHaveBeenCalledTimes(1)
expect(lateChannel.resume).toHaveBeenCalled()
lateChannel.emit('close')
await expect(outcomePromise).resolves.toBe('AbortError')
})
it('times out when ssh2 never opens an SFTP channel', async () => {
const conn = new SshConnection(createTarget(), createCallbacks())
await conn.connect()
+124 -17
View File
@@ -35,12 +35,25 @@ import {
type SshConnectionCallbacks
} from './ssh-connection-utils'
import type { RemoteHostPlatform } from './ssh-remote-platform'
import { isSshSessionLimitError } from './ssh-session-limit-error'
export type { SshConnectionCallbacks } from './ssh-connection-utils'
type SshRemoteFileOptions = {
hostPlatform?: RemoteHostPlatform
}
// Upper bound on waiting, after an abort, for the in-flight open callback or
// for an aborted late-opened channel to finish closing before rejecting
// anyway. Normal opens and closes complete in one network round-trip.
const ABORTED_CHANNEL_CLOSE_GRACE_MS = 5_000
// Why: on session-limited servers (MaxSessions), a channel open can be refused
// transiently — e.g. our next CHANNEL_OPEN reaching sshd a few microseconds
// before it finishes processing the previous channel's close. A refused open
// never started the command, so retrying is always safe.
const SESSION_LIMIT_OPEN_RETRIES = 4
const SESSION_LIMIT_OPEN_RETRY_DELAY_MS = 150
function cloneResolvedConfig(config: SshResolvedConfig | null): SshResolvedConfig | null {
if (!config) {
return null
@@ -132,10 +145,14 @@ export class SshConnection {
}
const client = this.client
const remoteCommand = options?.wrapCommand === false ? cmd : wrapRemoteCommandForPosixShell(cmd)
return this.waitForSshCallback(
'SSH exec channel timed out',
(callback) => client.exec(remoteCommand, callback),
(channel) => channel.close(),
return this.openSessionChannelWithRetry(
() =>
this.waitForSshCallback(
'SSH exec channel timed out',
(callback) => client.exec(remoteCommand, callback),
(channel) => channel.close(),
options?.signal
),
options?.signal
)
}
@@ -148,13 +165,50 @@ export class SshConnection {
throw new Error('Not connected')
}
const client = this.client
return this.waitForSshCallback(
'SSH SFTP channel timed out',
(callback) => client.sftp(callback),
(sftp) => sftp.end()
return this.openSessionChannelWithRetry(() =>
this.waitForSshCallback(
'SSH SFTP channel timed out',
(callback) => client.sftp(callback),
(sftp) => sftp.end()
)
)
}
private async openSessionChannelWithRetry<T>(
open: () => Promise<T>,
signal?: AbortSignal
): Promise<T> {
let lastError: unknown
for (let attempt = 0; attempt < SESSION_LIMIT_OPEN_RETRIES; attempt++) {
if (attempt > 0) {
// Why: an abort must release the backoff immediately, not after it.
if (!signal?.aborted) {
await new Promise<void>((resolve) => {
const onDelayDone = (): void => {
clearTimeout(delayTimer)
signal?.removeEventListener('abort', onDelayDone)
resolve()
}
const delayTimer = setTimeout(onDelayDone, SESSION_LIMIT_OPEN_RETRY_DELAY_MS)
signal?.addEventListener('abort', onDelayDone, { once: true })
})
}
if (signal?.aborted) {
throw createSshOperationAbortError()
}
}
try {
return await open()
} catch (err) {
if (!isSshSessionLimitError(err)) {
throw err
}
lastError = err
}
}
throw lastError
}
private waitForSshCallback<T>(
timeoutMessage: string,
register: (callback: (error: Error | undefined, value: T) => void) => void,
@@ -163,23 +217,66 @@ export class SshConnection {
): Promise<T> {
return new Promise((resolve, reject) => {
let settled = false
// Why: rejecting the instant the signal aborts lets the caller proceed
// while the in-flight channel open completes in the background and holds
// a server-side session slot (MaxSessions). Mark the abort and settle
// from the open callback, after the late resource has been closed.
let abortRequested = false
let abortDeadlineTimer: NodeJS.Timeout | undefined
const cleanup = (): void => {
clearTimeout(timer)
clearTimeout(abortDeadlineTimer)
signal?.removeEventListener('abort', onAbort)
}
const onAbort = (): void => {
if (settled) {
return
}
settled = true
cleanup()
reject(createSshOperationAbortError())
abortRequested = true
// Why: a hung socket may never invoke the open callback — bound the
// aborted caller's wait instead of pinning it for CONNECT_TIMEOUT_MS.
abortDeadlineTimer = setTimeout(() => {
settled = true
cleanup()
reject(createSshOperationAbortError())
}, ABORTED_CHANNEL_CLOSE_GRACE_MS)
}
const timer = setTimeout(() => {
settled = true
signal?.removeEventListener('abort', onAbort)
reject(new Error(timeoutMessage))
cleanup()
reject(abortRequested ? createSshOperationAbortError() : new Error(timeoutMessage))
}, CONNECT_TIMEOUT_MS)
const rejectAfterClose = (value: T): void => {
const abortError = createSshOperationAbortError()
const emitter = value as Partial<NodeJS.EventEmitter> & {
resume?: () => void
stderr?: { resume?: () => void }
}
let finished = false
const done = (): void => {
if (finished) {
return
}
finished = true
clearTimeout(closeGraceTimer)
reject(abortError)
}
// Why: bounded — a remote that never confirms the close must not hang
// the aborted operation forever.
const closeGraceTimer = setTimeout(done, ABORTED_CHANNEL_CLOSE_GRACE_MS)
if (typeof emitter.once === 'function') {
emitter.once('close', done)
}
// Why: ssh2 withholds the 'close' event until the channel's streams
// are drained; nobody else will ever read this discarded channel.
emitter.resume?.()
emitter.stderr?.resume?.()
try {
cleanupLateValue?.(value)
} catch {
/* best effort */
}
if (typeof emitter.once !== 'function') {
done()
}
}
const finish = (error: Error | undefined, value?: T): void => {
if (settled) {
// Why: ssh2 can invoke the open callback after our timeout has
@@ -196,6 +293,14 @@ export class SshConnection {
}
settled = true
cleanup()
if (abortRequested) {
if (!error && value !== undefined) {
rejectAfterClose(value)
} else {
reject(createSshOperationAbortError())
}
return
}
if (error) {
reject(error)
return
@@ -203,7 +308,9 @@ export class SshConnection {
resolve(value as T)
}
if (signal?.aborted) {
onAbort()
// No open is in flight yet, so failing fast leaks nothing.
cleanup()
reject(createSshOperationAbortError())
return
}
signal?.addEventListener('abort', onAbort, { once: true })
+21 -2
View File
@@ -286,8 +286,22 @@ describe('execCommand', () => {
await Promise.resolve()
controller.abort()
await expect(commandPromise).rejects.toMatchObject({ name: 'AbortError' })
// Why: sshd frees the MaxSessions slot only when the channel finishes
// closing, so abort must request close and settle from the 'close' event —
// settling immediately lets the sequential fallback race the closing
// channel and get refused.
expect(channel.close).toHaveBeenCalledOnce()
const settledEarly = await Promise.race([
commandPromise.then(
() => 'settled',
() => 'settled'
),
Promise.resolve('pending')
])
expect(settledEarly).toBe('pending')
channel.emit('close', 0)
await expect(commandPromise).rejects.toMatchObject({ name: 'AbortError' })
expect(channel.listenerCount('error')).toBe(0)
expect(channel.listenerCount('data')).toBe(0)
expect(channel.listenerCount('close')).toBe(0)
@@ -313,8 +327,13 @@ describe('execCommand', () => {
controller.abort()
resolveExec(channel)
await expect(commandPromise).rejects.toMatchObject({ name: 'AbortError' })
await Promise.resolve()
await Promise.resolve()
expect(channel.close).toHaveBeenCalledOnce()
// Nonzero exit from the killed command must still surface as AbortError.
channel.emit('close', 1)
await expect(commandPromise).rejects.toMatchObject({ name: 'AbortError' })
expect(channel.listenerCount('error')).toBe(0)
expect(channel.listenerCount('data')).toBe(0)
expect(channel.listenerCount('close')).toBe(0)
+16 -4
View File
@@ -275,11 +275,16 @@ export async function execCommand(
fn(val as never)
}
const fail = (err: Error): void => {
settle(reject, err)
settle(reject, abortRequested ? createSshOperationAbortError() : err)
}
// Why: sshd counts the session against MaxSessions until CHANNEL_CLOSE
// completes. Settling on abort before the channel actually closes lets the
// concurrent-bootstrap sequential fallback reissue an exec while the slot
// is still held, so it gets refused again. Close and settle from onClose.
let abortRequested = false
const onAbort = (): void => {
abortRequested = true
channel.close()
settle(reject, createSshOperationAbortError())
}
const onStdoutData = (data: Buffer): void => {
stdout += data.toString('utf-8')
@@ -288,7 +293,9 @@ export async function execCommand(
stderr += data.toString('utf-8')
}
const onClose = (code: number): void => {
if (code !== 0) {
if (abortRequested) {
settle(reject, createSshOperationAbortError())
} else if (code !== 0) {
// Why: on the system-ssh transport channel.stderr carries local OpenSSH
// client noise; preferring it masks the real failure in stdout (2>&1).
const output = [stderr.trim(), stdout.trim()].filter(Boolean).join('\n')
@@ -299,7 +306,12 @@ export async function execCommand(
}
const timeout = setTimeout(() => {
channel.close()
settle(reject, new Error(`Command "${command}" timed out after ${timeoutMs / 1000}s`))
settle(
reject,
abortRequested
? createSshOperationAbortError()
: new Error(`Command "${command}" timed out after ${timeoutMs / 1000}s`)
)
}, timeoutMs)
// Why: remote reboot tears down exec channels with stream errors. Without
+13 -1
View File
@@ -531,7 +531,19 @@ export class SshRelaySession {
return false
}
await this.installRemoteOrcaCliShim()
try {
await this.installRemoteOrcaCliShim()
} catch (error) {
// Why: the remote `orca` CLI shim is a convenience bridge. On session-
// limited remotes (MaxSessions=1) the relay bridge holds the only slot,
// so this raw-connection install can fail — that must not fail the
// whole connection, matching the managed-hook install above.
console.warn(
`[ssh-relay-session] remote orca CLI shim install failed for ${this.targetId}: ${
error instanceof Error ? error.message : String(error)
}`
)
}
if (shouldContinue && !shouldContinue()) {
return false
}
@@ -331,6 +331,25 @@ describe('resolveRemoteNodePath', () => {
).rejects.toBe(sessionLimitError)
})
it('surfaces an AbortError instead of not-found when the shared signal is aborted', async () => {
// Why: in concurrent bootstrap a sibling probe aborts this resolution via
// the shared signal. Each strategy catch swallows the injected AbortError,
// so without re-raising it here the resolver would launder cancellation
// into a fatal "Node.js not found" and defeat the sequential fallback.
const controller = new AbortController()
const abortError = Object.assign(new Error('SSH operation was cancelled'), {
name: 'AbortError'
})
execCommandMock.mockImplementation(() => {
controller.abort()
return Promise.reject(abortError)
})
await expect(
resolveRemoteNodePath(conn, undefined, { signal: controller.signal })
).rejects.toMatchObject({ name: 'AbortError' })
})
it('throws when every candidate across both strategies is below the minimum', async () => {
execCommandMock
.mockResolvedValueOnce('/old/node\n') // path probe
+12 -4
View File
@@ -1,5 +1,5 @@
import type { SshConnection } from './ssh-connection'
import { shellEscape } from './ssh-connection-utils'
import { createSshOperationAbortError, shellEscape } from './ssh-connection-utils'
import type { RemoteHostPlatform } from './ssh-remote-platform'
import { isWindowsRemoteHost, normalizeWindowsRemotePath } from './ssh-remote-platform'
import { powerShellCommand } from './ssh-remote-powershell'
@@ -47,7 +47,7 @@ export async function resolveRemoteNodePath(
return loginShellPath
}
throwNodeNotFound()
throwNodeNotFound(options)
}
// Probe the on-disk install directories of every common Node version manager
@@ -245,10 +245,18 @@ async function resolveRemoteWindowsNodePath(
// Fall through to the shared error below.
}
throwNodeNotFound()
throwNodeNotFound(options)
}
function throwNodeNotFound(): never {
function throwNodeNotFound(options?: RemoteNodeResolutionOptions): never {
// Why: when a sibling bootstrap probe aborts this resolution via the shared
// signal, the strategy catch-blocks swallow the injected AbortError and fall
// through to here. Surfacing "Node.js not found" would launder a cancellation
// into a fatal non-session failure, defeating the concurrent-bootstrap
// sequential fallback. Re-raise the abort so callers classify it correctly.
if (options?.signal?.aborted) {
throw createSshOperationAbortError()
}
throw new Error(
'Node.js not found on remote host. Orca relay requires Node.js 18+. ' +
'Install Node.js on the remote and try again.'
+10 -5
View File
@@ -10,6 +10,16 @@ describe('isSshSessionLimitError', () => {
).toBe(true)
})
it('matches the OpenSSH MaxSessions rejection (SSH2_OPEN_CONNECT_FAILED + "open failed")', () => {
// Why: stock OpenSSH sshd refuses session channels over MaxSessions with
// reason 2, not resource-shortage — observed against OpenSSH 9.2.
expect(
isSshSessionLimitError(
Object.assign(new Error('(SSH) Channel open failure: open failed'), { reason: 2 })
)
).toBe(true)
})
it('matches OpenSSH mux and MaxSessions failures', () => {
expect(
isSshSessionLimitError(
@@ -29,11 +39,6 @@ describe('isSshSessionLimitError', () => {
Object.assign(new Error('(SSH) Channel open failure: open failed'), { reason: 1 })
)
).toBe(false)
expect(
isSshSessionLimitError(
Object.assign(new Error('(SSH) Channel open failure: open failed'), { reason: 2 })
)
).toBe(false)
expect(
isSshSessionLimitError(
Object.assign(new Error('(SSH) Channel open failure: open failed'), { reason: 3 })
+4 -1
View File
@@ -4,8 +4,11 @@ export function isSshSessionLimitError(err: unknown): boolean {
}
const reason = (err as { reason?: unknown }).reason
const message = err.message.toLowerCase()
// Why: OpenSSH rejects session channels over MaxSessions with
// SSH2_OPEN_CONNECT_FAILED (2) and the literal description "open failed";
// reason 4 (resource shortage) covers other server implementations.
if (
reason === 4 &&
(reason === 2 || reason === 4) &&
(message.includes('channel open failure') || message.includes('open failed'))
) {
return true
@@ -116,12 +116,8 @@ describe('resource manager row presentation', () => {
expect(container.textContent).toContain('· remote')
const killButtons = container.querySelectorAll('button[aria-label^="Kill session"]')
expect(killButtons).toHaveLength(2)
expect(
container.querySelector('button[aria-label="Kill session ssh-a"]')
).not.toBeNull()
expect(
container.querySelector('button[aria-label="Kill session ssh-b"]')
).not.toBeNull()
expect(container.querySelector('button[aria-label="Kill session ssh-a"]')).not.toBeNull()
expect(container.querySelector('button[aria-label="Kill session ssh-b"]')).not.toBeNull()
})
it('keeps kill affordances on the orphan bucket rows', () => {
@@ -133,8 +129,6 @@ describe('resource manager row presentation', () => {
})
)
expect(
container.querySelector('button[aria-label="Kill session orphan-a"]')
).not.toBeNull()
expect(container.querySelector('button[aria-label="Kill session orphan-a"]')).not.toBeNull()
})
})
+3 -3
View File
@@ -217,9 +217,9 @@ describe('isGitLabIssueUrl', () => {
it('detects modern /-/work_items/<iid> issue URLs (incl. non-default port)', () => {
expect(isGitLabIssueUrl('https://gitlab.com/group/project/-/work_items/123')).toBe(true)
expect(
isGitLabIssueUrl('https://gitlab.example.com:8443/group/project/-/work_items/7')
).toBe(true)
expect(isGitLabIssueUrl('https://gitlab.example.com:8443/group/project/-/work_items/7')).toBe(
true
)
})
it('does not classify GitHub issue URLs as GitLab issues', () => {