Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/fly-guest-transport.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Fly guest command and file transport

`createFlyGuestTransport` in `packages/api/src/fly-guest-transport.ts` uses the documented `fly machine exec` and `fly sftp put/get` commands. It starts Fly CLI directly with an argument vector; guest command arguments and paths are never interpolated into a shell command. The Fly API token is supplied through the CLI's `FLY_API_TOKEN` environment variable and is not included in arguments, results, or transport errors.

The execution host must have a supported `fly` CLI installed and access to the selected Fly app and Machine. The token must authorize Machine execution and SFTP access. Machines must be running. The guest image must support Fly's Machine exec and SFTP paths; images do not need exe.dev's SSH tooling or systemd. `run()` accepts a nonempty executable and argv plus optional stdin bytes, returns captured stdout/stderr and the process exit code, and enforces a deadline of at most ten minutes and a combined output cap of at most 16 MiB. File operations enforce a configurable transfer cap of at most 64 MiB and use normalized absolute guest paths. Timed out operations terminate the CLI process group.

The local protocol fixtures verify process result handling, timeout, output overflow, disconnect, safe argv construction, and file byte transfer. They do not validate live Fly authentication, Fly CLI compatibility, routing to a real Machine, or the guest's exec/SFTP capabilities. A separate opt-in validation requires a Fly account, an authorized app/Machine and token, an installed Fly CLI, and a custom image with Fly exec/SFTP support; no Fly network call is part of the required test suite.
126 changes: 126 additions & 0 deletions packages/api/src/fly-guest-transport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawn } from "node:child_process";

export type FlyGuestErrorKind = "timeout" | "output_limit" | "disconnect" | "transport" | "file_limit";

/** Sanitized transport errors never include CLI output, command arguments, or credentials. */
export class FlyGuestError extends Error {
constructor(readonly kind: FlyGuestErrorKind) {
super(`Fly guest transport ${kind.replace("_", " ")}`);
this.name = "FlyGuestError";
}
}

export type FlyGuestCommandResult = { ok: boolean; exitCode: number; stdout: string; stderr: string };
export type FlyGuestTransportOptions = {
app: string;
machine: string;
token: string;
cliPath?: string;
timeoutMs?: number;
outputLimitBytes?: number;
fileLimitBytes?: number;
/** Subprocess injection is used by deterministic local protocol fixtures. */
spawnProcess?: typeof spawn;
};

function pathSegment(value: string, name: string): string {
if (!value || value === "." || value === ".." || /[\0/\r\n]/.test(value)) throw new TypeError(`${name} must be a path segment`);
return value;
}

function guestPath(value: string): string {
if (!value.startsWith("/") || value.includes("\0") || value.includes("\r") || value.includes("\n") || value.split("/").some(part => part === "." || part === "..")) {
throw new TypeError("Guest file path must be absolute and normalized");
}
return value;
}

export function createFlyGuestTransport(options: FlyGuestTransportOptions) {
pathSegment(options.app, "app");
pathSegment(options.machine, "machine");
if (!options.token) throw new TypeError("Fly token is required");
const timeoutMs = options.timeoutMs ?? 30_000;
const outputLimitBytes = options.outputLimitBytes ?? 1024 * 1024;
const fileLimitBytes = options.fileLimitBytes ?? 16 * 1024 * 1024;
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 10 * 60_000) throw new TypeError("timeoutMs must be between 1ms and 10 minutes");
if (!Number.isSafeInteger(outputLimitBytes) || outputLimitBytes < 1 || outputLimitBytes > 16 * 1024 * 1024 || !Number.isSafeInteger(fileLimitBytes) || fileLimitBytes < 1 || fileLimitBytes > 64 * 1024 * 1024) throw new TypeError("transport limits exceed the supported bounds");
const spawnProcess = options.spawnProcess ?? spawn;
const base = ["--app", options.app, "--machine", options.machine];

