Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
fix(switchdash): unbreak remote hosts with IdentitiesOnly or restricted agent forwarding (#98)
Louis Amaudruzd1d2343fc389
diff --git a/dash/apps/switchdash-desktop/src/main/core/ssh/connect/resolve-ssh-connect-config.test.ts b/dash/apps/switchdash-desktop/src/main/core/ssh/connect/resolve-ssh-connect-config.test.tsindex 93b2afb1f..ad83e80e2 100644--- a/dash/apps/switchdash-desktop/src/main/core/ssh/connect/resolve-ssh-connect-config.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/ssh/connect/resolve-ssh-connect-config.test.ts@@ -1,6 +1,6 @@import { PassThrough } from 'node:stream';-import type { BaseAgent, ParsedKey, SignCallback } from 'ssh2';-import { utils } from 'ssh2';+import type { IdentityCallback, ParsedKey, SignCallback } from 'ssh2';+import { BaseAgent, utils } from 'ssh2';import { describe, expect, it } from 'vitest';import type { SshConfig } from '@shared/core/ssh/ssh';import {@@ -298,6 +298,44 @@ describe('resolveSshConnectConfig', () => {).resolves.toBeInstanceOf(PassThrough);});+ it('builds an IdentitiesOnly agent ssh2 accepts when ForwardAgent is enabled', async () => {+ const allowedKey = parseFixturePublicKey();+ const result = await resolveSshConnectConfig(+ {+ kind: 'transient',+ config: baseConfig({ sshConfigAlias: 'corp-dev', authType: 'agent' }),+ },+ deps({+ readFile: async () =>+ 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILI4wa2zRZoB26D015dsafYmu3jDCI7rh26bFXZrUiAp test-key',+ env: { SSH_AUTH_SOCK: '/tmp/default-agent.sock' },+ createAgent: () =>+ ({+ getIdentities: (callback: IdentityCallback) => callback(undefined, [allowedKey]),+ sign: (_pubKey: unknown, _data: unknown, _options: unknown, callback?: SignCallback) =>+ callback?.(undefined, Buffer.from('signature')),+ }) as unknown as BaseAgent,+ resolveSshConfig: async () => ({+ hostname: 'dev.internal',+ user: 'alice',+ port: 22,+ identityFile: ['~/.ssh/corp_ed25519'],+ identityAgent: 'SSH_AUTH_SOCK',+ identityAgentDisabled: false,+ identitiesOnly: true,+ proxyCommand: undefined,+ proxyJump: undefined,+ forwardAgent: true,+ }),+ })+ );++ expect(result.config.agentForward).toBe(true);+ // ssh2 gates custom agents on `instanceof BaseAgent` and drops anything+ // that only duck-types the interface, which breaks agent forwarding.+ expect(result.config.agent).toBeInstanceOf(BaseAgent);+ });+it('does not expose agent getStream when the wrapped agent does not support it', async () => {const result = await resolveSshConnectConfig({diff --git a/dash/apps/switchdash-desktop/src/main/core/ssh/connect/ssh-connect-auth.ts b/dash/apps/switchdash-desktop/src/main/core/ssh/connect/ssh-connect-auth.tsindex 213f3001f..8ca4a6c1e 100644--- a/dash/apps/switchdash-desktop/src/main/core/ssh/connect/ssh-connect-auth.ts+++ b/dash/apps/switchdash-desktop/src/main/core/ssh/connect/ssh-connect-auth.ts@@ -3,7 +3,7 @@// are always transient, so password/passphrase come inline from the connect// config rather than a credential-service lookup keyed by a persisted row id.import ssh2, {- type BaseAgent,+ BaseAgent,type ConnectConfig,type IdentityCallback,type ParsedKey,@@ -44,7 +44,13 @@ function comparablePublicKey(key: AgentPublicKey): ParsedKey | Buffer | string {return key;}-class IdentityFilteredAgent implements BaseAgent {+/**+ * Extends ssh2's `BaseAgent` class rather than only implementing its shape:+ * ssh2 gates a custom agent on `instanceof BaseAgent` and silently discards+ * one that fails the check, which then surfaces as "You must set a valid agent+ * path to allow agent forwarding" whenever ForwardAgent is enabled.+ */+class IdentityFilteredAgent extends BaseAgent {readonly kind = 'identity-filtered-agent';declare getStream?: BaseAgent['getStream'];@@ -53,6 +59,7 @@ class IdentityFilteredAgent implements BaseAgent {private readonly agent: BaseAgent,private readonly allowedKeys: ParsedKey[]) {+ super();if (agent.getStream) {this.getStream = agent.getStream.bind(agent);}diff --git a/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-agent-forward-refusal.ts b/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-agent-forward-refusal.tsnew file mode 100644index 000000000..0e5634433--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-agent-forward-refusal.ts@@ -0,0 +1,39 @@+import type { Client } from 'ssh2';++/**+ * A server that declines `[email protected]` — typically+ * `AllowAgentForwarding no` in a hardening drop-in.+ *+ * ssh2 asks for a reply to that request and treats "no" as fatal: it closes the+ * channel and errors the exec/shell, so a host refusing an optional extra makes+ * every command on it fail. OpenSSH sends the same request with no reply+ * expected and never notices the refusal, which is why `ssh <host>` works on+ * exactly the hosts switchdash could not reach.+ */+export function isAgentForwardRefusal(error: unknown): boolean {+ const message =+ error instanceof Error+ ? error.message+ : typeof (error as { message?: unknown })?.message === 'string'+ ? (error as { message: string }).message+ : String(error);+ return message.toLowerCase().includes('unable to request agent forwarding');+}++type ClientWithConfig = { config?: { allowAgentFwd?: boolean } };++/**+ * Stop ssh2 requesting agent forwarding on this connection's future channels.+ *+ * `allowAgentFwd` is connection-scoped and decided at connect time, so a+ * refusal cannot be worked around per channel — every subsequent exec would+ * request it again and fail the same way. Clearing it degrades the connection+ * to what OpenSSH gives you against such a host: everything works except+ * forwarding. Returns false when there was no flag to clear.+ */+export function disableAgentForwarding(client: Client): boolean {+ const config = (client as unknown as ClientWithConfig).config;+ if (!config?.allowAgentFwd) return false;+ config.allowAgentFwd = false;+ return true;+}diff --git a/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-client-proxy.test.ts b/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-client-proxy.test.tsindex 694eefb04..efcc4fb88 100644--- a/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-client-proxy.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-client-proxy.test.ts@@ -413,3 +413,90 @@ describe('SshClientProxy channel health reporting', () => {expect(reporter.reportChannelError).toHaveBeenCalledWith('ssh-1', sftpError);});});++describe('SshClientProxy agent-forward refusal', () => {+ function refusingClient(refusals: number) {+ const commands: string[] = [];+ let seen = 0;+ const client = {+ config: { allowAgentFwd: true },+ exec: (command: string, optionsOrCb: unknown, maybeCb?: unknown) => {+ const callback = (typeof optionsOrCb === 'function' ? optionsOrCb : maybeCb) as (+ err: Error | undefined,+ channel?: unknown+ ) => void;+ commands.push(command);+ if (seen++ < refusals && client.config.allowAgentFwd) {+ callback(new Error('Unable to request agent forwarding'));+ return;+ }+ callback(undefined, {+ once: (event: string, listener: () => void) => {+ // Free the proxy's exec slot the way a real channel does.+ if (event === 'close') setTimeout(listener, 0);+ },+ });+ },+ };+ return { client, commands };+ }++ it('retries exec without forwarding when the host refuses it', async () => {+ const { client, commands } = refusingClient(1);+ const proxy = new SshClientProxy('ssh-1');+ proxy.update(client as never);++ const result = await new Promise<{ err: Error | undefined; channel: unknown }>((resolve) => {+ proxy.exec('echo hi', (err, channel) => resolve({ err, channel }));+ });++ expect(result.err).toBeUndefined();+ expect(result.channel).toBeDefined();+ expect(commands).toEqual(['echo hi', 'echo hi']);+ expect(client.config.allowAgentFwd).toBe(false);+ });++ it('retries a pty channel without forwarding when the host refuses it', async () => {+ const { client, commands } = refusingClient(1);+ const proxy = new SshClientProxy('ssh-1');+ proxy.update(client as never);++ const result = await new Promise<Error | undefined>((resolve) => {+ proxy.execPty('tmux a', {}, (err) => resolve(err));+ });++ expect(result).toBeUndefined();+ expect(commands).toHaveLength(2);+ expect(client.config.allowAgentFwd).toBe(false);+ });++ it('surfaces the error when a retry is not possible', async () => {+ const { client, commands } = refusingClient(1);+ client.config.allowAgentFwd = false;+ const proxy = new SshClientProxy('ssh-1');+ proxy.update(client as never);++ const result = await new Promise<Error | undefined>((resolve) => {+ proxy.exec('echo hi', (err) => resolve(err));+ });++ // Nothing to disable, so the refusal is reported rather than looped on.+ expect(result).toBeUndefined();+ expect(commands).toEqual(['echo hi']);+ });++ it('does not leak exec slots across a forwarding retry', async () => {+ const { client, commands } = refusingClient(1);+ const proxy = new SshClientProxy('ssh-1');+ proxy.update(client as never);++ for (let i = 0; i < 8; i++) {+ await new Promise<void>((resolve) => {+ proxy.exec(`cmd-${i}`, () => resolve());+ });+ }++ // 8 commands, one of which was retried after the refusal.+ expect(commands).toHaveLength(9);+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-client-proxy.ts b/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-client-proxy.tsindex f7192f220..466bc1e42 100644--- a/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-client-proxy.ts+++ b/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-client-proxy.ts@@ -1,5 +1,7 @@import type { Client, ClientCallback, ClientChannel, ClientSFTPCallback, ExecOptions } from 'ssh2';+import { log } from '@main/lib/logger';import { captureRemoteShellProfile, type RemoteShellProfile } from './remote-shell-profile';+import { disableAgentForwarding, isAgentForwardRefusal } from './ssh-agent-forward-refusal';import { SshChannelTimeoutError } from './ssh-channel-open-failure';type RemoteShellProfileState =@@ -109,6 +111,27 @@ export class SshClientProxy {return promise;}+ /**+ * Turn a server's refusal of agent forwarding into a degraded connection+ * rather than a dead one. Returns true when forwarding was just switched off+ * and the caller should retry its channel open once.+ *+ * The capability is optional — switchdash needs none of it, and it is only+ * requested because the user's ssh config asks for it — so a host that+ * declines it (`AllowAgentForwarding no`) must not lose every remote command.+ * The loss is real for anything on the host relying on the forwarded agent+ * (e.g. `git push` over SSH with the user's local keys), hence the warning.+ */+ private recoverFromAgentForwardRefusal(error: unknown): boolean {+ if (!this._client || !isAgentForwardRefusal(error)) return false;+ if (!disableAgentForwarding(this._client)) return false;+ log.warn('SshClientProxy: host refused agent forwarding, continuing without it', {+ event: 'ssh.agent_forward_refused',+ connectionId: this.connectionId,+ });+ return true;+ }+/** Run `fn` once an exec slot is free; queues it when at capacity. */private acquireExecSlot(fn: () => void): void {if (this.activeExec < MAX_CONCURRENT_EXEC) {@@ -183,35 +206,57 @@ export class SshClientProxy {this.releaseExecSlot();};- const wrappedCallback = this.withChannelOpenTimeout('exec', (err, channel) => {- if (!err && channel && typeof channel.once === 'function') {- // Free the slot when the command's channel finishes.- channel.once('close', release);- channel.once('error', release);- } else {+ const attempt = (retrying: boolean): void => {+ const wrappedCallback = this.withChannelOpenTimeout('exec', (err, channel) => {+ if (err && !retrying && this.recoverFromAgentForwardRefusal(err)) {+ attempt(true);+ return;+ }+ if (!err && channel && typeof channel.once === 'function') {+ // Free the slot when the command's channel finishes.+ channel.once('close', release);+ channel.once('error', release);+ } else {+ release();+ }+ userCallback?.(err, channel);+ });++ try {+ if (options) {+ this.client.exec(command, options, wrappedCallback);+ } else {+ this.client.exec(command, wrappedCallback);+ }+ } catch (err) {+ // e.g. connection not available — surface via callback, don't leak the slot.release();+ userCallback?.(err as Error, undefined as never);}- userCallback?.(err, channel);- });+ };- try {- if (options) {- this.client.exec(command, options, wrappedCallback);- } else {- this.client.exec(command, wrappedCallback);- }- } catch (err) {- // e.g. connection not available — surface via callback, don't leak the slot.- release();- userCallback?.(err as Error, undefined as never);- }+ attempt(false);});}execPty(command: string, options: ExecOptions, callback: ClientCallback): void {// The timeout guards only the channel OPEN; the pty channel itself is// long-lived (it is the interactive terminal).- this.client.exec(command, options, this.withChannelOpenTimeout('pty', callback));+ const attempt = (retrying: boolean): void => {+ this.client.exec(+ command,+ options,+ this.withChannelOpenTimeout('pty', (err, channel) => {+ if (err && !retrying && this.recoverFromAgentForwardRefusal(err)) {+ attempt(true);+ return;+ }+ callback(err, channel);+ })+ );+ };++ attempt(false);}/**