Skip to content

[Bug]: Desktop SSH environments can't reach hosts that require a one-time code (Duo); the tunnel forces ControlPath=none #30605

Closed

Description

@jfrake

Before submitting

  • I searched existing issues and did not find a duplicate.
  • I included enough detail to reproduce or investigate the problem.

Area

apps/desktop

Steps to reproduce

  1. Use an SSH host whose login asks for a password and then a Duo code (keyboard-interactive), for example a university HPC login node.
  2. In ~/.ssh/config, give the host ControlMaster auto, a ControlPath, and ControlPersist. Run ssh <alias> in a terminal and complete the Duo prompt, so a signed-in master is running.
  3. In the desktop app, open Settings → Environments → Add environment → SSH and enter the alias.

Expected behavior

The environment connects by reusing the signed-in ControlMaster, the same way a terminal ssh <alias> does.

Actual behavior

Could not prepare the SSH environment: Error invoking remote method 'desktop:ensure-ssh-environment': SshCommandError: OTP authentication failed OTP authentication failed OTP authentication failed [email protected]: Permission denied (publickey,keyboard-interactive).

The remote server launches fine, because runSshCommand reuses the user's ControlMaster. The port-forward tunnel in startSshTunnel (packages/ssh/src/tunnel.ts) passes ControlPath=none and logs in again. A fresh login cannot pass the Duo prompt: the askpass helper replays one cached secret to every prompt, so the password and the code can never both be right.

Impact

Major degradation or frequent failure

Desktop SSH environments cannot reach any host that requires a second sign-in factor. That covers most university HPC clusters, which is where many researchers run agents.

Version or commit

Desktop 0.1.7-nightly.20261103.4138. Fix below is against main at eb1db29e.

Environment

macOS (Apple Silicon), OpenSSH_10.3p1 client. Remote: Linux login node, OpenSSH_8.0, password + Duo keyboard-interactive.

Logs or stack traces

With the fix below, the dev desktop app connected end to end (desktop trace events, trimmed):

ssh.remoteServer.launch.ready     remotePort 3773, remoteServerKind managed
ssh.tunnel.process.exited         ssh ... -o ControlPath=none ... -N -L ...   (Permission denied)
ssh.tunnel.ready                  ssh ... -F none -o ControlPath=/Users/jfrake/.ssh/cm/[email protected]:22 -o ProxyCommand=false ... -T -L 127.0.0.1:60898:127.0.0.1:3773 -- gl sh -c 'exec cat >/dev/null'
ssh.environment.ensure.succeeded  localPort 60898, remotePort 3773, issuedPairingToken true

No password prompt was shown, the forward listened only on 127.0.0.1:60898 inside the existing master, and agents ran on the remote host.

Workaround

None in the app. Running agents over a plain terminal SSH session works.

Proposed fix

I have a patch and am happy to open a PR if you want it. It only changes behavior after the direct tunnel fails authentication, so users whose SSH already works see no difference:

  • After the direct tunnel fails with an auth error, look for a live ControlMaster (ssh -G for the control path, then ssh -O check). If one exists, start the tunnel through it. Otherwise the error goes to the existing password prompt as before.
  • The mux tunnel uses -F none -o ControlPath=<path> -o ProxyCommand=false. -F none keeps the user's configured forwards out of T3's requests, and ProxyCommand=false fails closed if the master disappears. Without it, ssh would quietly dial the host directly.
  • A mux client with -N exits as soon as the master takes the forward, so the tunnel holds a sh -c 'exec cat >/dev/null' session to keep a process to monitor. The forward binds 127.0.0.1 explicitly, because the master's own GatewayPorts would otherwise decide.
  • The master keeps forwards after the client exits, so a scope finalizer runs ssh -O cancel with the same spec.
  • Known limit: if the desktop app crashes, the forward stays in the user's master until the master exits. It is loopback-only and leads to the T3 server, which still requires T3 auth.