async function invoke(args: string[], limit = outputLimitBytes, input?: string | Uint8Array): Promise<FlyGuestCommandResult> {
return new Promise((resolve, reject) => {
let stdout = Buffer.alloc(0), stderr = Buffer.alloc(0), settled = false, exceeded = false;
const child = spawnProcess(options.cliPath ?? "fly", args, { env: { ...process.env, FLY_API_TOKEN: options.token }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, detached: process.platform !== "win32" });
const killTree = () => {
try {
if (child.pid && process.platform !== "win32") process.kill(-child.pid, "SIGKILL");
else child.kill("SIGKILL");
} catch { child.kill("SIGKILL"); }
};
const finishError = (error: FlyGuestError) => {
if (settled) return;
settled = true;
clearTimeout(deadline);
killTree();
reject(error);
};
const collect = (current: Buffer, chunk: Buffer): Buffer => {
const remaining = limit - stdout.byteLength - stderr.byteLength;
if (chunk.byteLength > remaining) {
exceeded = true;
return Buffer.concat([current, chunk.subarray(0, Math.max(0, remaining))]);
}
return Buffer.concat([current, chunk]);
};
child.stdout.on("data", (chunk: Buffer) => { stdout = collect(stdout, chunk); if (exceeded) finishError(new FlyGuestError("output_limit")); });
child.stderr.on("data", (chunk: Buffer) => { stderr = collect(stderr, chunk); if (exceeded) finishError(new FlyGuestError("output_limit")); });
child.on("error", () => finishError(new FlyGuestError("transport")));
const deadline = setTimeout(() => finishError(new FlyGuestError("timeout")), timeoutMs);
child.stdin.end(input);
child.on("close", (code: number | null) => {
if (settled) return;
settled = true;
clearTimeout(deadline);
if (code === null) return reject(new FlyGuestError("disconnect"));
resolve({ ok: code === 0, exitCode: code, stdout: stdout.toString("utf8"), stderr: stderr.toString("utf8") });
});
});
}

