diff --git a/apps/desktop/src/ipc/methods/sshEnvironment.test.ts b/apps/desktop/src/ipc/methods/sshEnvironment.test.ts index e776b49bb3..fd7b0ac29f 100644 --- a/apps/desktop/src/ipc/methods/sshEnvironment.test.ts +++ b/apps/desktop/src/ipc/methods/sshEnvironment.test.ts @@ -98,8 +98,6 @@ describe("SSH environment IPC", () => { const structured = new SshCommandSpawnError({ command: "ssh", argumentCount: 0, - exitCode: null, - stderrBytes: 0, target: "devbox", cause, }); diff --git a/packages/ssh/src/auth.test.ts b/packages/ssh/src/auth.test.ts index e0eae6de15..f5dbfc5ac3 100644 --- a/packages/ssh/src/auth.test.ts +++ b/packages/ssh/src/auth.test.ts @@ -36,18 +36,12 @@ describe("ssh auth", () => { const commandFailure = new SshErrors.SshCommandSpawnError({ command: "ssh", argumentCount: 1, - exitCode: null, - stderrBytes: 0, target: "devbox", cause: authFailure, }); assert.equal(isSshAuthFailure(commandFailure), true); const helperFailure = new SshErrors.SshAuthenticationHelperError({ - command: "ssh", - argumentCount: 1, - exitCode: null, - stderrBytes: 0, target: "devbox", cause: authFailure, }); diff --git a/packages/ssh/src/auth.ts b/packages/ssh/src/auth.ts index b289ffc005..c9d9c147fa 100644 --- a/packages/ssh/src/auth.ts +++ b/packages/ssh/src/auth.ts @@ -217,6 +217,19 @@ function isSshAuthFailureMessage(message: string): boolean { ); } +export function classifySshProcessExit(input: { + readonly stdout: string; + readonly stderr: string; +}): SshErrors.SshProcessExitReason { + return isSshAuthFailureMessage(`${input.stderr}\n${input.stdout}`) + ? "authentication-failed" + : "process-exited"; +} + +const isSshAuthFailureExit = Schema.is( + Schema.Union([SshErrors.SshCommandExitError, SshErrors.SshTunnelExitError]), +); + const isSshAuthFailureCauseWrapper = Schema.is( Schema.Union([ SshErrors.SshCommandSpawnError, @@ -232,6 +245,9 @@ export function isSshAuthFailure(error: unknown): boolean { while (!visited.has(current)) { visited.add(current); + if (isSshAuthFailureExit(current)) { + return current.reason === "authentication-failed"; + } const message = current instanceof Error ? current.message : String(current); if (isSshAuthFailureMessage(message)) { return true; diff --git a/packages/ssh/src/command.test.ts b/packages/ssh/src/command.test.ts index e25b201970..fdc2fe6020 100644 --- a/packages/ssh/src/command.test.ts +++ b/packages/ssh/src/command.test.ts @@ -184,8 +184,6 @@ describe("ssh command", () => { const spawnError = new SshCommandSpawnError({ command: "ssh", argumentCount: 0, - exitCode: null, - stderrBytes: 0, target: "devbox", cause: spawnCause, }); @@ -254,7 +252,7 @@ describe("ssh command", () => { assert.isTrue(Result.isFailure(result)); if (Result.isFailure(result)) { - assert.include(result.failure.message, "SSH command timed out after 1ms."); + assert.equal(result.failure.message, "SSH command timed out after 1ms for devbox."); } }).pipe(Effect.provide(processLayer)); }); diff --git a/packages/ssh/src/command.ts b/packages/ssh/src/command.ts index 27b3b5164d..2e5559ad28 100644 --- a/packages/ssh/src/command.ts +++ b/packages/ssh/src/command.ts @@ -178,10 +178,6 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func Effect.mapError( (cause) => new SshAuthenticationHelperError({ - command: "ssh", - argumentCount: 0, - exitCode: null, - stderrBytes: 0, target: hostSpec, cause, }), @@ -222,8 +218,6 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func new SshCommandSpawnError({ command: sshCommand, argumentCount: args.length, - exitCode: null, - stderrBytes: 0, target: hostSpec, cause, }), @@ -243,8 +237,6 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func new SshCommandExecutionError({ command: sshCommand, argumentCount: args.length, - exitCode: null, - stderrBytes: 0, target: hostSpec, cause, }), @@ -267,6 +259,7 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func stdoutBytes: utf8ByteLength(stdout), stderrBytes: utf8ByteLength(stderr), target: hostSpec, + reason: SshAuth.classifySshProcessExit({ stdout, stderr }), }); } @@ -312,8 +305,6 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* ( (input.preHostArgs?.length ?? 0) + 1 + (input.remoteCommandArgs?.length ?? 0), - exitCode: null, - stderrBytes: 0, target: target.alias || target.hostname, timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS, }); diff --git a/packages/ssh/src/errors.ts b/packages/ssh/src/errors.ts index 1ddc635dd9..3998d97040 100644 --- a/packages/ssh/src/errors.ts +++ b/packages/ssh/src/errors.ts @@ -41,117 +41,125 @@ export const SshInvalidTargetError = Schema.Union([ ]); export type SshInvalidTargetError = typeof SshInvalidTargetError.Type; -const SshCommandErrorFields = { +const SshCommandContextFields = { command: Schema.String, argumentCount: Schema.Number, - exitCode: Schema.NullOr(Schema.Number), - stderrBytes: Schema.Number, - stdoutBytes: Schema.optional(Schema.Number), - target: Schema.optional(Schema.String), - timeoutMs: Schema.optional(Schema.Number), + target: Schema.String, }; -const SshCommandFailureFields = { - ...SshCommandErrorFields, +const SshCommandCauseFields = { + ...SshCommandContextFields, cause: Schema.Defect(), }; +export const SshProcessExitReason = Schema.Literals(["authentication-failed", "process-exited"]); +export type SshProcessExitReason = typeof SshProcessExitReason.Type; + export class SshAuthenticationHelperError extends Schema.TaggedErrorClass()( "SshAuthenticationHelperError", { - ...SshCommandFailureFields, + target: Schema.String, + cause: Schema.Defect(), }, ) { override get message(): string { - return "Failed to prepare SSH authentication helpers."; + return `Failed to prepare SSH authentication helpers for ${this.target}.`; } } export class SshCommandSpawnError extends Schema.TaggedErrorClass()( "SshCommandSpawnError", { - ...SshCommandFailureFields, + ...SshCommandCauseFields, }, ) { override get message(): string { - return `Failed to spawn SSH command${targetSuffix(this.target)}.`; + return `Failed to spawn SSH command for ${this.target}.`; } } export class SshCommandExecutionError extends Schema.TaggedErrorClass()( "SshCommandExecutionError", { - ...SshCommandFailureFields, + ...SshCommandCauseFields, }, ) { override get message(): string { - return `Failed to run SSH command${targetSuffix(this.target)}.`; + return `Failed to run SSH command for ${this.target}.`; } } export class SshCommandExitError extends Schema.TaggedErrorClass()( "SshCommandExitError", { - ...SshCommandErrorFields, + ...SshCommandContextFields, + exitCode: Schema.Number, + stdoutBytes: Schema.Number, + stderrBytes: Schema.Number, + reason: SshProcessExitReason, }, ) { override get message(): string { - return `SSH command failed${targetSuffix(this.target)}${exitCodeSuffix(this.exitCode)}.`; + return `SSH command failed for ${this.target} (exit ${this.exitCode}).`; } } export class SshCommandTimeoutError extends Schema.TaggedErrorClass()( "SshCommandTimeoutError", { - ...SshCommandErrorFields, + ...SshCommandContextFields, + timeoutMs: Schema.Number, }, ) { override get message(): string { - return `SSH command timed out after ${this.timeoutMs ?? 0}ms.`; + return `SSH command timed out after ${this.timeoutMs}ms for ${this.target}.`; } } export class SshCommandCancelledError extends Schema.TaggedErrorClass()( "SshCommandCancelledError", { - ...SshCommandErrorFields, + target: Schema.String, }, ) { override get message(): string { - return `SSH environment connection was cancelled${targetSuffix(this.target)}.`; + return `SSH environment connection was cancelled for ${this.target}.`; } } export class SshTunnelSpawnError extends Schema.TaggedErrorClass()( "SshTunnelSpawnError", { - ...SshCommandFailureFields, + ...SshCommandCauseFields, }, ) { override get message(): string { - return `Failed to spawn SSH tunnel${targetSuffix(this.target)}.`; + return `Failed to spawn SSH tunnel for ${this.target}.`; } } export class SshTunnelMonitorError extends Schema.TaggedErrorClass()( "SshTunnelMonitorError", { - ...SshCommandFailureFields, + ...SshCommandCauseFields, }, ) { override get message(): string { - return `Failed to monitor SSH tunnel${targetSuffix(this.target)}.`; + return `Failed to monitor SSH tunnel for ${this.target}.`; } } export class SshTunnelExitError extends Schema.TaggedErrorClass()( "SshTunnelExitError", { - ...SshCommandErrorFields, + ...SshCommandContextFields, + exitCode: Schema.Number, + stderrBytes: Schema.Number, + reason: SshProcessExitReason, }, ) { override get message(): string { - return `SSH tunnel exited unexpectedly${targetSuffix(this.target)}${exitCodeSuffix(this.exitCode)}.`; + return `SSH tunnel exited unexpectedly for ${this.target} (exit ${this.exitCode}).`; } } @@ -171,35 +179,38 @@ export type SshCommandError = typeof SshCommandError.Type; export class SshLaunchPortMissingError extends Schema.TaggedErrorClass()( "SshLaunchPortMissingError", { + target: Schema.String, stdoutBytes: Schema.Number, }, ) { override get message(): string { - return "SSH launch did not return a remote port."; + return `SSH launch for ${this.target} did not return a remote port.`; } } export class SshLaunchOutputParseError extends Schema.TaggedErrorClass()( "SshLaunchOutputParseError", { + target: Schema.String, stdoutBytes: Schema.Number, cause: Schema.Defect(), }, ) { override get message(): string { - return "SSH launch returned unparseable output."; + return `SSH launch for ${this.target} returned unparseable output.`; } } export class SshLaunchInvalidPortError extends Schema.TaggedErrorClass()( "SshLaunchInvalidPortError", { + target: Schema.String, stdoutBytes: Schema.Number, - remotePort: Schema.optional(Schema.Number), + remotePort: Schema.Number, }, ) { override get message(): string { - return `SSH launch returned an invalid remote port: ${String(this.remotePort)}.`; + return `SSH launch for ${this.target} returned an invalid remote port: ${this.remotePort}.`; } } @@ -213,34 +224,37 @@ export type SshLaunchError = typeof SshLaunchError.Type; export class SshPairingCredentialMissingError extends Schema.TaggedErrorClass()( "SshPairingCredentialMissingError", { + target: Schema.String, stdoutBytes: Schema.Number, }, ) { override get message(): string { - return "SSH pairing did not return a credential."; + return `SSH pairing for ${this.target} did not return a credential.`; } } export class SshPairingOutputParseError extends Schema.TaggedErrorClass()( "SshPairingOutputParseError", { + target: Schema.String, stdoutBytes: Schema.Number, cause: Schema.Defect(), }, ) { override get message(): string { - return "SSH pairing returned unparseable output."; + return `SSH pairing for ${this.target} returned unparseable output.`; } } export class SshPairingInvalidCredentialError extends Schema.TaggedErrorClass()( "SshPairingInvalidCredentialError", { + target: Schema.String, stdoutBytes: Schema.Number, }, ) { override get message(): string { - return "SSH pairing command returned an invalid credential."; + return `SSH pairing for ${this.target} returned an invalid credential.`; } } @@ -459,11 +473,3 @@ export const SshPasswordPromptError = Schema.Union([ SshPasswordPromptRequestError, ]); export type SshPasswordPromptError = typeof SshPasswordPromptError.Type; - -function targetSuffix(target: string | undefined): string { - return target ? ` for ${target}` : ""; -} - -function exitCodeSuffix(exitCode: number | null): string { - return exitCode === null ? "" : ` (exit ${exitCode})`; -} diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index d64c9eddd1..1264bd24b9 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -48,6 +48,26 @@ const makeSuccessfulProcess = (stdout: string) => { }); }; +const makeFailedProcess = (input: { readonly stdout?: string; readonly stderr?: string }) => { + const stdout = input.stdout ?? ""; + const stderr = input.stderr ?? ""; + const stdoutStream = stdout === "" ? Stream.empty : Stream.make(new TextEncoder().encode(stdout)); + const stderrStream = stderr === "" ? Stream.empty : Stream.make(new TextEncoder().encode(stderr)); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(123), + stdout: stdoutStream, + stderr: stderrStream, + all: Stream.empty, + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }); +}; + const makeRunningProcess = (onKill: () => void) => { let finish: ((exitCode: ChildProcessSpawner.ExitCode) => void) | null = null; return ChildProcessSpawner.makeHandle({ @@ -576,6 +596,7 @@ describe("ssh tunnel scripts", () => { assert.isTrue(Result.isFailure(result)); if (Result.isFailure(result)) { assert.instanceOf(result.failure, SshPairingOutputParseError); + assert.equal(result.failure.target, "devbox"); assert.equal(result.failure.stdoutBytes, new TextEncoder().encode(output).length); assert.isFalse("stdout" in result.failure); assert.notInclude(result.failure.message, "pairing-secret"); @@ -640,6 +661,59 @@ describe("ssh tunnel scripts", () => { }).pipe(Effect.provide(layer), Effect.scoped); }); + it.effect("retries authentication after a permission-denied SSH exit", () => { + const target = { + alias: "devbox", + hostname: "devbox.example.com", + username: "julius", + port: 2222, + } as const; + const promptAttempts: number[] = []; + let launchAttempts = 0; + const spawner = ChildProcessSpawner.make((command) => { + const args = commandArgs(command); + if (args.includes("sh") && args.includes("--")) { + launchAttempts += 1; + if (launchAttempts === 1) { + return Effect.succeed( + makeFailedProcess({ + stderr: "julius@devbox: Permission denied (publickey,password).\n", + }), + ); + } + return Effect.succeed(makeSuccessfulProcess('{"remotePort":3773}\n')); + } + if (args.includes("-N")) { + return Effect.succeed(makeRunningProcess(() => {})); + } + return Effect.succeed(makeSuccessfulProcess("\n")); + }); + const layer = Layer.mergeAll( + NodeServices.layer, + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + Layer.succeed(HttpClient.HttpClient, testHttpClient), + Layer.succeed(NetService.NetService, testNetService), + SshAuth.layer({ + isAvailable: true, + request: (request) => + Effect.sync(() => { + promptAttempts.push(request.attempt); + return "secret"; + }), + }), + SshTunnel.layer(), + ); + + return Effect.gen(function* () { + const manager = yield* SshTunnel.SshEnvironmentManager; + const environment = yield* manager.ensureEnvironment(target); + + assert.equal(environment.remotePort, 3773); + assert.equal(launchAttempts, 2); + assert.deepEqual(promptAttempts, [1]); + }).pipe(Effect.provide(layer), Effect.scoped); + }); + it.effect("closes the tunnel scope and starts fresh after disconnect", () => { const spawnedCommands: Array> = []; let tunnelKillCount = 0; diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index 119b4f417a..7830cf095a 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -772,6 +772,7 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo SshCommandError | SshInvalidTargetError | SshLaunchError, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path > { + const destination = target.alias.trim() || target.hostname.trim(); yield* Effect.logInfo("ssh.remoteServer.launch.start", { ...sshTargetLogFields(target), ...sshRunnerLogFields(runner), @@ -786,6 +787,7 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo }); if (!getLastNonEmptyOutputLine(result.stdout)) { return yield* new SshLaunchPortMissingError({ + target: destination, stdoutBytes: utf8ByteLength(result.stdout), }); } @@ -793,6 +795,7 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo Effect.mapError( (cause) => new SshLaunchOutputParseError({ + target: destination, stdoutBytes: utf8ByteLength(result.stdout), cause, }), @@ -800,6 +803,7 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo ); if (!Number.isInteger(parsed.remotePort)) { return yield* new SshLaunchInvalidPortError({ + target: destination, stdoutBytes: utf8ByteLength(result.stdout), remotePort: parsed.remotePort, }); @@ -828,6 +832,7 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT SshCommandError | SshInvalidTargetError | SshPairingError, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path > { + const destination = target.alias.trim() || target.hostname.trim(); yield* Effect.logDebug("ssh.remoteServer.pairingToken.start", { ...sshTargetLogFields(target), stateKey: remoteStateKey(target), @@ -841,6 +846,7 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT }); if (!getLastNonEmptyOutputLine(result.stdout)) { return yield* new SshPairingCredentialMissingError({ + target: destination, stdoutBytes: utf8ByteLength(result.stdout), }); } @@ -848,6 +854,7 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT Effect.mapError( (cause) => new SshPairingOutputParseError({ + target: destination, stdoutBytes: utf8ByteLength(result.stdout), cause, }), @@ -855,6 +862,7 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT ); if (parsed.credential.trim().length === 0) { return yield* new SshPairingInvalidCredentialError({ + target: destination, stdoutBytes: utf8ByteLength(result.stdout), }); } @@ -1087,10 +1095,6 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: Effect.mapError( (cause) => new SshAuthenticationHelperError({ - command: "ssh", - argumentCount: 0, - exitCode: null, - stderrBytes: 0, target: hostSpec, cause, }), @@ -1142,8 +1146,6 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: new SshTunnelSpawnError({ command: sshCommand, argumentCount: args.length, - exitCode: null, - stderrBytes: 0, target: input.resolvedTarget.alias, cause, }), @@ -1178,8 +1180,6 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: new SshTunnelMonitorError({ command: sshCommand, argumentCount: args.length, - exitCode: null, - stderrBytes: 0, target: input.resolvedTarget.alias, cause, }), @@ -1191,6 +1191,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: exitCode, stderrBytes: utf8ByteLength(stderr), target: input.resolvedTarget.alias, + reason: SshAuth.classifySshProcessExit({ stdout: "", stderr }), }); return Effect.logWarning("ssh.tunnel.process.exited", { ...sshTargetLogFields(input.resolvedTarget), @@ -1319,10 +1320,6 @@ export const make = Effect.fn("ssh/tunnel.SshEnvironmentManager.make")(function* yield* Deferred.fail( pending, new SshCommandCancelledError({ - command: "ssh", - argumentCount: 0, - exitCode: null, - stderrBytes: 0, target: target.alias || target.hostname, }), ).pipe(Effect.ignore);