Each OpenSSH behavior above was checked by hand against a real ControlMaster (OpenSSH 10.3 client, 8.0 server). vp run check:changed passes. The new test fails on main with Permission denied (publickey,keyboard-interactive), and a second case checks that behavior is unchanged when no master is running. The docs get a short "Hosts that ask for a one-time code" subsection under Desktop-managed SSH.

Patch (docs, packages/ssh/src/command.ts, tunnel.ts, tunnel.test.ts)
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index 259f58c0..003255b3 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -236,6 +236,23 @@ again on its next connect.
 For Antigravity's Google callback on a remote host, see
 [remote sign-in](./providers-antigravity.md#sign-in-from-a-remote-device).
 
+### Hosts that ask for a one-time code
+
+T3 Code cannot answer a second sign-in prompt, such as a Duo code. On macOS and
+Linux, sign in once in a terminal and let SSH share that connection. Add these
+lines to the host's entry in `~/.ssh/config`, run `ssh <alias>`, then add or
+reconnect the environment:
+
+```sshconfig
+Host <alias>
+  ControlMaster auto
+  ControlPath ~/.ssh/cm-%C
+  ControlPersist 8h
+```
+
+When the shared connection has closed, connecting fails with a permission
+error. Sign in again in a terminal and retry.
+
 ## Browser on a remote environment
 
 Browser tabs belong to the environment, so you and your agents see the same
diff --git a/packages/ssh/src/command.ts b/packages/ssh/src/command.ts
index eafda87d..230e226d 100644
--- a/packages/ssh/src/command.ts
+++ b/packages/ssh/src/command.ts
@@ -117,6 +117,12 @@ export function baseSshArgs(
   ];
 }
 
+// `-F none` keeps the user's configured forwards out of T3's requests, and ProxyCommand=false
+// fails closed instead of dialing the host directly once the master is gone.
+export function controlMasterArgs(controlPath: string) {
+  return ["-F", "none", "-o", `ControlPath=${controlPath}`, "-o", "ProxyCommand=false"];
+}
+
 export function getLastNonEmptyOutputLine(stdout: string): string | null {
   return (
     stdout
@@ -373,3 +379,19 @@ export const resolveSshTarget = Effect.fn("ssh/command.resolveSshTarget")(functi
     ),
   );
 });
+
+export const findLiveControlPath = Effect.fn("ssh/command.findLiveControlPath")(function* (
+  target: DesktopSshEnvironmentTarget,
+) {
+  const resolved = yield* runSshCommand(target, { preHostArgs: ["-G"] }).pipe(Effect.option);
+  const controlPath = Option.getOrUndefined(resolved)
+    ?.stdout.match(/^controlpath\s+(.+)$/imu)?.[1]
+    ?.trim();
+  if (!controlPath || controlPath === "none") return null;
+  return yield* runSshCommand(target, {
+    preHostArgs: [...controlMasterArgs(controlPath), "-O", "check"],
+  }).pipe(
+    Effect.as(controlPath),
+    Effect.orElseSucceed(() => null),
+  );
+});
diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts
index b0ff65cb..476618b6 100644
--- a/packages/ssh/src/tunnel.test.ts
+++ b/packages/ssh/src/tunnel.test.ts
@@ -451,6 +451,90 @@ describe("ssh tunnel scripts", () => {
         );
       }),
   );
