Repository navigation
[wrangler] Open Container shells without SSH keys #17304
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 <ID>` 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 <ID> -- ls /` | ||
|
|
||
| Wrangler runs the command directly, not through a remote shell. To use shell syntax, run `sh -c`: | ||
|
|
||
| `wrangler containers ssh <ID> -- 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`. | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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`. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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(); | ||
| } | ||
| ); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<void>; | ||
| /** Resolves with the remote exit code. */ | ||
| exited: Promise<number>; | ||
| 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, | ||
| }, | ||
| }); | ||
|
Comment on lines
+69
to
+74
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔍 Deployed shell handshake remains unverified The shell fixture checks the request against a local WebSocket server. It does not verify that a production token works at Was this helpful? React with 👍 or 👎 to provide feedback.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I tested this against production: shells, commands, exit codes, PTY, resize and Ctrl-C all work against the live |
||
|
|
||
| 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<void>((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<number>((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); | ||
| } | ||
| }); | ||
| }; | ||
|
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
|
||
| 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; | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔍 Redirected command docs omit OpenSSH exception
With both streams redirected, shouldUseStdio still selects proxy mode for
-ior--legacy-opensshunless--ttyis set. The changeset says a command after--runs in the Container even with both streams redirected.Was this helpful? React with 👍 or 👎 to provide feedback.