Files
orca/src/main/ssh/ssh-connection-utils.ts
T
Jinjing bdb7d58c4b fix(P1-B): recover SSH targets and remote file watchers after a network drop (#12032)
* fix(P1-B): recover system-SSH targets after a network drop

Two defects stopped a remote workspace auto-recovering after a blip.

runReconnectAttempt classified failures with isTransientError, which only
matches ETIMEDOUT/ECONNREFUSED/ECONNRESET by errno code or literal
substring. The system-SSH transport — the only transport FIDO2 and
ProxyUseFdpass targets can use — reports network failures as OpenSSH
prose ("System SSH connection timed out"), so the ladder published a
permanent 'error' on the first timeout and the target never came back
without a manual reconnect. isTransientReconnectError adds a
network-shaped prose table on top of isTransientError and is used only on
the reconnect path: connect() keeps the narrow classifier so an
unreachable host still fails fast instead of burning five 30s attempts
and five security-key touch prompts. Auth and passphrase failures stay
permanent on both paths.

runReconnectAttempt also had no generation fence, so a superseded attempt
published its cancellation as a permanent error over the winner's live
connection — reachable when a system-transport proc.onExit schedules a
reconnect while an attempt is still in flight. Cancellation now carries a
stable error name, and both connect() and runReconnectAttempt claim their
connectGeneration and stay silent when a newer attempt owns the state.

* fix(P1-B): retry a dropped watcher overflow marker on real capacity

emitWatcherOverflowToClient published the {kind:'overflow'} resync marker
with controlOverflow:'reject'. A full control queue rejects at admission
with no settlement callback, so the marker was silently discarded and the
remote File Explorer stayed stale until some later watcher event happened
to produce another one — for a quiet tree, possibly never.

The emitter now retains a rejected marker per (client, root) and
republishes it when the sink actually frees up. The existing
onLegacyPtyCapacity signal cannot drive that: it is gated on producer
retention, so it stays silent exactly under the dual-queue pressure that
caused the rejection. RelayDispatcher.onClientCapacity is an ungated
per-client capacity signal that fires on every writer settlement and
drain. It lives on the dispatcher rather than the writer so a retained
marker survives setWrite() replacing the primary sink, and setWrite
notifies capacity once afterwards so the marker does not wait on traffic
that may never arrive.

Retention is bounded to one marker per (client, root), released on
settlement and purged on client detach.

* fix(P1-B): address all review findings on SSH network recovery

Fix four issues from code review:

1. **Bug — admitted overflow markers lost on setWrite**: Retain markers when
   settlement fails `ok: false`, not just on admission rejection. Prevents
   desynced filesystem trees after SSH sink replacement.

2. **SSH error classification expanded**: Add missing OpenSSH patterns
   (`ssh_exchange_identification`, `connection closed by remote`) and new
   `isDefiniteSystemSshHostFailure()` classifier.

3. **ControlMaster retry optimization**: Skip second probe when first failure is
   already definite host-level (network timeout, refused, unreachable). Saves
   ~30s per reconnect ladder step.

4. **Overflow flush under dual-queue pressure**: Gate pending marker retries on
   control-lane headroom instead of re-attempting on every capacity notification.
   Reduces thrash proportional to producer traffic.

Add regression tests for marker republish on sink replacement and validate auth
error detection against live OpenSSH credential rejection messages.

* rm random doc

* fix(P1-B): skip credential-failure retries and recover watcher markers o

- Auth and passphrase errors fail immediately without retry attempts
- Bare "System SSH probe failed (exit 255)" is transient only for reconnect
- Watcher markers survive client invalidation when switching SSH connections
- Add network error patterns: "lost connection", "remote end closed"

(cherry picked from commit ce5b639e03)
2026-08-02 00:50:29 -07:00

363 lines
12 KiB
TypeScript

import { spawn, type ChildProcess } from 'node:child_process'
import { Duplex } from 'node:stream'
import type { Socket as NetSocket } from 'node:net'
import type { ConnectConfig } from 'ssh2'
import type { SshTarget, SshConnectionState } from '../../shared/ssh-types'
import type { SshResolvedConfig } from './ssh-config-parser'
import {
findEncryptedPrivateKeyPath,
resolveAgentConfigValue,
resolveAgentSocket,
resolvePrivateKeys,
resolveUnencryptedExplicitPrivateKeys
} from './ssh-auth-resolution'
import { configurePrivateKeyAuthentication } from './ssh-private-key-authentication'
import { isOpenSshConfigBackedTarget } from './system-ssh-args'
export { findDefaultKeyFile, resolveAgentSocket } from './ssh-auth-resolution'
export type SshCredentialKind = 'passphrase' | 'password'
export type SshConnectionCallbacks = {
onStateChange: (targetId: string, state: SshConnectionState) => void
onCredentialRequest?: (
targetId: string,
kind: SshCredentialKind,
detail: string
) => Promise<string | null>
}
export function isPassphraseError(err: Error): boolean {
const msg = err.message.toLowerCase()
return msg.includes('passphrase') || msg.includes('encrypted key') || msg.includes('bad decrypt')
}
export const INITIAL_RETRY_ATTEMPTS = 5
export const INITIAL_RETRY_DELAY_MS = 2000
export const RECONNECT_BACKOFF_MS = [1000, 2000, 5000, 5000, 10000, 10000, 10000, 30000, 30000]
export const CONNECT_TIMEOUT_MS = 30_000
const TRANSIENT_ERROR_CODES = new Set([
'ETIMEDOUT',
'ECONNREFUSED',
'ECONNRESET',
'EHOSTUNREACH',
'ENETUNREACH',
'EAI_AGAIN'
])
export function isAuthError(err: Error): boolean {
const msg = err.message.toLowerCase()
return (
msg.includes('all configured authentication methods failed') ||
msg.includes('authentication failed') ||
msg.includes('too many authentication failures') ||
/permission denied(?:, please try again\.?| \([^)]*(?:publickey|password|keyboard-interactive|gssapi|hostbased)[^)]*\))/.test(msg) ||
(err as { level?: string }).level === 'client-authentication'
)
}
export function isAgentFallbackError(err: Error): boolean {
return isAuthError(err) || (err as { level?: string }).level === 'agent'
}
export function isTransientError(err: Error): boolean {
const code = (err as NodeJS.ErrnoException).code
if (code && TRANSIENT_ERROR_CODES.has(code)) {
return true
}
if (err.message.includes('ETIMEDOUT')) {
return true
}
if (err.message.includes('ECONNREFUSED')) {
return true
}
if (err.message.includes('ECONNRESET')) {
return true
}
return false
}
const SYSTEM_SSH_FALLBACK_ERROR_CODES = new Set(['EHOSTUNREACH', 'ENETUNREACH'])
export function isSystemSshFallbackError(err: Error): boolean {
const code = (err as NodeJS.ErrnoException).code
if (code && SYSTEM_SSH_FALLBACK_ERROR_CODES.has(code)) {
return true
}
return err.message.includes('EHOSTUNREACH') || err.message.includes('ENETUNREACH')
}
// Why: ssh2 has no gssapi-with-mic support. When the effective OpenSSH config
// enables GSSAPIAuthentication (often a distro-wide /etc/ssh default), a
// Kerberos ticket can still authenticate through the system ssh binary after
// key/agent auth fails — but only auth-shaped failures qualify, so network
// errors keep their existing retry semantics.
export function isGssapiSystemSshFallbackCandidate(
err: Error,
target: Pick<SshTarget, 'gssapiAuthentication'>,
resolved: Pick<SshResolvedConfig, 'gssapiAuthentication'> | null
): boolean {
// Why: targets with an explicit per-host flag already tried system ssh
// proactively during this attempt; probing again cannot succeed.
if (target.gssapiAuthentication === true) {
return false
}
return (isAuthError(err) || isPassphraseError(err)) && resolved?.gssapiAuthentication === true
}
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
export function shellEscape(s: string): string {
return `'${s.replace(/'/g, "'\\''")}'`
}
const REMOTE_COMMAND_CHUNK_MAX_BYTES = 1_024
const REMOTE_COMMAND_PRINTF_ESCAPED_BYTES = new Set([0x21, 0x27, 0x5c])
function encodeRemoteCommandForPrintf(command: string): string[] {
const chunks: string[] = []
let chunk = ''
let chunkBytes = 0
for (const character of command) {
const codePoint = character.codePointAt(0)!
const isSafePrintableAscii =
codePoint >= 0x20 && codePoint <= 0x7e && !REMOTE_COMMAND_PRINTF_ESCAPED_BYTES.has(codePoint)
const encodedCharacter =
codePoint > 0x7f || isSafePrintableAscii
? character
: `\\0${codePoint.toString(8).padStart(3, '0')}`
const encodedBytes = codePoint > 0x7f ? Buffer.byteLength(character) : encodedCharacter.length
if (chunkBytes + encodedBytes > REMOTE_COMMAND_CHUNK_MAX_BYTES) {
chunks.push(chunk)
chunk = ''
chunkBytes = 0
}
chunk += encodedCharacter
chunkBytes += encodedBytes
}
chunks.push(chunk)
return chunks
}
/** Wrap a POSIX snippet into one line that non-POSIX SSH login shells can forward. */
export function wrapRemoteCommandForPosixShell(command: string): string {
// Why: csh/tcsh split multiline SSH exec strings before /bin/sh sees them.
// POSIX printf rebuilds bounded argument chunks without consuming relay stdin.
const encodedChunks = encodeRemoteCommandForPrintf(command)
const decodeAndRun =
'decoded=$(printf %b "$@" && printf _) || exit $?; ' +
'decoded=${decoded%_}; exec /bin/sh -c "$decoded"'
const chunkArguments = encodedChunks.map(shellEscape).join(' ')
return `exec /bin/sh -c ${shellEscape(decodeAndRun)} orca-command ${chunkArguments}`
}
export type SshExecOptions = {
wrapCommand?: boolean
signal?: AbortSignal
}
export function createSshOperationAbortError(): Error & { name: string } {
const error = new Error('SSH operation was cancelled') as Error & { name: string }
error.name = 'AbortError'
return error
}
function cmdEscape(s: string): string {
return `"${s.replace(/"/g, '""')}"`
}
type BuildConnectConfigOptions = {
includeAgent?: boolean
includePrivateKey?: boolean
}
// Why: ssh2 tries privateKey before agent, but parses encrypted privateKey
// values before any agent auth can run. Keep unencrypted explicit keys first
// while deferring encrypted keys until the post-agent passphrase path.
export function buildConnectConfig(
target: SshTarget,
resolved: SshResolvedConfig | null,
options: BuildConnectConfigOptions = {}
): ConnectConfig {
const effectiveHost = resolveEffectiveHost(target, resolved)
const effectivePort = resolveEffectivePort(target, resolved)
const effectiveUser =
isOpenSshConfigBackedTarget(target) && resolved
? (resolved.user ?? target.username)
: target.username || resolved?.user || ''
const config: Record<string, unknown> = {
host: effectiveHost,
port: effectivePort,
username: effectiveUser,
readyTimeout: CONNECT_TIMEOUT_MS,
keepaliveInterval: 15_000
}
const shouldIncludeAgent = options.includeAgent ?? true
const agentSocket = shouldIncludeAgent ? resolveAgentSocket(target, resolved) : undefined
const agent = agentSocket ? resolveAgentConfigValue(agentSocket, target, resolved) : undefined
if (agent) {
config.agent = agent
}
if (agent && resolved?.forwardAgent) {
config.agentForward = true
}
const keys =
(options.includePrivateKey ?? !agent)
? resolvePrivateKeys(target, resolved)
: resolveUnencryptedExplicitPrivateKeys(target, resolved)
configurePrivateKeyAuthentication(
config as ConnectConfig,
keys,
findEncryptedPrivateKeyPath(keys)
)
return config as ConnectConfig
}
function resolveEffectiveHost(target: SshTarget, resolved: SshResolvedConfig | null): string {
if (isOpenSshConfigBackedTarget(target) && resolved?.hostname) {
return resolved.hostname
}
if (shouldUseResolvedEndpoint(target, resolved)) {
return resolved!.hostname
}
return target.host || resolved?.hostname || target.label
}
function resolveEffectivePort(target: SshTarget, resolved: SshResolvedConfig | null): number {
if (isOpenSshConfigBackedTarget(target) && resolved) {
return resolved.port || target.port || 22
}
// Why: imported config aliases store 22 as the schema default even when an
// included/wildcard OpenSSH rule later resolves a different effective Port.
if (target.configHost && target.port === 22 && resolved?.port) {
return resolved.port
}
return target.port || resolved?.port || 22
}
function shouldUseResolvedEndpoint(target: SshTarget, resolved: SshResolvedConfig | null): boolean {
if (!target.configHost || !resolved?.hostname) {
return false
}
const host = target.host.trim()
return host === '' || host === target.configHost || host === target.label
}
// Why: ProxyJump and jumpHost are syntactic sugar for ProxyCommand.
// OpenSSH internally converts `ProxyJump bastion` to
// `ProxyCommand ssh -W %h:%p bastion`. We do the same so that ssh2
// gets a single proxy spawn path regardless of how the tunnel was configured.
export type EffectiveProxy =
| { kind: 'proxy-command'; command: string }
| { kind: 'jump-host'; jumpHost: string }
export function resolveEffectiveProxy(
target: SshTarget,
resolved: SshResolvedConfig | null
): EffectiveProxy | undefined {
if (isOpenSshConfigBackedTarget(target) && resolved) {
if (resolved.proxyCommand) {
return { kind: 'proxy-command', command: resolved.proxyCommand }
}
return resolved.proxyJump ? { kind: 'jump-host', jumpHost: resolved.proxyJump } : undefined
}
if (target.proxyCommand) {
return { kind: 'proxy-command', command: target.proxyCommand }
}
if (resolved?.proxyCommand) {
return { kind: 'proxy-command', command: resolved.proxyCommand }
}
const jump = target.jumpHost || resolved?.proxyJump
if (jump) {
return { kind: 'jump-host', jumpHost: jump }
}
return undefined
}
// Why: ssh2 doesn't natively support ProxyCommand. When the SSH config
// specifies one (e.g. `cloudflared access ssh --hostname %h`), we spawn
// the command and bridge its stdin/stdout into a Duplex stream that ssh2
// uses as its transport socket via `config.sock`.
function getShellSpawnConfig(command: string): { file: string; args: string[] } {
if (process.platform === 'win32') {
const comspec = process.env.ComSpec || 'cmd.exe'
return { file: comspec, args: ['/d', '/s', '/c', command] }
}
return { file: '/bin/sh', args: ['-c', command] }
}
export function spawnProxyCommand(
proxy: EffectiveProxy,
host: string,
port: number,
user: string
): { process: ChildProcess; sock: NetSocket } {
const proc =
proxy.kind === 'jump-host'
? // Why: ProxyJump is structured input, not a shell snippet. Spawn ssh
// directly so jump-host values cannot escape through shell parsing.
spawn('ssh', ['-W', `${host}:${port}`, '--', proxy.jumpHost], {
stdio: ['pipe', 'pipe', 'pipe']
})
: (() => {
const escape = process.platform === 'win32' ? cmdEscape : shellEscape
const expanded = proxy.command
.replace(/%h/g, escape(host))
.replace(/%p/g, escape(String(port)))
.replace(/%r/g, escape(user))
const shell = getShellSpawnConfig(expanded)
return spawn(shell.file, shell.args, { stdio: ['pipe', 'pipe', 'pipe'] })
})()
// Why: a single PassThrough for both directions creates a feedback loop.
// Reads come from the proxy's stdout; writes go to its stdin.
let cleanedUp = false
const cleanup = (): void => {
if (cleanedUp) {
return
}
cleanedUp = true
proc.stdout!.off('data', onStdoutData)
proc.stdout!.off('end', onStdoutEnd)
proc.stdin!.off('error', onInputError)
proc.off('error', onProcessError)
}
const onStdoutData = (data: Buffer): void => {
stream.push(data)
}
const onStdoutEnd = (): void => {
stream.push(null)
}
const onInputError = (err: Error): void => {
stream.destroy(err)
}
const onProcessError = (err: Error): void => {
stream.destroy(err)
}
const stream = new Duplex({
read() {},
write(chunk, _encoding, cb) {
proc.stdin!.write(chunk, cb)
},
destroy(err, cb) {
cleanup()
cb(err)
}
})
proc.stdout!.on('data', onStdoutData)
proc.stdout!.on('end', onStdoutEnd)
proc.stdin!.on('error', onInputError)
proc.on('error', onProcessError)
return { process: proc, sock: stream as unknown as NetSocket }
}