+
+  it.effect.each([
+    { name: "rides a live ControlMaster", masterLive: true },
+    { name: "keeps the auth failure without a live ControlMaster", masterLive: false },
+  ])("when the tunnel cannot re-authenticate, $name", ({ masterLive }) =>
+    Effect.gen(function* () {
+      const events: Array<string> = [];
+      let tunnelForward: string | undefined;
+      let cancelForward: string | undefined;
+      let forwardOpen = false;
+      const spawner = ChildProcessSpawner.make((command) =>
+        Effect.sync(() => {
+          const args = commandArgs(command);
+          const forward = args[args.indexOf("-L") + 1];
+          if (args.includes("-G")) {
+            return makeSuccessfulProcess("hostname devbox\ncontrolpath /tmp/t3-cm\n");
+          }
+          if (args.includes("check")) {
+            return masterLive
+              ? makeSuccessfulProcess("")
+              : {
+                  ...makeSuccessfulProcess(""),
+                  exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(255)),
+                };
+          }
+          if (args.includes("cancel")) {
+            events.push("cancel");
+            cancelForward = forward;
+            return makeSuccessfulProcess("");
+          }
+          // A fresh login cannot answer the host's one-time-code prompt.
+          if (args.includes("-N")) {
+            return {
+              ...makeSuccessfulProcess(""),
+              exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(255)),
+              stderr: Stream.make(
+                new TextEncoder().encode("Permission denied (publickey,keyboard-interactive).\n"),
+              ),
+            };
+          }
+          if (args.includes("-L")) {
+            forwardOpen = true;
+            tunnelForward = forward;
+            return makeRunningProcess(() => events.push("kill"));
+          }
+          return makeSuccessfulProcess('{"remotePort":3773}\n');
+        }),
+      );
+      const layer = Layer.mergeAll(
+        NodeServices.layer,
+        NodeCrypto.layer,
+        Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
+        Layer.succeed(
+          HttpClient.HttpClient,
+          HttpClient.make((request) =>
+            forwardOpen ? testHttpClient.execute(request) : Effect.never,
+          ),
+        ),
+        Layer.succeed(NetService.NetService, testNetService),
+        SshAuth.SshPasswordPrompt.disabledLayer,
+        SshTunnel.SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
+      );
+      const target = { alias: "devbox", hostname: "devbox", username: null, port: null };
+      yield* Effect.gen(function* () {
+        const manager = yield* SshTunnel.SshEnvironmentManager;
+        const result = yield* Effect.result(manager.ensureEnvironment(target));
+        if (!masterLive) {
+          assert.isTrue(Result.isFailure(result));
+          if (Result.isFailure(result)) assert.instanceOf(result.failure, SshCommandError);
+          return;
+        }
+        assert.isTrue(Result.isSuccess(result));
+        yield* manager.disconnectEnvironment(target);
+      }).pipe(Effect.provide(layer), Effect.scoped);
+
+      if (masterLive) {
+        assert.deepEqual(events, ["kill", "cancel"]);
+        assert.equal(cancelForward, tunnelForward);
+      } else {
+        assert.deepEqual(events, []);
+        assert.isFalse(forwardOpen);
+      }
+    }),
+  );
 });
 
 // On macOS, Node can bind 127.0.0.1:<port> while another process (such as the
diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts
index 6a08b20a..9cb673f2 100644
--- a/packages/ssh/src/tunnel.ts
+++ b/packages/ssh/src/tunnel.ts
@@ -26,6 +26,8 @@ import * as SshAuth from "./auth.ts";
 import {
   baseSshArgs,
   buildSshHostSpecEffect,
+  controlMasterArgs,
+  findLiveControlPath,
   getLastNonEmptyOutputLine,
   remoteStateKey,
   resolveSshCommand,
@@ -1104,6 +1106,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
   readonly httpBaseUrl: string;
   readonly wsBaseUrl: string;
   readonly authOptions: SshAuth.SshAuthOptions;
+  readonly controlPath: string | null;
   readonly remoteServerKind: "external" | "managed" | null;
   readonly scope: Scope.Closeable;
 }): Effect.fn.Return<
@@ -1136,7 +1139,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
         }),
     ),
   );