return {
/** Arguments are passed as an argv vector after `--`; no shell parses guest input. */
run(command: readonly string[], input?: string | Uint8Array): Promise<FlyGuestCommandResult> {
if (!command.length || command.some(arg => typeof arg !== "string" || arg.includes("\0"))) throw new TypeError("Guest command must contain valid arguments");
return invoke(["machine", "exec", options.machine, "--app", options.app, "--no-container", "--timeout", String(Math.max(1, Math.ceil(timeoutMs / 1000))), "--", ...command], outputLimitBytes, input);
},
async upload(remotePath: string, bytes: Uint8Array): Promise<void> {
remotePath = guestPath(remotePath);
if (bytes.byteLength > fileLimitBytes) throw new FlyGuestError("file_limit");
const directory = await mkdtemp(join(tmpdir(), "factorize-fly-upload-"));
const localPath = join(directory, "payload");
try {
await writeFile(localPath, bytes, { mode: 0o600 });
const result = await invoke(["sftp", "put", localPath, remotePath, ...base, "--no-container", "--user", "root"], 64 * 1024);
if (!result.ok) throw new FlyGuestError("transport");
} finally { await rm(directory, { recursive: true, force: true }); }
},
async download(remotePath: string): Promise<Uint8Array> {
remotePath = guestPath(remotePath);
const directory = await mkdtemp(join(tmpdir(), "factorize-fly-download-"));
const localPath = join(directory, "payload");
try {
const result = await invoke(["sftp", "get", remotePath, localPath, ...base, "--no-container", "--user", "root"], 64 * 1024);
if (!result.ok) throw new FlyGuestError("transport");
const size = (await stat(localPath)).size;
if (size > fileLimitBytes) throw new FlyGuestError("file_limit");
return new Uint8Array(await readFile(localPath));
} catch (error) {
if (error instanceof FlyGuestError) throw error;
throw new FlyGuestError("transport");
} finally { await rm(directory, { recursive: true, force: true }); }
},
};
}
81 changes: 81 additions & 0 deletions packages/api/test/fly-guest-transport.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import { readFile, writeFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { createFlyGuestTransport, FlyGuestError } from "../src/fly-guest-transport.js";

function fixture(handler: (args: string[]) => Promise<{ code: number | null; stdout?: string; stderr?: string }>) {
const calls: { executable: string; args: string[]; env: NodeJS.ProcessEnv; stdin: Buffer }[] = [];
const spawnProcess = ((executable: string, args: string[], options: any) => {
const call = { executable, args: [...args], env: options.env, stdin: Buffer.alloc(0) };
calls.push(call);
const child = new EventEmitter() as any;
child.stdout = new PassThrough(); child.stderr = new PassThrough(); child.stdin = new PassThrough();
child.stdin.on("data", (chunk: Buffer) => { call.stdin = Buffer.concat([call.stdin, chunk]); });
child.kill = () => { queueMicrotask(() => child.emit("close", null)); return true; };
void handler(args).then(result => {
if (result.stdout) child.stdout.write(result.stdout);
if (result.stderr) child.stderr.write(result.stderr);
queueMicrotask(() => child.emit("close", result.code));
});
return child;
}) as any;
return { calls, spawnProcess };
}

const base = { app: "fixture-app", machine: "machine-1", token: "redacted-test-token", timeoutMs: 1000, outputLimitBytes: 128, fileLimitBytes: 1024 };

describe("Fly guest command and file transport", () => {
it("passes arguments literally and returns a nonzero process exit", async () => {
const f = fixture(async () => ({ code: 17, stdout: "guest output", stderr: "guest error" }));
const transport = createFlyGuestTransport({ ...base, spawnProcess: f.spawnProcess });
const result = await transport.run(["printf", "%s", "$(touch /tmp/not-run); ' quote"], "prompt bytes");
expect(result).toEqual({ ok: false, exitCode: 17, stdout: "guest output", stderr: "guest error" });
expect(f.calls[0].args).toEqual(["machine", "exec", "machine-1", "--app", "fixture-app", "--no-container", "--timeout", "1", "--", "printf", "%s", "$(touch /tmp/not-run); ' quote"]);
expect(f.calls[0].env.FLY_API_TOKEN).toBe(base.token);
expect(f.calls[0].stdin.toString()).toBe("prompt bytes");
});

it("bounds the operation deadline and captured output", async () => {
const hanging = fixture(() => new Promise(() => undefined));
const transport = createFlyGuestTransport({ ...base, timeoutMs: 15, spawnProcess: hanging.spawnProcess });
await expect(transport.run(["sleep", "forever"])).rejects.toMatchObject({ kind: "timeout" });

const noisy = fixture(async () => ({ code: 0, stdout: "x".repeat(129) }));
await expect(createFlyGuestTransport({ ...base, spawnProcess: noisy.spawnProcess }).run(["emit"])).rejects.toMatchObject({ kind: "output_limit" });
});

it("reports a disconnected guest transport distinctly", async () => {
const f = fixture(async () => ({ code: null }));
await expect(createFlyGuestTransport({ ...base, spawnProcess: f.spawnProcess }).run(["true"])).rejects.toMatchObject({ kind: "disconnect" });
});

it("uploads and downloads bytes through SFTP argv without shell interpolation", async () => {
let uploaded = new Uint8Array();
const downloaded = Buffer.from([0, 1, 2, 255]);
const f = fixture(async args => {
const mode = args[1];
if (mode === "put") uploaded = new Uint8Array(await readFile(args[2]));
if (mode === "get") await writeFile(args[3], downloaded);
return { code: 0 };
});
const transport = createFlyGuestTransport({ ...base, spawnProcess: f.spawnProcess });
await transport.upload("/tmp/file;$(id)", new Uint8Array([3, 4, 5]));
expect([...uploaded]).toEqual([3, 4, 5]);
expect(f.calls[0].args.slice(0, 2)).toEqual(["sftp", "put"]);
expect(f.calls[0].args[3]).toBe("/tmp/file;$(id)");
expect([...await transport.download("/tmp/result")]).toEqual([0, 1, 2, 255]);
expect(f.calls[1].args.slice(0, 3)).toEqual(["sftp", "get", "/tmp/result"]);
});

it("rejects unsafe guest paths and oversized transfers", async () => {
const f = fixture(async () => ({ code: 0 }));
const transport = createFlyGuestTransport({ ...base, spawnProcess: f.spawnProcess });
await expect(transport.download("/tmp/../secret")).rejects.toThrow();
await expect(transport.upload("relative", new Uint8Array())).rejects.toThrow();
await expect(transport.upload("/tmp/large", new Uint8Array(1025))).rejects.toMatchObject({ kind: "file_limit" } satisfies Partial<FlyGuestError>);
expect(f.calls).toHaveLength(0);
expect(() => createFlyGuestTransport({ ...base, timeoutMs: 10 * 60_000 + 1 })).toThrow(/10 minutes/);
expect(() => createFlyGuestTransport({ ...base, outputLimitBytes: 16 * 1024 * 1024 + 1 })).toThrow(/supported bounds/);
});
});
Loading