Files
orca/src/main/ssh/ssh-connection-auth-fallback.test.ts
T
NeilandBrennan Benson fbe94ceff6 fix: close readiness gaps found by merged-change audit (#17159)
* fix(ssh): fence stale kills and retired pane replay

* fix(ssh): support cancellable interactive authentication

* fix(ssh): await remote catalog before snapshot adoption

* fix(pty): contain Windows ConPTY input failures

* fix(power): avoid redundant macOS display blocking

* perf(editor): narrow markdown override subscriptions

* fix(quick-open): close directory handles after reads

* refactor(linux): remove unused proc socket scanner

* fix(usage): apply flat Sonnet 4.6 pricing

* ci: prime Node next native test cache

* docs(skills): resolve snapshot cleanup data path

* fix(ssh): recover install locks after host reboot

* test(ssh): recognize boot-aware install locks

* test(ssh): prove previous-boot lock recovery live

* test(wire): pin pre-metadata release coverage

* fix(terminal): preserve remote tab ownership through recovery races

* test(runtime): fence replaced terminal handles in agent guard

* fix(ssh): preserve remote snapshot authority across polls

* fix(pty): contain late ConPTY output EPIPE

* test(pty): register Windows exit watcher before kill

* fix: close SSH and tab readiness race gaps

* fix(tabs): retain headless order and placeholder titles

* fix(build): avoid parallel electron-vite config race

* test(windows): avoid MSYS temp path rewriting

* test(windows): avoid killing exited PTY

* fix(pty): avoid late ConPTY input teardown race

* fix(terminal): sync reconnect error ownership after commit

* fix(runtime): use canonical worktree identity comparison

* test(ssh): assert complete cold-hydration baseline

* test(windows): invoke quoted retention fixture via PowerShell

* test(windows): read ConPTY grid through mode con

* fix(terminal): publish PTY replacements atomically

* fix(terminal): infer stale identity on reattach

* fix(terminal): fence stale pane PTY callbacks

* fix(terminal): fence stale pane binds after rebind

* fix(terminal): reject stale pane transport callbacks

* fix(terminal): fence mirrored reattach spawn callbacks

* fix(terminal): replace stale pane PTYs on remount

* fix(ci): size the Windows launcher-compile test budget from measurement

`native-smoke (windows-latest)` fails ~4.5% of runs on
`preserves a multiline argument through the compiled remote launcher`
with "Test timed out in 15000ms" — on unrelated PRs, for reasons that
have nothing to do with them. Across 176 sampled attempts it is the only
red that job produced, and it hit seven different PRs in two days:
#16900, #16904, #16915, #16955 (twice), #16979, #17014, #17085.

The test is six process creations: powershell.exe forks csc.exe, then
the freshly compiled orca.exe forks node.exe, twice. Hosted Windows
runners periodically slow process creation down, and this test amplifies
that far harder than anything else in the job. Comparing the 80 attempts
where it ran under 3s against the 12 where it ran over 12s, its own
median goes 2198ms -> 15917ms (7.2x) while the same file's
powershell-only test moves 556 -> 686ms (1.2x), the cmd.exe and Git Bash
process tests in the neighbouring file move 1.4x, and the other 35 files
put together move 1.5x.

Measured across those 176 attempts: 1881ms to 35438ms, p50 4264ms,
correlation +0.881 with the job's total Vitest duration. 8 of 176 (4.5%)
exceeded the 15s cap; 2 of 176 (1.1%) also exceeded the shared 30s
testTimeout, so deleting the override and inheriting the config is not
enough on its own. 60s clears all 176 with 1.7x headroom on the worst.

This is slow, not hung. Every body here is synchronous spawnSync, so
Vitest cannot interrupt one — the timer fires only after the body
returns and the reported duration is real elapsed time. That is why a
failure reads `× ... 22464ms` under `Test timed out in 15000ms`. The
work finished; the stopwatch was short. Seven reruns at one identical
head measured 2053 / 4680 / 5551 / 8732 / 13506 / 14868 / 21937ms — the
last of those would have been red on code that had not changed.

The 15s came from #8897, which raised this test off Vitest's built-in 5s
default because the job then ran bare `pnpm vitest run`. #8909 landed
3h27m later and pointed the job at config/vitest.config.ts, which is the
real fix for that. The constant stayed behind and has been the binding
budget ever since.

* fix(terminal): fence stale remount reattach ownership

* fix(terminal): reconcile mounted pane identity after replacement

* fix(terminal): fence stale reattach fallback ownership

* fix(terminal): fence deferred SSH reattach ownership

* fix(terminal): fence stale split pane ownership callbacks

* fix(terminal): keep stale spawns from consuming startup

---------

Co-authored-by: Brennan Benson <79079362+brennanb2025@users.noreply.github.com>
2026-08-31 08:17:40 -07:00

415 lines
14 KiB
TypeScript

import { describe, expect, it, vi, beforeEach } from 'vitest'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import {
clientInstances,
emitSshEvent,
nextSshClientCreation,
resetSshConnectionMocks,
ssh2Mock
} from './ssh-connection-test-harness'
import { createCallbacks, createTarget } from './ssh-connection-test-fixtures'
import { SshConnection } from './ssh-connection'
import { resolveWithSshG } from './ssh-config-parser'
vi.mock('ssh2', async () => (await import('./ssh-connection-test-harness')).createSsh2Module())
vi.mock('./system-ssh-binary', async () =>
(await import('./ssh-connection-test-harness')).createSystemSshBinaryModule()
)
vi.mock('./ssh-system-fallback', async () =>
(await import('./ssh-connection-test-harness')).createSystemFallbackModule()
)
vi.mock('./ssh-control-socket', async () =>
(await import('./ssh-connection-test-harness')).createControlSocketModule()
)
vi.mock('./ssh-config-parser', async () =>
(await import('./ssh-connection-test-harness')).createSshConfigParserModule()
)
describe('SshConnection', () => {
beforeEach(() => {
resetSshConnectionMocks()
})
it('resolves OpenSSH config using configHost when present', async () => {
const callbacks = createCallbacks()
const conn = new SshConnection(
createTarget({
label: 'Friendly Name',
configHost: 'ssh-alias'
}),
callbacks
)
await conn.connect()
expect(resolveWithSshG).toHaveBeenCalledWith('ssh-alias')
})
it('tries ssh-agent before reading an explicit private key', async () => {
vi.stubEnv('SSH_AUTH_SOCK', '/tmp/agent.sock')
const callbacks = createCallbacks({
onCredentialRequest: vi.fn()
})
const conn = new SshConnection(
createTarget({
identityFile: '/tmp/encrypted-key'
}),
callbacks
)
await conn.connect()
const initialConfig = clientInstances[0].lastConnectConfig as {
agent?: unknown
privateKey?: unknown
}
expect(initialConfig.agent).toBe('/tmp/agent.sock')
expect(initialConfig.privateKey).toBeUndefined()
expect(callbacks.onCredentialRequest).not.toHaveBeenCalled()
})
it('falls back to direct private key auth when agent auth fails', async () => {
vi.stubEnv('SSH_AUTH_SOCK', '/tmp/agent.sock')
const tempDir = mkdtempSync(join(tmpdir(), 'orca-ssh-key-'))
const keyPath = join(tempDir, 'id_ed25519')
writeFileSync(keyPath, 'test-key')
ssh2Mock.connectSequence = [new Error('All configured authentication methods failed'), 'ready']
try {
const conn = new SshConnection(createTarget({ identityFile: keyPath }), createCallbacks())
await conn.connect()
expect(clientInstances).toHaveLength(2)
const initialConfig = clientInstances[0].lastConnectConfig as {
agent?: unknown
privateKey?: unknown
}
const fallbackConfig = clientInstances[1].lastConnectConfig as {
agent?: unknown
privateKey?: Buffer
}
expect(initialConfig.agent).toBe('/tmp/agent.sock')
expect(initialConfig.privateKey).toBeUndefined()
expect(fallbackConfig.agent).toBeUndefined()
expect(fallbackConfig.privateKey).toEqual(Buffer.from('test-key'))
} finally {
rmSync(tempDir, { recursive: true, force: true })
}
})
it('falls back to direct private key auth when the agent socket is unavailable', async () => {
vi.stubEnv('SSH_AUTH_SOCK', '/tmp/stale-agent.sock')
const tempDir = mkdtempSync(join(tmpdir(), 'orca-ssh-key-'))
const keyPath = join(tempDir, 'id_ed25519')
writeFileSync(keyPath, 'test-key')
const agentError = new Error('Failed to connect to agent') as Error & { level: string }
agentError.level = 'agent'
ssh2Mock.connectSequence = [agentError, 'ready']
try {
const conn = new SshConnection(createTarget({ identityFile: keyPath }), createCallbacks())
await conn.connect()
expect(clientInstances).toHaveLength(2)
const fallbackConfig = clientInstances[1].lastConnectConfig as {
agent?: unknown
privateKey?: Buffer
}
expect(fallbackConfig.agent).toBeUndefined()
expect(fallbackConfig.privateKey).toEqual(Buffer.from('test-key'))
} finally {
rmSync(tempDir, { recursive: true, force: true })
}
})
it('falls back to direct private key auth after too many agent authentication failures', async () => {
vi.stubEnv('SSH_AUTH_SOCK', '/tmp/agent.sock')
const tempDir = mkdtempSync(join(tmpdir(), 'orca-ssh-key-'))
const keyPath = join(tempDir, 'id_ed25519')
writeFileSync(keyPath, 'test-key')
ssh2Mock.connectSequence = [
new Error('Received disconnect: Too many authentication failures'),
'ready'
]
try {
const conn = new SshConnection(createTarget({ identityFile: keyPath }), createCallbacks())
await conn.connect()
expect(clientInstances).toHaveLength(2)
const fallbackConfig = clientInstances[1].lastConnectConfig as {
agent?: unknown
privateKey?: Buffer
}
expect(fallbackConfig.agent).toBeUndefined()
expect(fallbackConfig.privateKey).toEqual(Buffer.from('test-key'))
} finally {
rmSync(tempDir, { recursive: true, force: true })
}
})
it('retries password auth without a stale agent when no private key fallback exists', async () => {
vi.stubEnv('SSH_AUTH_SOCK', '/tmp/stale-agent.sock')
const agentError = new Error('Failed to connect to agent') as Error & { level: string }
agentError.level = 'agent'
ssh2Mock.connectSequence = [agentError, 'ready']
const onCredentialRequest = vi.fn(async () => 'password-123')
const conn = new SshConnection(
createTarget({ identityFile: join(tmpdir(), 'missing-key') }),
createCallbacks({ onCredentialRequest })
)
await conn.connect()
expect(clientInstances).toHaveLength(2)
const retryConfig = clientInstances[1].lastConnectConfig as {
agent?: unknown
password?: string
privateKey?: unknown
}
expect(retryConfig.agent).toBeUndefined()
expect(retryConfig.password).toBe('password-123')
expect(retryConfig.privateKey).toBeUndefined()
expect(onCredentialRequest).toHaveBeenCalledWith(
'target-1',
'password',
'example.com',
expect.any(AbortSignal)
)
})
it('retries password auth with the no-agent key config after direct key fallback fails', async () => {
vi.stubEnv('SSH_AUTH_SOCK', '/tmp/agent.sock')
const tempDir = mkdtempSync(join(tmpdir(), 'orca-ssh-key-'))
const keyPath = join(tempDir, 'id_ed25519')
writeFileSync(keyPath, 'test-key')
ssh2Mock.connectSequence = [
new Error('All configured authentication methods failed'),
new Error('All configured authentication methods failed'),
'ready'
]
const onCredentialRequest = vi.fn(async () => 'password-123')
try {
const conn = new SshConnection(
createTarget({ identityFile: keyPath }),
createCallbacks({ onCredentialRequest })
)
await conn.connect()
expect(clientInstances).toHaveLength(3)
const keyRetryConfig = clientInstances[1].lastConnectConfig as {
agent?: unknown
privateKey?: Buffer
}
const passwordRetryConfig = clientInstances[2].lastConnectConfig as {
agent?: unknown
password?: string
privateKey?: Buffer
}
expect(keyRetryConfig.agent).toBeUndefined()
expect(keyRetryConfig.privateKey).toEqual(Buffer.from('test-key'))
expect(passwordRetryConfig.agent).toBeUndefined()
expect(passwordRetryConfig.privateKey).toEqual(Buffer.from('test-key'))
expect(passwordRetryConfig.password).toBe('password-123')
} finally {
rmSync(tempDir, { recursive: true, force: true })
}
})
it('answers bounded keyboard-interactive challenges such as Duo 2FA', async () => {
vi.useFakeTimers()
const onCredentialRequest = vi.fn().mockResolvedValueOnce('1').mockResolvedValueOnce('123456')
try {
const conn = new SshConnection(createTarget(), createCallbacks({ onCredentialRequest }))
const clientCreated = nextSshClientCreation()
const connected = conn.connect()
await clientCreated
const finish = vi.fn()
emitSshEvent(
'keyboard-interactive',
'Duo two-factor login',
'Select push or enter a passcode.',
'',
[
{ prompt: 'Option:', echo: false },
{ prompt: 'Passcode:', echo: false }
],
finish
)
for (let turn = 0; turn < 8 && finish.mock.calls.length === 0; turn += 1) {
await Promise.resolve()
}
expect(clientInstances[0].lastConnectConfig).toMatchObject({ tryKeyboard: true })
expect(onCredentialRequest).toHaveBeenNthCalledWith(
1,
'target-1',
'keyboard-interactive',
'Duo two-factor login\nSelect push or enter a passcode.\nOption:',
expect.any(AbortSignal)
)
expect(onCredentialRequest).toHaveBeenNthCalledWith(
2,
'target-1',
'keyboard-interactive',
'Duo two-factor login\nSelect push or enter a passcode.\nPasscode:',
expect.any(AbortSignal)
)
expect(finish).toHaveBeenCalledWith(['1', '123456'])
await vi.advanceTimersByTimeAsync(1)
await connected
} finally {
vi.useRealTimers()
}
})
it('rearms the handshake budget for each slow prompt in one keyboard-interactive round', async () => {
vi.useFakeTimers()
ssh2Mock.connectBehavior = 'pending'
const firstResponse = Promise.withResolvers<string | null>()
const secondResponse = Promise.withResolvers<string | null>()
const onCredentialRequest = vi
.fn()
.mockImplementationOnce(() => firstResponse.promise)
.mockImplementationOnce(() => secondResponse.promise)
try {
const conn = new SshConnection(createTarget(), createCallbacks({ onCredentialRequest }))
const clientCreated = nextSshClientCreation()
const connected = conn.connect()
let settled = false
void connected.then(
() => {
settled = true
},
() => {
settled = true
}
)
await clientCreated
await vi.advanceTimersByTimeAsync(1)
const finish = vi.fn()
emitSshEvent(
'keyboard-interactive',
'Duo two-factor login',
'Complete both checks.',
'',
[
{ prompt: 'Option:', echo: false },
{ prompt: 'Passcode:', echo: false }
],
finish
)
await vi.advanceTimersByTimeAsync(100_000)
firstResponse.resolve('1')
for (let turn = 0; turn < 4 && onCredentialRequest.mock.calls.length < 2; turn += 1) {
await Promise.resolve()
}
expect(onCredentialRequest).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(30_000)
expect(settled).toBe(false)
expect(finish).not.toHaveBeenCalled()
secondResponse.resolve('123456')
for (let turn = 0; turn < 4 && finish.mock.calls.length === 0; turn += 1) {
await Promise.resolve()
}
expect(finish).toHaveBeenCalledWith(['1', '123456'])
emitSshEvent('ready')
await connected
} finally {
vi.useRealTimers()
}
})
it('aborts an in-flight keyboard challenge when the connection is disconnected', async () => {
vi.useFakeTimers()
ssh2Mock.connectBehavior = 'pending'
let credentialSignal: AbortSignal | undefined
const onCredentialRequest = vi.fn(
(_targetId: string, _kind: string, _detail: string, signal?: AbortSignal) => {
credentialSignal = signal
const response = Promise.withResolvers<string | null>()
if (signal?.aborted) {
response.resolve(null)
} else {
signal?.addEventListener('abort', () => response.resolve(null), { once: true })
}
return response.promise
}
)
try {
const conn = new SshConnection(createTarget(), createCallbacks({ onCredentialRequest }))
const clientCreated = nextSshClientCreation()
const connected = conn.connect()
const connectionResult = connected.then(
() => null,
(error: unknown) => error
)
await clientCreated
await vi.advanceTimersByTimeAsync(1)
const finish = vi.fn()
emitSshEvent(
'keyboard-interactive',
'Duo two-factor login',
'Approve the push.',
'',
[{ prompt: 'Response:', echo: false }],
finish
)
await Promise.resolve()
expect(credentialSignal?.aborted).toBe(false)
await conn.disconnect()
expect(credentialSignal?.aborted).toBe(true)
await expect(connectionResult).resolves.toBeInstanceOf(Error)
for (let turn = 0; turn < 4 && finish.mock.calls.length === 0; turn += 1) {
await Promise.resolve()
}
expect(finish).toHaveBeenCalledWith([])
} finally {
vi.useRealTimers()
}
})
it('does not prompt twice when post-agent private key passphrase is cancelled', async () => {
vi.stubEnv('SSH_AUTH_SOCK', '/tmp/agent.sock')
const tempDir = mkdtempSync(join(tmpdir(), 'orca-ssh-key-'))
const keyPath = join(tempDir, 'id_ed25519')
writeFileSync(keyPath, 'test-key')
ssh2Mock.connectSequence = [
new Error('All configured authentication methods failed'),
new Error('Encrypted private OpenSSH key detected, but no passphrase given')
]
const onCredentialRequest = vi.fn(async () => null)
try {
const conn = new SshConnection(
createTarget({ identityFile: keyPath }),
createCallbacks({ onCredentialRequest })
)
await expect(conn.connect()).rejects.toThrow('Encrypted private OpenSSH key detected')
expect(onCredentialRequest).toHaveBeenCalledTimes(1)
expect(onCredentialRequest).toHaveBeenCalledWith(
'target-1',
'passphrase',
keyPath,
expect.any(AbortSignal)
)
} finally {
rmSync(tempDir, { recursive: true, force: true })
}
})
})