-  const args = [
+  const directArgs = [
     ...baseSshArgs(input.resolvedTarget, {
       batchMode: input.authOptions.batchMode ?? "no",
     }),
@@ -1159,10 +1162,47 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
     "--",
     hostSpec,
   ];
+  const { controlPath } = input;
+  // The master's own GatewayPorts would otherwise decide the bind address.
+  const forwardSpec = `127.0.0.1:${input.localPort}:127.0.0.1:${input.remotePort}`;
+  const args =
+    controlPath === null
+      ? directArgs
+      : [
+          ...baseSshArgs(input.resolvedTarget, { batchMode: "yes" }),
+          ...controlMasterArgs(controlPath),
+          "-o",
+          "ExitOnForwardFailure=yes",
+          "-o",
+          "ControlMaster=no",
+          // A mux client with -N exits once the master owns the forward; a session keeps it monitorable.
+          "-T",
+          "-L",
+          forwardSpec,
+          "--",
+          hostSpec,
+          "sh -c 'exec cat >/dev/null'",
+        ];
   const sshCommand = yield* resolveSshCommand;
   const tunnelCommand = [sshCommand, ...args];
   const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
   const { scope } = input;
+  if (controlPath !== null) {
+    const fileSystemService = yield* FileSystem.FileSystem;
+    const pathService = yield* Path.Path;
+    // The master keeps forwards after the mux client exits.
+    yield* Scope.addFinalizer(
+      scope,
+      runSshCommand(input.resolvedTarget, {
+        preHostArgs: [...controlMasterArgs(controlPath), "-O", "cancel", "-L", forwardSpec],
+      }).pipe(
+        Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
+        Effect.provideService(FileSystem.FileSystem, fileSystemService),
+        Effect.provideService(Path.Path, pathService),
+        Effect.ignore,
+      ),
+    );
+  }
   yield* Effect.logDebug("ssh.tunnel.spawn.start", {
     ...sshTargetLogFields(input.resolvedTarget),
     command: tunnelCommand,
@@ -1176,10 +1216,13 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
       ChildProcess.make(sshCommand, args, {
         env: childEnvironment,
         extendEnv: true,
-        stdin: {
-          stream: Stream.empty,
-          endOnDone: true,
-        },
+        stdin:
+          controlPath === null
+            ? {
+                stream: Stream.empty,
+                endOnDone: true,
+              }
+            : "pipe",
       }),
     )
     .pipe(
@@ -1536,18 +1579,32 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
     const tunnelEntry = yield* runWithSshAuth({
       key: input.key,
       target: input.resolvedTarget,
-      operation: (authOptions) =>
-        startSshTunnel({
-          key: input.key,
-          resolvedTarget: input.resolvedTarget,
-          remotePort,
-          localPort,
-          httpBaseUrl,
-          wsBaseUrl,
-          authOptions,
-          remoteServerKind: remoteLaunch.remoteServerKind,
-          scope: entryScope,
-        }),
+      operation: (authOptions) => {
+        const start = (controlPath: string | null) =>
+          startSshTunnel({
+            key: input.key,
+            resolvedTarget: input.resolvedTarget,
+            remotePort,
+            localPort,
+            httpBaseUrl,
+            wsBaseUrl,
+            authOptions,
+            controlPath,
+            remoteServerKind: remoteLaunch.remoteServerKind,
+            scope: entryScope,
+          });
+        // Hosts that ask for one-time codes (such as Duo) cannot be re-authenticated here, so
+        // ride the user's signed-in ControlMaster before falling back to a password prompt.
+        return start(null).pipe(
+          Effect.catchIf(SshAuth.isSshAuthFailure, (error) =>
+            findLiveControlPath(input.resolvedTarget).pipe(
+              Effect.flatMap((controlPath) =>
+                controlPath === null ? Effect.fail(error) : start(controlPath),
+              ),
+            ),
+          ),
+        );
+      },
     }).pipe(
       Effect.onExit((exit) =>
         Exit.isSuccess(exit) ? Effect.void : Scope.close(entryScope, Exit.void).pipe(Effect.ignore),

Written with Claude Opus 5.5 in T3 Code. Earlier versions were reviewed by Codex (gpt-6-astra) and a separate Claude agent, and their findings are addressed here.

Activity

  1. shivamhwp commented on Nov 4, 2026

    @shivamhwp
    Collaborator

    [GPT-6.1 Sol][Codex] on behalf of shivam.

    Julius has taken this fix over in #30616, which explicitly closes this issue. I confirmed the current issue-watch baseline still forces ControlPath=none in packages/ssh/src/tunnel.ts. No changes or runtime tests were started in this thread; stopping the duplicate work under our takeover rule.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions