diff --git a/.changeset/containers-keyless-ssh.md b/.changeset/containers-keyless-ssh.md new file mode 100644 index 00000000000..66d91b5233e --- /dev/null +++ b/.changeset/containers-keyless-ssh.md @@ -0,0 +1,18 @@ +--- +"wrangler": minor +"@cloudflare/containers-shared": minor +--- + +Open a shell in a Container with `wrangler containers ssh` without SSH keys or OpenSSH + +`wrangler containers ssh ` now connects over the Containers shell connection by default. It no longer needs `authorized_keys` in the Container configuration or a local OpenSSH install. Pass a command after `--` to run it. Wrangler allocates a terminal when stdin and stdout are terminals. Pass `--no-tty` to turn it off: + +`wrangler containers ssh -- ls /` + +Wrangler runs the command directly, not through a remote shell. To use shell syntax, run `sh -c`: + +`wrangler containers ssh -- sh -c 'ls / | head'` + +Pass `--legacy-openssh` to use the previous connection with OpenSSH and the Container's authorized keys. `--legacy-openssh` is deprecated and will be removed in a future release. The hidden OpenSSH options also select this connection. + +OpenSSH `ProxyCommand` setups keep working for port forwarding, SFTP and IDE tools such as VS Code Remote-SSH. With `--stdio`, or when stdin and stdout are both redirected and no command is given, Wrangler proxies SSH traffic to the Container as before. A command after `--` now runs in the Container, even when both streams are redirected. A `ProxyCommand` that passes arguments after `--` must add `--stdio`. diff --git a/.changeset/spinner-show-cursor.md b/.changeset/spinner-show-cursor.md new file mode 100644 index 00000000000..29d7eaf262b --- /dev/null +++ b/.changeset/spinner-show-cursor.md @@ -0,0 +1,7 @@ +--- +"@cloudflare/cli-shared-helpers": patch +--- + +Show the cursor again when a spinner stops without a message + +Before, the cursor stayed hidden until the process exited. This hid the cursor in long-running commands such as `wrangler containers ssh`. diff --git a/packages/cli/__tests__/interactive.test.ts b/packages/cli/__tests__/interactive.test.ts new file mode 100644 index 00000000000..9b5574dce42 --- /dev/null +++ b/packages/cli/__tests__/interactive.test.ts @@ -0,0 +1,37 @@ +import { afterEach, beforeEach, describe, test, vi } from "vitest"; +import { spinner } from "../interactive"; + +const logUpdate = vi.hoisted(() => + Object.assign(vi.fn(), { clear: vi.fn(), done: vi.fn() }) +); + +vi.mock("log-update", () => ({ createLogUpdate: () => logUpdate })); + +describe("spinner", () => { + const isTTY = [process.stdin.isTTY, process.stdout.isTTY] as const; + + beforeEach(() => { + vi.useFakeTimers(); + process.stdin.isTTY = true; + process.stdout.isTTY = true; + }); + + afterEach(() => { + vi.useRealTimers(); + [process.stdin.isTTY, process.stdout.isTTY] = isTTY; + logUpdate.mockClear(); + logUpdate.clear.mockClear(); + logUpdate.done.mockClear(); + }); + + test.for([undefined, "done"])( + "shows the cursor again when stopped with message %s", + (message, { expect }) => { + const s = spinner(); + s.start("Loading"); + vi.advanceTimersByTime(500); + s.stop(message); + expect(logUpdate.done).toHaveBeenCalledOnce(); + } + ); +}); diff --git a/packages/cli/interactive.ts b/packages/cli/interactive.ts index 9da02901607..8480edb7a64 100644 --- a/packages/cli/interactive.ts +++ b/packages/cli/interactive.ts @@ -688,7 +688,10 @@ export const spinner = ( logUpdate.clear(); if (msg) { logUpdate(`${leftT} ${startMsg}\n${grayBar} ${msg}`); - logUpdate.done(); + } + // Shows the cursor, which logUpdate hides on every frame. + logUpdate.done(); + if (msg) { newline(); } clearLoop(); diff --git a/packages/containers-shared/src/shell.ts b/packages/containers-shared/src/shell.ts new file mode 100644 index 00000000000..d6c51c045cb --- /dev/null +++ b/packages/containers-shared/src/shell.ts @@ -0,0 +1,239 @@ +import { WebSocket } from "ws"; +import type { WranglerSSHResponse } from "./client"; +import type { IncomingMessage } from "node:http"; +import type { Readable, Writable } from "node:stream"; + +const STDIN = 0; +const STDOUT = 1; +const STDERR = 2; +const EXIT = 3; +const RESIZE = 4; +const SIGNAL = 5; +const EOF = 6; +const ACK = 7; +const START = 8; + +/** Output is acknowledged in steps of this many bytes. The gateway holds output past 1 MiB. */ +const ACK_BYTES = 64 * 1024; + +export interface TerminalSize { + cols: number; + rows: number; +} + +export interface ShellRequest { + /** The argv to run. Omit it for the default login shell. */ + command?: string[]; + /** Allocates a PTY with this initial size. */ + pty?: TerminalSize; +} + +export interface ShellStreams { + stdin: Readable; + stdout: Writable; + stderr: Writable; +} + +export interface ShellSession { + /** Resolves when the WebSocket opens. */ + opened: Promise; + /** Resolves with the remote exit code. */ + exited: Promise; + readonly isOpen: boolean; + resize(size: TerminalSize): void; + signal(signal: number): void; + close(): void; +} + +/** Stdin pauses while more than this many bytes are not acknowledged. The gateway disconnects at 1 MiB. */ +const MAX_UNACKED_INPUT = 512 * 1024; + +/** + * Runs a process in a Container over the shell WebSocket and connects it to + * `streams`. Byte 0 of each binary frame is the channel. The first frame + * starts the process. It keeps the command out of the URL, which request logs + * record. Closing the WebSocket kills the process. + */ +export function openShell( + mint: WranglerSSHResponse, + request: ShellRequest, + streams: ShellStreams, + userAgent: string +): ShellSession { + const url = new URL("/shell", mint.url); + const start = JSON.stringify({ + command: request.command, + ...(request.pty === undefined ? {} : { tty: true, ...request.pty }), + }); + + const ws = new WebSocket(url, ["cf-container-shell.v1"], { + headers: { + authorization: `Bearer ${mint.token}`, + "user-agent": userAgent, + }, + }); + + let inputPaused = false; + let unackedInput = 0; + const send = (channel: number, payload: Uint8Array | string = "") => { + if (ws.readyState !== WebSocket.OPEN) { + return; + } + const body = Buffer.from(payload); + ws.send(Buffer.concat([Buffer.from([channel]), body])); + if (channel === STDIN) { + unackedInput += body.length; + if (!inputPaused && unackedInput > MAX_UNACKED_INPUT) { + inputPaused = true; + streams.stdin.pause(); + } + } + }; + const inputAcknowledged = (bytes: number) => { + unackedInput -= bytes; + if (inputPaused && unackedInput <= MAX_UNACKED_INPUT) { + inputPaused = false; + streams.stdin.resume(); + } + }; + const onData = (data: Buffer) => send(STDIN, data); + const onEnd = () => send(EOF); + const detachInput = () => { + streams.stdin.off("data", onData); + streams.stdin.off("end", onEnd); + streams.stdin.pause(); + inputPaused = false; + }; + const opened = new Promise((resolve) => + ws.on("open", () => { + send(START, start); + streams.stdin.on("data", onData); + streams.stdin.on("end", onEnd); + streams.stdin.resume(); + resolve(); + }) + ); + + // Output bytes written to the streams but not yet acknowledged. + let handled = 0; + const acknowledge = (bytes: number) => { + handled += bytes; + if (handled >= ACK_BYTES && ws.readyState === WebSocket.OPEN) { + const frame = Buffer.alloc(5); + frame[0] = ACK; + frame.writeUInt32BE(handled, 1); + handled = 0; + ws.send(frame); + } + }; + + const exited = new Promise((resolve, reject) => { + const write = (stream: Writable, payload: Buffer) => { + stream.write(payload, (err) => { + if (err) { + // The reader closed the pipe. Stop the process, as SIGPIPE would. + resolve(128 + LINUX_SIGNALS.PIPE); + } else { + acknowledge(payload.length); + } + }); + }; + ws.on("message", (data: Buffer, isBinary) => { + if (!isBinary || data.length === 0) { + return; + } + const payload = data.subarray(1); + switch (data[0]) { + case ACK: + if (payload.length === 4) { + inputAcknowledged(payload.readUInt32BE(0)); + } + break; + case STDOUT: + write(streams.stdout, payload); + break; + case STDERR: + write(streams.stderr, payload); + break; + case EXIT: { + let status: { exit_code?: number; error?: string }; + try { + status = JSON.parse(payload.toString()); + } catch { + reject(new Error("Invalid exit status from the shell connection")); + break; + } + if (status.error !== undefined) { + reject(new Error(status.error)); + } else { + resolve(status.exit_code ?? 0); + } + break; + } + } + }); + ws.on("unexpected-response", (req, res: IncomingMessage) => { + const chunks: Buffer[] = []; + res.on("data", (chunk: Buffer) => chunks.push(chunk)); + res.on("end", () => { + reject( + new Error( + `Shell connection failed with status ${res.statusCode}${errorDetail(Buffer.concat(chunks).toString())}` + ) + ); + req.destroy(); + }); + }); + ws.on("error", (err) => + reject(new Error(`Shell connection error: ${err.message}`)) + ); + ws.on("close", () => { + detachInput(); + reject(new Error("Shell connection closed before the process exited")); + }); + }); + + return { + opened, + exited, + get isOpen() { + return ws.readyState === WebSocket.OPEN; + }, + resize: (size) => send(RESIZE, JSON.stringify(size)), + signal: (signal) => send(SIGNAL, JSON.stringify({ signal })), + close: () => { + detachInput(); + ws.close(); + }, + }; +} + +function errorDetail(body: string): string { + try { + const parsed = JSON.parse(body) as { + error?: string; + errors?: { message: string }[]; + }; + const message = parsed.error ?? parsed.errors?.[0]?.message; + return message === undefined ? "" : `: ${message}`; + } catch { + return body === "" ? "" : `: ${body}`; + } +} + +/** POSIX signal numbers on Linux, keyed by SSH signal name (RFC 4254). */ +export const LINUX_SIGNALS = { + HUP: 1, + INT: 2, + QUIT: 3, + ILL: 4, + ABRT: 6, + FPE: 8, + KILL: 9, + USR1: 10, + SEGV: 11, + USR2: 12, + PIPE: 13, + ALRM: 14, + TERM: 15, +} as const; diff --git a/packages/containers-shared/src/ssh.ts b/packages/containers-shared/src/ssh.ts index b423a4807a8..0cc80de85b9 100644 --- a/packages/containers-shared/src/ssh.ts +++ b/packages/containers-shared/src/ssh.ts @@ -6,6 +6,7 @@ import { bold } from "@cloudflare/cli-shared-helpers/colors"; import { WebSocket } from "ws"; import { ApiError, DeploymentsService } from "./client"; import { logger } from "./context"; +import { LINUX_SIGNALS, openShell } from "./shell"; import { promiseSpinner } from "./spinner"; import type { WranglerSSHResponse } from "./client"; import type { Server, Socket } from "node:net"; @@ -16,6 +17,7 @@ export interface ContainerSshArgs { command?: string[]; stdio?: boolean; tty?: boolean; + legacyOpenssh?: boolean; cipher?: string; logFile?: string; escapeChar?: string; @@ -27,8 +29,8 @@ export interface ContainerSshArgs { tag?: string; } -// Deprecated SSH flags are hidden because a future SSH implementation -// will not use OpenSSH, at which point these options will not work. +// Deprecated SSH flags are hidden. They select the OpenSSH connection, which +// goes away once the shell connection supports port forwarding. export const containersSshOptions = { cipher: { describe: @@ -103,43 +105,41 @@ export const containersSshOptions = { tty: { alias: "t", describe: - "Force pseudo-terminal allocation, e.g. for interactive commands like `-- bash`", + "Allocate a pseudo-terminal. By default, one is allocated when stdin and stdout are terminals. With --legacy-openssh, the OpenSSH default applies", type: "boolean", }, + "legacy-openssh": { + describe: + "Connect with OpenSSH and the container's authorized keys. Needed for port forwarding. This option will be removed in a future release", + type: "boolean", + deprecated: true, + }, } as const; /** - * Connect to a Container over SSH. Before calling, configure the OpenAPI client - * with the account API base URL and authentication, and call + * Connect to a Container. Before calling, configure the OpenAPI client with + * the account API base URL and authentication, and call * initContainersSharedContext to supply the CLI's logger. + * + * @returns the remote exit code of a shell or command */ -export async function sshCommand(sshArgs: ContainerSshArgs, userAgent: string) { +export async function sshCommand( + sshArgs: ContainerSshArgs, + userAgent: string +): Promise { const useStdio = shouldUseStdio(sshArgs); - - // Check that ssh is enabled - let sshResponse: WranglerSSHResponse; - try { - const sshPromise = DeploymentsService.containerWranglerSsh(sshArgs.id); - sshResponse = useStdio - ? await sshPromise - : await promiseSpinner(sshPromise, { message: "Authenticating" }); - } catch (e) { - if (e instanceof ApiError) { - if (e.status === 404) { - throw new Error(`Instance ${sshArgs.id} not found`); - } - - let msg = `Error verifying SSH access`; - if (e.body.error !== undefined) { - msg += `: ${e.body.error}`; - } - - throw new Error(msg); - } - - throw e; + // The spinner writes to stdout, so it would mix with redirected output. + const mint = () => + useStdio || process.stdout.isTTY !== true + ? mintSshToken(sshArgs.id) + : promiseSpinner(mintSshToken(sshArgs.id), { message: "Authenticating" }); + + if (!usesOpenssh(sshArgs) && !useStdio) { + return runShell(await mint(), sshArgs, userAgent); } + const sshResponse = await mint(); + const ws = new WebSocket(sshResponse.url, { headers: { authorization: `Bearer ${sshResponse.token}`, @@ -228,6 +228,96 @@ export async function sshCommand(sshArgs: ContainerSshArgs, userAgent: string) { } } +async function mintSshToken(id: string): Promise { + try { + return await DeploymentsService.containerWranglerSsh(id); + } catch (e) { + if (e instanceof ApiError) { + if (e.status === 404) { + throw new Error(`Instance ${id} not found`); + } + + let msg = `Error verifying SSH access`; + if (e.body.error !== undefined) { + msg += `: ${e.body.error}`; + } + + throw new Error(msg); + } + + throw e; + } +} + +/** + * Runs a shell or command attached to this process's stdio. A PTY is used + * when stdin and stdout are terminals, unless `--tty` or `--no-tty` says + * otherwise. + */ +async function runShell( + sshResponse: WranglerSSHResponse, + sshArgs: ContainerSshArgs, + userAgent: string +): Promise { + const { stdin, stdout, stderr } = process; + const command = sshArgs.command?.length ? sshArgs.command : undefined; + const usePty = sshArgs.tty ?? (stdin.isTTY === true && stdout.isTTY === true); + const terminal = [stdout, stderr].find((stream) => stream.isTTY === true); + const size = () => ({ + cols: terminal?.columns || 80, + rows: terminal?.rows || 24, + }); + const shell = openShell( + sshResponse, + { command, pty: usePty ? size() : undefined }, + { stdin, stdout, stderr }, + userAgent + ); + + let interrupted = false; + let stop = (_code: number) => {}; + const stopped = new Promise((resolve) => (stop = resolve)); + // A second Ctrl-C, or one before the connection opens, closes the + // connection, so a remote that ignores SIGINT cannot keep wrangler alive. + // In a PTY, raw mode sends Ctrl-C to the remote terminal instead. + const onInterrupt = () => { + if (interrupted || !shell.isOpen) { + stop(130); + } else { + interrupted = true; + shell.signal(LINUX_SIGNALS.INT); + } + }; + const onResize = () => shell.resize(size()); + // Raw mode starts after the connection opens, so that Ctrl-C can still + // interrupt a connection that does not open. + let raw = false; + let done = false; + void shell.opened.then(() => { + if (!done && usePty && stdin.isTTY === true) { + raw = true; + stdin.setRawMode(true); + } + }); + try { + if (usePty) { + terminal?.on("resize", onResize); + } + process.on("SIGINT", onInterrupt); + return await Promise.race([shell.exited, stopped]); + } finally { + done = true; + process.off("SIGINT", onInterrupt); + terminal?.off("resize", onResize); + stdin.pause(); + if (raw) { + stdin.setRawMode(false); + } + shell.close(); + showCursor(true); + } +} + export function verifySshInstalled(sshPath: string): Promise { return new Promise((resolve, reject) => { const child = spawn(sshPath, ["-V"]); @@ -348,17 +438,43 @@ function formatWebSocketData(data: RawData) { return data instanceof ArrayBuffer ? new Uint8Array(data) : data; } -export function shouldUseStdio(sshArgs: { stdio?: boolean; tty?: boolean }) { +/** + * Detects OpenSSH `ProxyCommand` usage, which uses the OpenSSH path: + * `--stdio`, or both stdin and stdout redirected without a command. With + * the OpenSSH connection, a command does not prevent it. + */ +export function shouldUseStdio(sshArgs: Omit) { return ( sshArgs.stdio === true || - // An explicit --tty requests an OpenSSH session, so it must not be + // An explicit --tty requests a terminal session, so it must not be // mistaken for ProxyCommand usage when both streams are redirected. (sshArgs.tty !== true && + (usesOpenssh(sshArgs) || !sshArgs.command?.length) && process.stdin.isTTY !== true && process.stdout.isTTY !== true) ); } +const OPENSSH_OPTIONS = [ + "cipher", + "logFile", + "escapeChar", + "configFile", + "pkcs11", + "identityFile", + "macSpec", + "option", + "tag", +] as const; + +/** --legacy-openssh or any OpenSSH option selects the OpenSSH connection. */ +function usesOpenssh(sshArgs: Omit) { + return ( + sshArgs.legacyOpenssh === true || + OPENSSH_OPTIONS.some((option) => sshArgs[option] !== undefined) + ); +} + function buildContainerSshArgs(sshArgs: ContainerSshArgs): string[] { const flags = [ // Never use a control socket. diff --git a/packages/containers-shared/tests/ssh.test.ts b/packages/containers-shared/tests/ssh.test.ts index 77822ac32e5..168ae7c0aa2 100644 --- a/packages/containers-shared/tests/ssh.test.ts +++ b/packages/containers-shared/tests/ssh.test.ts @@ -1,28 +1,33 @@ import { EventEmitter, once } from "node:events"; +import { createServer } from "node:http"; import { connect } from "node:net"; -import { PassThrough } from "node:stream"; +import { PassThrough, Writable } from "node:stream"; import { showCursor } from "@cloudflare/cli-shared-helpers"; import { afterEach, beforeEach, describe, it, vi } from "vitest"; import { WebSocketServer } from "ws"; import { ApiError, DeploymentsService } from "../src/client"; import { shouldUseStdio, sshCommand } from "../src/ssh"; import type { ChildProcess } from "node:child_process"; +import type { IncomingMessage } from "node:http"; +import type { Socket } from "node:net"; +import type { WebSocket } from "ws"; -const { spawn } = vi.hoisted(() => ({ spawn: vi.fn() })); -vi.mock("node:child_process", () => ({ spawn })); -vi.mock("../src/spinner", () => ({ - promiseSpinner: (promise: Promise) => promise, +const { spawn, promiseSpinner } = vi.hoisted(() => ({ + spawn: vi.fn(), + promiseSpinner: vi.fn((promise: Promise) => promise), })); +vi.mock("node:child_process", () => ({ spawn })); +vi.mock("../src/spinner", () => ({ promiseSpinner })); vi.mock("@cloudflare/cli-shared-helpers", () => ({ showCursor: vi.fn() })); const originalStdin = process.stdin; const originalStdout = process.stdout; const servers: WebSocketServer[] = []; -function streams(tty = false) { +function streams(tty = false, stdoutTty = tty) { const stdin = new PassThrough(); const stdout = new PassThrough(); Object.defineProperty(stdin, "isTTY", { value: tty }); - Object.defineProperty(stdout, "isTTY", { value: tty }); + Object.defineProperty(stdout, "isTTY", { value: stdoutTty }); Object.defineProperty(process, "stdin", { value: stdin, configurable: true }); Object.defineProperty(process, "stdout", { value: stdout, @@ -46,6 +51,7 @@ async function server() { } beforeEach(() => { spawn.mockReset(); + promiseSpinner.mockClear(); vi.mocked(showCursor).mockClear(); streams(); }); @@ -72,7 +78,14 @@ describe("shared Container SSH", () => { expect, }) => { expect(shouldUseStdio({})).toBe(true); + expect(shouldUseStdio({ legacyOpenssh: true })).toBe(true); expect(shouldUseStdio({ tty: true })).toBe(false); + expect(shouldUseStdio({ command: ["ls"] })).toBe(false); + expect(shouldUseStdio({ command: ["ls"], stdio: true })).toBe(true); + expect(shouldUseStdio({ legacyOpenssh: true, command: ["22"] })).toBe(true); + expect(shouldUseStdio({ identityFile: "/tmp/key", command: ["22"] })).toBe( + true + ); expect(shouldUseStdio({ stdio: true, tty: true })).toBe(true); streams(true); expect(shouldUseStdio({})).toBe(false); @@ -127,7 +140,7 @@ describe("shared Container SSH", () => { ); } }); - it("forwards commands and options when OpenSSH connects after the WebSocket opens", async ({ + it("uses OpenSSH for OpenSSH options and forwards commands and options after the WebSocket opens", async ({ expect, }) => { streams(true); @@ -205,7 +218,7 @@ describe("shared Container SSH", () => { return child; }); await sshCommand( - { id: "instance", tty: true, command: ["top"] }, + { id: "instance", legacyOpenssh: true, tty: true, command: ["top"] }, "test-cli" ); expect(childArgs).toContain("RequestTTY=force"); @@ -231,7 +244,10 @@ describe("shared Container SSH", () => { ); return child; }); - const run = sshCommand({ id: "instance" }, "test-cli"); + const run = sshCommand( + { id: "instance", legacyOpenssh: true }, + "test-cli" + ); const rejection = expect(run).rejects.toThrow( failure === "missing-binary" ? "Verifying SSH installation failed" @@ -245,3 +261,338 @@ describe("shared Container SSH", () => { }); } }); + +describe("Container shell", () => { + /** Accepts a shell connection as the gateway. It records frames and acks. */ + async function connection(ws: WebSocketServer) { + const [socket, request] = (await once(ws, "connection")) as [ + WebSocket, + IncomingMessage, + ]; + const url = new URL(request.url ?? "", "http://localhost"); + const frames: string[] = []; + const acks: number[] = []; + const input = { bytes: 0, acked: 0 }; + socket.on("message", (data: Buffer) => { + if (data[0] === 7) { + acks.push(data.readUInt32BE(1)); + return; + } + if (data[0] === 0) { + input.bytes += data.length - 1; + } + frames.push(data.toString()); + }); + const output = (channel: number, data: Buffer | string) => + socket.send(Buffer.concat([Buffer.from([channel]), Buffer.from(data)])); + const ackInput = () => { + const frame = Buffer.alloc(5); + frame[0] = 7; + frame.writeUInt32BE(input.bytes - input.acked, 1); + input.acked = input.bytes; + socket.send(frame); + }; + return { + socket, + request, + url, + params: [...url.searchParams], + frames, + acks, + output, + input, + ackInput, + }; + } + + it("runs a command without a PTY, pipes stdio, and returns the exit code", async ({ + expect, + }) => { + const { stdin, stdout } = streams(); + const stderr = vi + .spyOn(process.stderr, "write") + .mockImplementation(() => true); + const ws = await server(); + const connected = connection(ws); + const run = sshCommand( + { id: "instance", command: ["echo", "hi"] }, + "test-cli" + ); + const { socket, request, url, params, frames, output } = await connected; + expect(url.pathname).toBe("/shell"); + expect(params).toEqual([]); + expect(request.headers.authorization).toBe("Bearer ssh-token"); + expect(socket.protocol).toBe("cf-container-shell.v1"); + + stdin.end("input"); + const start = '\x08{"command":["echo","hi"]}'; + await vi.waitFor(() => expect(frames).toEqual([start, "\0input", "\x06"])); + process.emit("SIGINT"); + await vi.waitFor(() => + expect(frames).toEqual([start, "\0input", "\x06", '\x05{"signal":2}']) + ); + + const written = once(stdout, "data"); + output(1, "out"); + expect((await written)[0].toString()).toBe("out"); + output(2, "err"); + socket.send(Buffer.from('\x03{"exit_code":3}')); + socket.close(1000); + await expect(run).resolves.toBe(3); + expect(stderr).toHaveBeenCalledWith( + Buffer.from("err"), + expect.any(Function) + ); + expect(process.listenerCount("SIGINT")).toBe(0); + }); + + it("opens a PTY in raw mode, sends resizes, and restores the terminal on error", async ({ + expect, + }) => { + const { stdin, stdout } = streams(true); + const setRawMode = vi.fn(); + Object.assign(stdin, { setRawMode }); + Object.assign(stdout, { columns: 100, rows: 30 }); + const ws = await server(); + const connected = connection(ws); + const run = sshCommand({ id: "instance" }, "test-cli"); + const { socket, params, frames } = await connected; + expect(params).toEqual([]); + expect(promiseSpinner).toHaveBeenCalledOnce(); + await vi.waitFor(() => + expect(frames).toEqual(['\x08{"tty":true,"cols":100,"rows":30}']) + ); + await vi.waitFor(() => expect(setRawMode).toHaveBeenCalledWith(true)); + + Object.assign(stdout, { columns: 120 }); + stdout.emit("resize"); + await vi.waitFor(() => + expect(frames).toEqual([ + '\x08{"tty":true,"cols":100,"rows":30}', + '\x04{"cols":120,"rows":30}', + ]) + ); + + socket.send(Buffer.from('\x03{"error":"exec failed"}')); + await expect(run).rejects.toThrow("exec failed"); + expect(setRawMode).toHaveBeenLastCalledWith(false); + expect(showCursor).toHaveBeenLastCalledWith(true); + expect(stdout.listenerCount("resize")).toBe(0); + }); + + it.for([ + { + name: "a command in a terminal", + terminal: [true, true], + args: { command: ["top"] }, + start: { command: ["top"], tty: true, cols: 80, rows: 24 }, + }, + { + name: "a shell with stdin redirected", + terminal: [false, true], + args: {}, + start: {}, + }, + { + name: "a shell with stdout redirected", + terminal: [true, false], + args: {}, + start: {}, + }, + { + name: "a shell with --no-tty", + terminal: [true, true], + args: { tty: false }, + start: {}, + }, + ])( + "uses a PTY only when stdin and stdout are terminals: $name", + async ({ terminal: [stdinTty, stdoutTty], args, start }, { expect }) => { + const { stdin } = streams(stdinTty, stdoutTty); + Object.assign(stdin, { setRawMode: vi.fn() }); + const ws = await server(); + const connected = connection(ws); + const run = sshCommand({ id: "instance", ...args }, "test-cli"); + const { socket, frames } = await connected; + await vi.waitFor(() => + expect(frames).toEqual([`\x08${JSON.stringify(start)}`]) + ); + socket.send(Buffer.from('\x03{"exit_code":0}')); + await expect(run).resolves.toBe(0); + } + ); + + it("reports HTTP errors from the shell endpoint", async ({ expect }) => { + streams(); + const body = JSON.stringify({ error: "SSH is disabled" }); + const http = createServer(); + http.on("upgrade", (_req, socket) => { + socket.end( + `HTTP/1.1 403 Forbidden\r\nContent-Type: application/json\r\nContent-Length: ${body.length}\r\n\r\n${body}` + ); + }); + http.listen(0, "127.0.0.1"); + await once(http, "listening"); + const address = http.address(); + if (typeof address === "string" || address === null) { + throw new Error("No address"); + } + vi.spyOn(DeploymentsService, "containerWranglerSsh").mockResolvedValue({ + url: `ws://127.0.0.1:${address.port}`, + token: "ssh-token", + }); + try { + await expect( + sshCommand({ id: "instance", command: ["true"] }, "test-cli") + ).rejects.toThrow( + "Shell connection failed with status 403: SSH is disabled" + ); + } finally { + http.close(); + } + }); + + it("pauses stdin until the Container takes it and keeps it paused after the session ends", async ({ + expect, + }) => { + const { stdin } = streams(); + const ws = await server(); + const connected = connection(ws); + const run = sshCommand( + { id: "instance", command: ["head", "-n1"] }, + "test-cli" + ); + const { socket, input, ackInput } = await connected; + for (let i = 0; i < 64; i++) { + stdin.write(Buffer.alloc(64 * 1024)); + } + // Stdin pauses once more than 512 KiB is not acknowledged. + const frame = 64 * 1024; + await vi.waitFor(() => expect(input.bytes).toBe(9 * frame)); + expect(stdin.isPaused()).toBe(true); + ackInput(); + await vi.waitFor(() => expect(input.bytes).toBe(18 * frame)); + expect(stdin.isPaused()).toBe(true); + + socket.send(Buffer.from('\x03{"exit_code":0}')); + await expect(run).resolves.toBe(0); + socket.terminate(); + await vi.waitFor(() => expect(stdin.listenerCount("data")).toBe(0)); + await new Promise((resolve) => setImmediate(resolve)); + expect(stdin.isPaused()).toBe(true); + }); + + it("acknowledges output once stdout has taken it", async ({ expect }) => { + const { stdout } = streams(); + const ws = await server(); + const connected = connection(ws); + const run = sshCommand({ id: "instance", command: ["cat"] }, "test-cli"); + const { socket, output, acks } = await connected; + output(1, Buffer.alloc(64 * 1024)); + output(1, Buffer.alloc(64 * 1024)); + // A PassThrough above its high-water mark holds the write callback until it is read. + await vi.waitFor(() => expect(stdout.readableLength).toBeGreaterThan(0)); + expect(acks).toEqual([]); + + stdout.resume(); + await vi.waitFor(() => expect(acks).toEqual([65536, 65536])); + socket.send(Buffer.from('\x03{"exit_code":0}')); + await expect(run).resolves.toBe(0); + }); + + it("does not show the spinner when stdout is not a terminal", async ({ + expect, + }) => { + streams(true, false); + const ws = await server(); + const connected = connection(ws); + const run = sshCommand({ id: "instance", command: ["true"] }, "test-cli"); + const { socket } = await connected; + socket.send(Buffer.from('\x03{"exit_code":0}')); + await expect(run).resolves.toBe(0); + expect(promiseSpinner).not.toHaveBeenCalled(); + }); + + it("ends the session with 141 when stdout is closed", async ({ expect }) => { + streams(); + const stdout = new Writable({ + write: (_chunk, _encoding, callback) => + callback(Object.assign(new Error("EPIPE"), { code: "EPIPE" })), + }); + stdout.on("error", () => {}); + Object.defineProperty(process, "stdout", { + value: stdout, + configurable: true, + }); + const ws = await server(); + const connected = connection(ws); + const run = sshCommand({ id: "instance", command: ["yes"] }, "test-cli"); + const { socket, output } = await connected; + const closed = once(socket, "close"); + output(1, "y\n"); + await expect(run).resolves.toBe(141); + await closed; + }); + + it("fails when the connection closes without an exit status", async ({ + expect, + }) => { + streams(); + const ws = await server(); + const connected = connection(ws); + const run = sshCommand({ id: "instance", command: ["true"] }, "test-cli"); + const { socket } = await connected; + socket.close(1011); + await expect(run).rejects.toThrow( + "Shell connection closed before the process exited" + ); + }); + + it("closes the connection on Ctrl-C before it opens and on a second Ctrl-C", async ({ + expect, + }) => { + const { stdin } = streams(); + const http = createServer(); + const upgrade = once(http, "upgrade"); + http.listen(0, "127.0.0.1"); + await once(http, "listening"); + const address = http.address(); + if (typeof address === "string" || address === null) { + throw new Error("No address"); + } + vi.spyOn(DeploymentsService, "containerWranglerSsh").mockResolvedValue({ + url: `ws://127.0.0.1:${address.port}`, + token: "ssh-token", + }); + try { + const hanging = sshCommand( + { id: "instance", command: ["true"] }, + "test-cli" + ); + const [, socket] = (await upgrade) as [unknown, Socket]; + const aborted = once(socket.resume(), "end"); + process.emit("SIGINT"); + await expect(hanging).resolves.toBe(130); + await aborted; + } finally { + http.closeAllConnections(); + http.close(); + } + + const ws = await server(); + const connected = connection(ws); + const run = sshCommand({ id: "instance", command: ["true"] }, "test-cli"); + const { socket, frames } = await connected; + stdin.write("x"); + const start = '\x08{"command":["true"]}'; + await vi.waitFor(() => expect(frames).toEqual([start, "\0x"])); + process.emit("SIGINT"); + await vi.waitFor(() => + expect(frames).toEqual([start, "\0x", '\x05{"signal":2}']) + ); + const closed = once(socket, "close"); + process.emit("SIGINT"); + await expect(run).resolves.toBe(130); + await closed; + }); +}); diff --git a/packages/wrangler/src/__tests__/containers/ssh.test.ts b/packages/wrangler/src/__tests__/containers/ssh.test.ts index 1e8c09ebd6c..51742d3abaf 100644 --- a/packages/wrangler/src/__tests__/containers/ssh.test.ts +++ b/packages/wrangler/src/__tests__/containers/ssh.test.ts @@ -51,6 +51,7 @@ describe("containers ssh", () => { beforeEach(mockAccount); afterEach(() => { + process.exitCode = undefined; msw.resetHandlers(); Object.defineProperty(process, "stdin", { value: originalStdin, @@ -84,8 +85,9 @@ describe("containers ssh", () => { -v, --version Show version number [boolean] OPTIONS - --stdio Proxy SSH traffic over stdin/stdout [boolean] - -t, --tty Force pseudo-terminal allocation, e.g. for interactive commands like \`-- bash\` [boolean]" + --stdio Proxy SSH traffic over stdin/stdout [boolean] + -t, --tty Allocate a pseudo-terminal. By default, one is allocated when stdin and stdout are terminals. With --legacy-openssh, the OpenSSH default applies [boolean] + --legacy-openssh Connect with OpenSSH and the container's authorized keys. Needed for port forwarding. This option will be removed in a future release [deprecated] [boolean]" `); }); @@ -157,13 +159,15 @@ describe("containers ssh", () => { }) ); - const wrangler = runWrangler(`containers ssh ${instanceId}`); + const wrangler = runWrangler( + `containers ssh ${instanceId} --legacy-openssh` + ); const expectedFailure = expect(wrangler).rejects.toMatchInlineSnapshot(` [Error: SSH exited unsuccessfully. Is the container running? NOTE: SSH does not automatically wake a container or count as activity to keep a container alive] `); - const socket = await server.connection; - socket.close(); + // The fake OpenSSH can fail before the WebSocket connects. + void server.connection.then((socket) => socket.close()); await expectedFailure; } finally { server.ws.close(); @@ -244,7 +248,9 @@ describe("containers ssh", () => { socket.on("message", (chunk) => resolve(chunk.toString())); }); }); - const wrangler = runWrangler(`containers ssh ${instanceId} -- 22`); + const wrangler = runWrangler( + `containers ssh ${instanceId} --legacy-openssh -- 22` + ); const socket = await server.connection; stdin.write("client-data"); @@ -259,6 +265,51 @@ describe("containers ssh", () => { server.ws.close(); expect(std.out).toBe(""); }); + + it("should run a command over the shell connection and exit with its code", async ({ + expect, + }) => { + const instanceId = "a".repeat(64); + const server = await createWsServer(); + const { stdout } = mockStdio({}); + + setWranglerConfig({}); + msw.use( + http.get(`*/instances/:instanceId/ssh`, async () => { + return HttpResponse.json( + { success: true, result: { url: server.url, token: "asd" } }, + { status: 200 } + ); + }) + ); + + const requestUrl = new Promise((resolve) => { + server.ws.on("connection", (_socket, request) => resolve(request.url)); + }); + const firstFrame = server.connection.then( + (socket) => + new Promise((resolve) => + socket.once("message", (data: Buffer) => resolve(data.toString())) + ) + ); + const stdoutData = new Promise((resolve) => { + stdout.on("data", (chunk: Buffer) => resolve(chunk.toString())); + }); + const wrangler = runWrangler( + `containers ssh ${instanceId} -- sh -c "exit 3"` + ); + + const socket = await server.connection; + expect(await requestUrl).toBe("/shell"); + expect(await firstFrame).toBe('\x08{"command":["sh","-c","exit 3"]}'); + socket.send(Buffer.from("\x01hi\n")); + await expect(stdoutData).resolves.toBe("hi\n"); + socket.send(Buffer.from('\x03{"exit_code":3}')); + await wrangler; + server.ws.close(); + expect(process.exitCode).toBe(3); + expect(std.out).toBe(""); + }); }); async function createWsServer() { diff --git a/packages/wrangler/src/containers/ssh.ts b/packages/wrangler/src/containers/ssh.ts index 38b174bd28f..67b2cec0b75 100644 --- a/packages/wrangler/src/containers/ssh.ts +++ b/packages/wrangler/src/containers/ssh.ts @@ -20,7 +20,9 @@ export const containersSshCommand = createCommand({ }, behaviour: { supportTemporary: true, - printBanner: (args) => !shouldUseStdio(args), + printBanner: (args) => + !shouldUseStdio({ ...args, command: args._.slice(2).map(String) }) && + process.stdout.isTTY === true, }, args: { ID: { @@ -37,7 +39,7 @@ export const containersSshCommand = createCommand({ logger, fetchResult, }); - await sshCommand( + const exitCode = await sshCommand( { ...args, id: args.ID, @@ -45,5 +47,8 @@ export const containersSshCommand = createCommand({ }, "wrangler" ); + if (exitCode !== undefined) { + process.exitCode = exitCode; + } }, });