fix: show why SSH connection tests and runs fail (#7)
Test connection, key installation and runs now tell authentication failures apart from unreachable hosts (refused, timeout, DNS, ...) instead of a generic "SSH connection failed". The web client keeps the server's deliberate error messages (4xx, 502, 503) and shows them in the hosts page; unexpected 500 errors still show only the status. The reload hint appears only on 409 conflicts.
This commit is contained in:
@@ -17,7 +17,7 @@ import {
|
|||||||
httpError,
|
httpError,
|
||||||
SerialQueue,
|
SerialQueue,
|
||||||
} from "../workspace";
|
} from "../workspace";
|
||||||
import { connect, exec, forgetHostKey, HostKeyError } from "../ssh";
|
import { connect, exec, forgetHostKey, HostKeyError, sshFailure } from "../ssh";
|
||||||
import { CredentialStore } from "./credentials";
|
import { CredentialStore } from "./credentials";
|
||||||
import { validateHost } from "./validation";
|
import { validateHost } from "./validation";
|
||||||
const saves = new SerialQueue();
|
const saves = new SerialQueue();
|
||||||
@@ -221,7 +221,7 @@ export async function hostsPlugin(
|
|||||||
changed: e.changed,
|
changed: e.changed,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
throw httpError(502, "SSH connection or action failed");
|
throw httpError(502, sshFailure(e) ?? "SSH connection or action failed");
|
||||||
} finally {
|
} finally {
|
||||||
client?.end();
|
client?.end();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import type { FastifyInstance } from "fastify";
|
|||||||
import type { Client } from "ssh2";
|
import type { Client } from "ssh2";
|
||||||
import type { ServerConfig } from "../config";
|
import type { ServerConfig } from "../config";
|
||||||
import { readHosts, readNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace";
|
import { readHosts, readNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace";
|
||||||
import { connect, exec, localExec, scriptInput, sftp, sftpRequest, transfer, HostKeyError, type Output } from "../ssh";
|
import { connect, exec, localExec, scriptInput, sftp, sftpRequest, transfer, HostKeyError, sshFailure, type Output } from "../ssh";
|
||||||
import { EventsHub } from "./events";
|
import { EventsHub } from "./events";
|
||||||
import { runRoot, artifactFile, persistArtifacts, isSensitive, claimArtifact, sweepRuns } from "./artifacts";
|
import { runRoot, artifactFile, persistArtifacts, isSensitive, claimArtifact, sweepRuns } from "./artifacts";
|
||||||
export { EventsHub } from "./events";
|
export { EventsHub } from "./events";
|
||||||
@@ -232,7 +232,8 @@ export async function runsPlugin(app: FastifyInstance, { config, hub }: { config
|
|||||||
function runFailure(error: unknown, fallback: string, timeoutSec: number): string {
|
function runFailure(error: unknown, fallback: string, timeoutSec: number): string {
|
||||||
const e = error as { message?: string; level?: string; code?: string };
|
const e = error as { message?: string; level?: string; code?: string };
|
||||||
if (e.message === "Execution timed out") return `Execution timed out after ${timeoutSec} s`;
|
if (e.message === "Execution timed out") return `Execution timed out after ${timeoutSec} s`;
|
||||||
if (e.level === "client-authentication") return "SSH authentication failed";
|
const ssh = sshFailure(error);
|
||||||
|
if (ssh) return ssh;
|
||||||
if (e.message === "Captured output exceeds 1 MiB") return e.message;
|
if (e.message === "Captured output exceeds 1 MiB") return e.message;
|
||||||
if (e.message?.startsWith("SFTP ") && e.message.endsWith(" timed out")) return "File transfer timed out";
|
if (e.message?.startsWith("SFTP ") && e.message.endsWith(" timed out")) return "File transfer timed out";
|
||||||
return fallback;
|
return fallback;
|
||||||
|
|||||||
@@ -162,3 +162,17 @@ export async function forgetHostKey(config: ServerConfig, host: HostInfo) {
|
|||||||
await writeFile(file, lines.join("\n"), { mode: 0o600 });
|
await writeFile(file, lines.join("\n"), { mode: 0o600 });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const unreachable: Record<string, string> = {
|
||||||
|
ECONNREFUSED: "connection refused", EHOSTUNREACH: "host unreachable", ENETUNREACH: "network unreachable",
|
||||||
|
ENOTFOUND: "unknown host name", EAI_AGAIN: "host name lookup failed", ETIMEDOUT: "connection timed out",
|
||||||
|
ECONNRESET: "connection reset",
|
||||||
|
};
|
||||||
|
/** User-facing reason for a failed SSH connection; undefined when not a connection problem. Never includes secrets. */
|
||||||
|
export function sshFailure(error: unknown): string | undefined {
|
||||||
|
const e = error as { level?: string; code?: string } | null;
|
||||||
|
if (e?.level === "client-authentication") return "SSH authentication failed: check the user and the saved password or key";
|
||||||
|
if (e?.level === "client-timeout") return "Cannot reach the server: SSH handshake timed out";
|
||||||
|
if (e?.code && unreachable[e.code]) return `Cannot reach the server: ${unreachable[e.code]}`;
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|||||||
@@ -454,3 +454,22 @@ it("refuses to write credential secrets inside the git workspace", async () => {
|
|||||||
).rejects.toThrow("outside the workspace");
|
).rejects.toThrow("outside the workspace");
|
||||||
expect(await readdir(dir)).not.toContain("ssh-credentials.key");
|
expect(await readdir(dir)).not.toContain("ssh-credentials.key");
|
||||||
});
|
});
|
||||||
|
it("tells wrong credentials apart from unreachable hosts on Test connection", async () => {
|
||||||
|
const { app, config, store } = await fixture();
|
||||||
|
const ssh = await createSshFixture(config, cleanup, false);
|
||||||
|
const { createServer } = await import("node:net");
|
||||||
|
const closed = createServer();
|
||||||
|
await new Promise<void>(resolve => closed.listen(0, "127.0.0.1", resolve));
|
||||||
|
const port = (closed.address() as import("node:net").AddressInfo).port;
|
||||||
|
await new Promise(resolve => closed.close(resolve));
|
||||||
|
const offline = { ...ssh.host, name: "offline", port };
|
||||||
|
await writeFile(path.join(config.workspaceDir, "hosts.yaml"), JSON.stringify([ssh.host, offline]));
|
||||||
|
await store.set(ssh.host.name, { type: "password", password: "wrong" });
|
||||||
|
const denied = await app.inject({ method: "POST", url: `/api/host-management/${ssh.host.name}/action`, payload: { action: "test", acceptHostKey: ssh.fp } });
|
||||||
|
expect(denied.statusCode).toBe(502);
|
||||||
|
expect(denied.body).toMatch(/authentication failed/i);
|
||||||
|
expect(denied.body).not.toContain("wrong");
|
||||||
|
const unreachable = await app.inject({ method: "POST", url: "/api/host-management/offline/action", payload: { action: "test" } });
|
||||||
|
expect(unreachable.statusCode).toBe(502);
|
||||||
|
expect(unreachable.body).toMatch(/cannot reach/i);
|
||||||
|
});
|
||||||
|
|||||||
@@ -205,5 +205,5 @@ it("reports SSH authentication failure without raw transport details", async ()
|
|||||||
const f = await httpFixture(false);
|
const f = await httpFixture(false);
|
||||||
const result = await run(f, 'authorize');
|
const result = await run(f, 'authorize');
|
||||||
expect(result.finished.exitCode).toBe(-1);
|
expect(result.finished.exitCode).toBe(-1);
|
||||||
expect(f.events).toContainEqual({ type: 'run.error', runId: result.id, message: 'SSH authentication failed' });
|
expect(f.events).toContainEqual({ type: 'run.error', runId: result.id, message: 'SSH authentication failed: check the user and the saved password or key' });
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -58,7 +58,12 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
|
|||||||
try {
|
try {
|
||||||
await work();
|
await work();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(`${String(e)}. Reload hosts after a conflict before retrying.`);
|
const message = e instanceof Error ? e.message : String(e);
|
||||||
|
setError(
|
||||||
|
(e as { status?: number }).status === 409
|
||||||
|
? `${message}. Reload hosts before retrying.`
|
||||||
|
: message,
|
||||||
|
);
|
||||||
} finally {
|
} finally {
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-3
@@ -9,8 +9,21 @@ import type {
|
|||||||
} from "@shellbook/core";
|
} from "@shellbook/core";
|
||||||
|
|
||||||
export class HttpError extends Error {
|
export class HttpError extends Error {
|
||||||
constructor(public status: number) {
|
constructor(
|
||||||
super(`Request failed (${status})`);
|
public status: number,
|
||||||
|
serverMessage?: string,
|
||||||
|
) {
|
||||||
|
super(serverMessage || `Request failed (${status})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/** Deliberate errors (4xx, 502, 503) carry a user-facing `message`; unexpected 500s may expose internals. */
|
||||||
|
async function serverMessage(response: Response): Promise<string | undefined> {
|
||||||
|
if (response.status === 500) return undefined;
|
||||||
|
try {
|
||||||
|
const body = (await response.json()) as { message?: unknown };
|
||||||
|
return typeof body.message === "string" ? body.message.slice(0, 500) : undefined;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export async function json<T>(
|
export async function json<T>(
|
||||||
@@ -24,7 +37,8 @@ export async function json<T>(
|
|||||||
headers: body === undefined ? {} : { "Content-Type": "application/json" },
|
headers: body === undefined ? {} : { "Content-Type": "application/json" },
|
||||||
body: body === undefined ? undefined : JSON.stringify(body),
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
});
|
});
|
||||||
if (!response.ok) throw new HttpError(response.status);
|
if (!response.ok)
|
||||||
|
throw new HttpError(response.status, await serverMessage(response));
|
||||||
return response.status === 204
|
return response.status === 204
|
||||||
? (undefined as T)
|
? (undefined as T)
|
||||||
: (response.json() as Promise<T>);
|
: (response.json() as Promise<T>);
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { afterEach, expect, it, vi } from "vitest";
|
||||||
|
import { HttpError, json } from "../api";
|
||||||
|
afterEach(() => vi.unstubAllGlobals());
|
||||||
|
it("keeps the server's error message and status", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ statusCode: 502, error: "Bad Gateway", message: "SSH authentication failed: check the user and the saved password or key" }), { status: 502, headers: { "Content-Type": "application/json" } })));
|
||||||
|
const error = (await json("/x").catch((e: HttpError) => e)) as HttpError;
|
||||||
|
expect(error).toBeInstanceOf(HttpError);
|
||||||
|
expect(error.status).toBe(502);
|
||||||
|
expect(error.message).toBe("SSH authentication failed: check the user and the saved password or key");
|
||||||
|
});
|
||||||
|
it("falls back to the status when the body is not JSON", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn(async () => new Response("<html>", { status: 500 })));
|
||||||
|
expect(((await json("/x").catch((e: HttpError) => e)) as HttpError).message).toBe("Request failed (500)");
|
||||||
|
});
|
||||||
|
it("does not surface messages of unexpected server errors", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ statusCode: 500, message: "EACCES: permission denied, open '/var/lib/shellbook/x'" }), { status: 500 })));
|
||||||
|
expect(((await json("/x").catch((e: HttpError) => e)) as HttpError).message).toBe("Request failed (500)");
|
||||||
|
});
|
||||||
@@ -117,3 +117,14 @@ it("loads external changes without silently changing the version of an open edit
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
it("shows the server's reason for a failed connection test without a conflict hint", async () => {
|
||||||
|
vi.mocked(json).mockImplementation(async (url) => {
|
||||||
|
if (url.endsWith("/action")) throw Object.assign(new Error("SSH authentication failed: check the user and the saved password or key"), { status: 502 });
|
||||||
|
return inventory;
|
||||||
|
});
|
||||||
|
render(<HostsPage />);
|
||||||
|
await screen.findByText("demo");
|
||||||
|
fireEvent.click(screen.getByText("Test connection to demo"));
|
||||||
|
const alert = await screen.findByText(/SSH authentication failed/);
|
||||||
|
expect(alert.textContent).toBe("SSH authentication failed: check the user and the saved password or key");
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user