Files
orca/src/main/ssh/ssh-channel-multiplexer.test.ts
T
JinjingandOrcaWin 5f7807497e feat(ssh): bound relay PTY output end to end (#11005)
* docs: design SSH relay PTY backpressure

* fix(ssh): bound relay frame decoding

* fix(relay): bound PTY output publication

* fix(ssh): bound PTY model admission

* fix(ssh): settle closed model admissions

* feat(ssh): negotiate bounded PTY consumer sessions

* fix(ssh): fence exit on renderer settlement

* feat(ssh): track PTY source credit end to end

* fix(ssh): recover bounded PTY output across reconnect

* feat(ssh): complete relay PTY output backpressure

* fix(ssh): close final PTY source credit races

* docs(ssh): record final backpressure validation

* feat(ssh): complete relay PTY source-credit lifecycle

* test(ssh): complete provider notification fixture

* fix(ssh): preserve terminal source credit across rotation

* fix(ssh): fail closed on recovery cancellation

* fix(ssh): prioritize mux control writes after drain

* fix(ssh): retire canceled relay restore deliveries

* fix(ssh): order exit cancellation cleanup

* fix(ssh): gate provisional source activation

* test(ssh): register mux drain-priority coverage

* fix(ssh): type stale owner recovery mismatches

* fix(ssh): close projection replacement races

* fix(relay): contain streaming edge failures

* fix(ssh): secure relay endpoint credentials

* docs(ssh): reconcile final backpressure lifecycle

* fix(ssh): bound main IPC output lifecycle

* fix(ssh): close recovery ownership gaps

* docs(ssh): record exact artifact validation

* fix(ssh): reject reclaimed snapshot replacements

* fix(ssh): fence model admission across reconnect

* fix(ssh): contain migration failure per PTY

* docs(ssh): record final exact-head validation

* test(ssh): align deploy fixtures with credential publication

* feat(ssh): add per-target bounded output setting

* fix(ssh): close source recovery review gaps

* fix(ssh): latch source credit environment override

* feat(ssh): make PTY source credit the default

* docs(ssh): record always-on relay validation

* docs(ssh): bind validation to current main

* test(ssh): grant source credit in IPC fixture

* test(ssh): grant source credit in fake relay

---------

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
2026-07-29 17:03:15 -07:00

566 lines
19 KiB
TypeScript

import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { SshChannelMultiplexer, type MultiplexerTransport } from './ssh-channel-multiplexer'
import { encodeFrame, MessageType, HEADER_LENGTH, encodeKeepAliveFrame } from './relay-protocol'
function createMockTransport(): MultiplexerTransport & {
dataCallbacks: ((data: Buffer) => void)[]
closeCallbacks: (() => void)[]
written: Buffer[]
} {
const dataCallbacks: ((data: Buffer) => void)[] = []
const closeCallbacks: (() => void)[] = []
const written: Buffer[] = []
return {
write: (data: Buffer) => {
written.push(data)
},
onData: (cb) => dataCallbacks.push(cb),
onClose: (cb) => closeCallbacks.push(cb),
dataCallbacks,
closeCallbacks,
written
}
}
function makeResponseFrame(requestId: number, result: unknown, seq: number): Buffer {
const payload = Buffer.from(
JSON.stringify({
jsonrpc: '2.0',
id: requestId,
result
})
)
return encodeFrame(MessageType.Regular, seq, 0, payload)
}
function makeErrorResponseFrame(
requestId: number,
code: number,
message: string,
seq: number
): Buffer {
const payload = Buffer.from(
JSON.stringify({
jsonrpc: '2.0',
id: requestId,
error: { code, message }
})
)
return encodeFrame(MessageType.Regular, seq, 0, payload)
}
function makeNotificationFrame(
method: string,
params: Record<string, unknown>,
seq: number
): Buffer {
const payload = Buffer.from(
JSON.stringify({
jsonrpc: '2.0',
method,
params
})
)
return encodeFrame(MessageType.Regular, seq, 0, payload)
}
type MuxInternals = {
notificationHandlers: unknown[]
methodNotificationHandlers: Map<string, Set<unknown>>
disposeHandlers: unknown[]
lastReceivedAt: number
unackedTimestamps: Map<number, number>
writerSaturated: boolean
}
function getMuxInternals(instance: SshChannelMultiplexer): MuxInternals {
return instance as unknown as MuxInternals
}
describe('SshChannelMultiplexer', () => {
let transport: ReturnType<typeof createMockTransport>
let mux: SshChannelMultiplexer
beforeEach(() => {
vi.useFakeTimers()
transport = createMockTransport()
mux = new SshChannelMultiplexer(transport)
})
afterEach(() => {
mux.dispose()
vi.useRealTimers()
})
describe('request/response', () => {
it('sends a JSON-RPC request and resolves on response', async () => {
const promise = mux.request('pty.spawn', { cols: 80, rows: 24 })
// Verify the request was written
expect(transport.written.length).toBe(1)
const frame = transport.written[0]
expect(frame[0]).toBe(MessageType.Regular)
const payloadLen = frame.readUInt32BE(9)
const payload = JSON.parse(
frame.subarray(HEADER_LENGTH, HEADER_LENGTH + payloadLen).toString()
)
expect(payload.method).toBe('pty.spawn')
expect(payload.id).toBe(1)
// Simulate response from relay
const response = makeResponseFrame(1, { id: 'pty-1' }, 1)
transport.dataCallbacks[0](response)
const result = await promise
expect(result).toEqual({ id: 'pty-1' })
})
it('rejects on error response', async () => {
const promise = mux.request('pty.spawn', { cols: 80, rows: 24 })
const response = makeErrorResponseFrame(1, -33004, 'PTY allocation failed', 1)
transport.dataCallbacks[0](response)
await expect(promise).rejects.toThrow('PTY allocation failed')
})
it('runs beforeResolve before an adjacent notification in the same decoder turn', async () => {
const order: string[] = []
mux.onNotification(() => order.push('notification'))
const promise = mux.request(
'pty.attach',
{ id: 'pty-1' },
{
beforeResolve: () => order.push('beforeResolve')
}
)
transport.dataCallbacks[0](
Buffer.concat([
makeResponseFrame(1, { incarnationId: 'incarnation-1' }, 1),
makeNotificationFrame('pty.data', { id: 'pty-1', data: 'first' }, 2)
])
)
expect(order).toEqual(['beforeResolve', 'notification'])
await expect(promise).resolves.toEqual({ incarnationId: 'incarnation-1' })
})
it('times out after 30s with no response', async () => {
const promise = mux.request('pty.spawn')
// Feed keepalive frames periodically to prevent the connection-level
// timeout (20s no-data) from firing before the 30s request timeout.
for (let i = 0; i < 6; i++) {
vi.advanceTimersByTime(5_000)
transport.dataCallbacks[0](encodeKeepAliveFrame(i + 1, 0))
}
vi.advanceTimersByTime(1_000)
await expect(promise).rejects.toThrow('timed out')
const cancelPayload = JSON.parse(
transport.written
.at(-1)!
.subarray(HEADER_LENGTH, HEADER_LENGTH + transport.written.at(-1)!.readUInt32BE(9))
.toString()
)
expect(cancelPayload).toMatchObject({
method: 'rpc.cancel',
params: { id: 1 }
})
})
it('uses per-request timeout overrides', async () => {
const promise = mux.request('fs.workspaceSpaceScan', {}, { timeoutMs: 60_000 })
for (let i = 0; i < 6; i++) {
vi.advanceTimersByTime(5_000)
transport.dataCallbacks[0](encodeKeepAliveFrame(i + 1, 0))
}
await Promise.resolve()
const requestWrites = transport.written.filter((frame) => frame[0] === MessageType.Regular)
expect(requestWrites).toHaveLength(1)
for (let i = 6; i < 12; i++) {
vi.advanceTimersByTime(5_000)
transport.dataCallbacks[0](encodeKeepAliveFrame(i + 1, 0))
}
await expect(promise).rejects.toThrow('timed out after 60000ms')
})
it('assigns unique request IDs', async () => {
void mux.request('method1').catch(() => {})
void mux.request('method2').catch(() => {})
expect(transport.written.length).toBe(2)
const id1 = JSON.parse(
transport.written[0]
.subarray(HEADER_LENGTH, HEADER_LENGTH + transport.written[0].readUInt32BE(9))
.toString()
).id
const id2 = JSON.parse(
transport.written[1]
.subarray(HEADER_LENGTH, HEADER_LENGTH + transport.written[1].readUInt32BE(9))
.toString()
).id
expect(id1).not.toBe(id2)
})
})
describe('notifications', () => {
it('sends notifications without expecting a response', () => {
mux.notify('pty.data', { id: 'pty-1', data: 'hello' })
expect(transport.written.length).toBe(1)
const payload = JSON.parse(
transport.written[0]
.subarray(HEADER_LENGTH, HEADER_LENGTH + transport.written[0].readUInt32BE(9))
.toString()
)
expect(payload.method).toBe('pty.data')
expect(payload.id).toBeUndefined()
})
it('dispatches incoming notifications to handler', () => {
const handler = vi.fn()
mux.onNotification(handler)
const frame = makeNotificationFrame('pty.exit', { id: 'pty-1', code: 0 }, 1)
transport.dataCallbacks[0](frame)
expect(handler).toHaveBeenCalledWith('pty.exit', { id: 'pty-1', code: 0 })
})
it('typed dispatcher only fires for its method', () => {
const chunkHandler = vi.fn()
const otherHandler = vi.fn()
const generic = vi.fn()
mux.onNotificationByMethod('fs.streamChunk', chunkHandler)
mux.onNotificationByMethod('fs.streamEnd', otherHandler)
mux.onNotification(generic)
transport.dataCallbacks[0](
makeNotificationFrame('fs.streamChunk', { streamId: 1, seq: 0, data: 'aGk=' }, 1)
)
expect(chunkHandler).toHaveBeenCalledWith({ streamId: 1, seq: 0, data: 'aGk=' })
expect(otherHandler).not.toHaveBeenCalled()
expect(generic).toHaveBeenCalledWith('fs.streamChunk', {
streamId: 1,
seq: 0,
data: 'aGk='
})
})
it('typed dispatcher unsubscribe removes only that handler', () => {
const a = vi.fn()
const b = vi.fn()
const unsubA = mux.onNotificationByMethod('fs.streamEnd', a)
mux.onNotificationByMethod('fs.streamEnd', b)
unsubA()
transport.dataCallbacks[0](makeNotificationFrame('fs.streamEnd', { streamId: 7 }, 1))
expect(a).not.toHaveBeenCalled()
expect(b).toHaveBeenCalledWith({ streamId: 7 })
})
it('contains generic notification handler failures', () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const badHandler = vi.fn(() => {
throw new Error('subscriber exploded')
})
const goodHandler = vi.fn()
mux.onNotification(badHandler)
mux.onNotification(goodHandler)
expect(() =>
transport.dataCallbacks[0](makeNotificationFrame('pty.data', { id: 'pty-1' }, 1))
).not.toThrow()
expect(badHandler).toHaveBeenCalled()
expect(goodHandler).toHaveBeenCalledWith('pty.data', { id: 'pty-1' })
expect(mux.isDisposed()).toBe(false)
expect(warnSpy).toHaveBeenCalledWith(
'[ssh-mux] Notification handler failed for pty.data: subscriber exploded'
)
})
it('contains method notification handler failures', () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const badHandler = vi.fn(() => {
throw new Error('stream consumer exploded')
})
const goodHandler = vi.fn()
mux.onNotificationByMethod('fs.streamChunk', badHandler)
mux.onNotificationByMethod('fs.streamChunk', goodHandler)
expect(() =>
transport.dataCallbacks[0](
makeNotificationFrame('fs.streamChunk', { streamId: 1, seq: 0, data: 'aGk=' }, 1)
)
).not.toThrow()
expect(badHandler).toHaveBeenCalled()
expect(goodHandler).toHaveBeenCalledWith({ streamId: 1, seq: 0, data: 'aGk=' })
expect(mux.isDisposed()).toBe(false)
expect(warnSpy).toHaveBeenCalledWith(
'[ssh-mux] Method notification handler failed for fs.streamChunk: stream consumer exploded'
)
})
})
describe('keepalive', () => {
it('sends one keepalive frame per cadence tick', () => {
const initialWrites = transport.written.length
vi.advanceTimersByTime(5_000)
expect(transport.written).toHaveLength(initialWrites + 1)
expect(transport.written.at(-1)![0]).toBe(MessageType.KeepAlive)
vi.advanceTimersByTime(5_000)
expect(transport.written).toHaveLength(initialWrites + 2)
expect(transport.written.at(-1)![0]).toBe(MessageType.KeepAlive)
})
it('turns transport write failures into connection loss instead of throwing from the timer', () => {
const writeError = new Error('write EPIPE')
transport.write = vi.fn(() => {
throw writeError
})
expect(() => vi.advanceTimersByTime(5_000)).not.toThrow()
expect(mux.isDisposed()).toBe(true)
})
it('drives keepalive sends AND dead-link detection from a single interval', () => {
// The keepalive send and the liveness/timeout check were merged from two
// 5s intervals into one; there must be exactly one recurring timer.
expect(vi.getTimerCount()).toBe(1)
// Send half: a keepalive is written on the tick.
const before = transport.written.length
vi.advanceTimersByTime(5_000)
expect(transport.written.length).toBeGreaterThan(before)
expect(transport.written.at(-1)![0]).toBe(MessageType.KeepAlive)
expect(vi.getTimerCount()).toBe(1)
// Check half: with no inbound frames or acks, the same interval declares
// the link dead (no-data + oldest-unacked both exceed the 20s window).
expect(mux.isDisposed()).toBe(false)
vi.advanceTimersByTime(25_000)
expect(mux.isDisposed()).toBe(true)
})
it('suppresses false death while locally saturated and rebases both clocks on drain', () => {
mux.dispose()
let drain = (): void => {}
const written: Buffer[] = []
const saturatedTransport: MultiplexerTransport = {
write: (data) => {
written.push(data)
return false
},
supportsWriteSettlement: true,
onDrain: (callback) => {
drain = callback
},
onData: vi.fn(),
onClose: vi.fn()
}
mux = new SshChannelMultiplexer(saturatedTransport)
vi.advanceTimersByTime(5_000)
expect(getMuxInternals(mux).writerSaturated).toBe(true)
vi.advanceTimersByTime(25_000)
expect(mux.isDisposed()).toBe(false)
expect(written).toHaveLength(1)
drain()
const resumedAt = Date.now()
const internals = getMuxInternals(mux)
expect(internals.writerSaturated).toBe(false)
expect(internals.lastReceivedAt).toBe(resumedAt)
expect(new Set(internals.unackedTimestamps.values())).toEqual(new Set([resumedAt]))
vi.advanceTimersByTime(20_000)
expect(mux.isDisposed()).toBe(false)
vi.advanceTimersByTime(5_000)
expect(mux.isDisposed()).toBe(true)
})
})
describe('wake guard (timer pause across system sleep, #7773)', () => {
it('sends one fresh probe per link and rebaselines liveness after a wake gap', () => {
const secondTransport = createMockTransport()
const secondMux = new SshChannelMultiplexer(secondTransport)
try {
// Reach steady state with pending unacked keepalives (<5s old at pause).
vi.advanceTimersByTime(5_000)
expect(mux.isDisposed()).toBe(false)
expect(secondMux.isDisposed()).toBe(false)
const internals = getMuxInternals(mux)
const secondInternals = getMuxInternals(secondMux)
const previousReceivedAt = internals.lastReceivedAt
const writesBefore = transport.written.length
const secondWritesBefore = secondTransport.written.length
// Simulate sleep/App Nap: wall clock jumps far ahead with no ticks.
vi.setSystemTime(Date.now() + 60 * 60 * 1000)
vi.advanceTimersByTime(5_000)
const resumedAt = Date.now()
expect(mux.isDisposed()).toBe(false)
expect(secondMux.isDisposed()).toBe(false)
expect(transport.written).toHaveLength(writesBefore + 1)
expect(secondTransport.written).toHaveLength(secondWritesBefore + 1)
expect(transport.written.at(-1)![0]).toBe(MessageType.KeepAlive)
expect(secondTransport.written.at(-1)![0]).toBe(MessageType.KeepAlive)
expect(internals.lastReceivedAt).toBe(resumedAt)
expect(internals.lastReceivedAt).toBeGreaterThan(previousReceivedAt)
expect(new Set(internals.unackedTimestamps.values())).toEqual(new Set([resumedAt]))
expect(secondInternals.lastReceivedAt).toBe(resumedAt)
expect(new Set(secondInternals.unackedTimestamps.values())).toEqual(new Set([resumedAt]))
} finally {
secondMux.dispose()
}
})
it('keeps the link alive after wake when frames resume', () => {
vi.advanceTimersByTime(5_000)
vi.setSystemTime(Date.now() + 60 * 60 * 1000)
vi.advanceTimersByTime(5_000) // guard tick
// The relay answers the post-wake probe; the link must stay up.
let seq = 1
for (let i = 0; i < 8; i++) {
vi.advanceTimersByTime(5_000)
transport.dataCallbacks[0](encodeKeepAliveFrame(seq++, 0))
}
expect(mux.isDisposed()).toBe(false)
})
it('still detects a genuinely dead link within the next window after wake', () => {
vi.advanceTimersByTime(5_000)
vi.setSystemTime(Date.now() + 60 * 60 * 1000)
vi.advanceTimersByTime(5_000) // guard tick: reset + probe, no kill
expect(mux.isDisposed()).toBe(false)
// No frames arrive after the guard reset; the honest window expires.
vi.advanceTimersByTime(25_000)
expect(mux.isDisposed()).toBe(true)
})
})
describe('probeLiveness', () => {
it('sends a keepalive and resolves true when any frame arrives', async () => {
const writesBefore = transport.written.length
const probe = mux.probeLiveness(5_000)
expect(transport.written.length).toBe(writesBefore + 1)
expect(transport.written.at(-1)![0]).toBe(MessageType.KeepAlive)
transport.dataCallbacks[0](encodeKeepAliveFrame(1, 0))
await expect(probe).resolves.toBe(true)
})
it('resolves false when no frame arrives before the timeout', async () => {
const probe = mux.probeLiveness(5_000)
vi.advanceTimersByTime(5_000)
await expect(probe).resolves.toBe(false)
})
it('resolves false when the mux is disposed while probing', async () => {
const probe = mux.probeLiveness(5_000)
mux.dispose()
await expect(probe).resolves.toBe(false)
})
it('resolves false immediately on a disposed mux', async () => {
mux.dispose()
await expect(mux.probeLiveness(5_000)).resolves.toBe(false)
})
})
describe('dispose', () => {
it('rejects all pending requests on dispose', async () => {
const promise = mux.request('pty.spawn')
mux.dispose()
await expect(promise).rejects.toThrow('Multiplexer disposed')
})
it('throws on request after dispose', async () => {
mux.dispose()
await expect(mux.request('pty.spawn')).rejects.toThrow('Multiplexer disposed')
})
it('ignores notify after dispose', () => {
mux.dispose()
mux.notify('pty.data', { id: 'pty-1', data: 'x' })
// No writes should happen after the initial keepalive writes
})
it('reports isDisposed correctly', () => {
expect(mux.isDisposed()).toBe(false)
mux.dispose()
expect(mux.isDisposed()).toBe(true)
})
it('clears registered handlers on dispose', () => {
const disposeHandler = vi.fn()
mux.onNotification(vi.fn())
mux.onNotificationByMethod('fs.streamChunk', vi.fn())
mux.onDispose(disposeHandler)
const internals = getMuxInternals(mux)
expect(internals.notificationHandlers).toHaveLength(1)
expect(internals.methodNotificationHandlers.size).toBe(1)
expect(internals.disposeHandlers).toHaveLength(1)
mux.dispose()
expect(disposeHandler).toHaveBeenCalledWith('shutdown')
expect(internals.notificationHandlers).toHaveLength(0)
expect(internals.methodNotificationHandlers.size).toBe(0)
expect(internals.disposeHandlers).toHaveLength(0)
})
it('does not retain handlers registered after dispose', () => {
mux.dispose()
const disposeNotification = mux.onNotification(vi.fn())
const disposeMethod = mux.onNotificationByMethod('fs.streamChunk', vi.fn())
const disposeLifecycle = mux.onDispose(vi.fn())
const internals = getMuxInternals(mux)
expect(internals.notificationHandlers).toHaveLength(0)
expect(internals.methodNotificationHandlers.size).toBe(0)
expect(internals.disposeHandlers).toHaveLength(0)
expect(() => {
disposeNotification()
disposeMethod()
disposeLifecycle()
}).not.toThrow()
})
})
describe('transport close', () => {
it('disposes multiplexer when transport closes', async () => {
const promise = mux.request('pty.spawn')
transport.closeCallbacks[0]()
await expect(promise).rejects.toThrow('SSH connection lost, reconnecting...')
expect(mux.isDisposed()).toBe(true)
})
})
})