[codex] Preserve SSH exit diagnostics

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-20 20:17:07 -07:00
1 parent 8abe5f15a6
commit 0d94e227e6
8 files changed
+148 -74

No files matched your search

@@ -98,8 +98,6 @@ describe("SSH environment IPC", () => {
const structured = new SshCommandSpawnError({
command: "ssh",
argumentCount: 0,
exitCode: null,
stderrBytes: 0,
target: "devbox",
cause,
});
-6
View File
@@ -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,
});
+16
View File
@@ -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;
+1 -3
View File
@@ -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));
});
+1 -10
View File
@@ -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,
});
+47 -41
View File
@@ -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>()(
"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>()(
"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>()(
"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>()(
"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>()(
"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>()(
"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>()(
"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>()(
"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>()(
"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>()(
"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>()(
"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>()(
"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>()(
"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>()(
"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>()(
"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})`;
}
+74
View File
@@ -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<ReadonlyArray<string>> = [];
let tunnelKillCount = 0;
+9 -12
View File
@@ -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);