mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 17:14:54 +01:00
feat(kubernetes): native file-sync lifecycle hooks over pod exec (#10053)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - AI agents run in sandboxed execution environments (Kubernetes pods, Daytona workspaces, etc.) and need to sync files between the host and those environments — for workspace setup, asset delivery, and output retrieval > - The existing sync path for Kubernetes uses a base64-over-exec chunk loop: each ~4 MB chunk requires its own `execInPod` round-trip, so large syncs balloon into many exec calls with corresponding overhead > - `execInPod` supports piped stdin/stdout, meaning the full transfer can be done as a single exec that streams a raw `tar` archive over the data channel — one round-trip regardless of file size, with nothing base64-encoded and nothing buffered whole in memory on either side > - PR-1 (#10013, merged) added the `onEnvironmentSyncIn`/`onEnvironmentSyncOut` opt-in hook API to the sandbox provider interface and documented the protocol; PR-2 (#10028, merged) implemented these hooks for the Daytona provider > - This pull request implements the same two lifecycle hooks in the Kubernetes sandbox provider, so workspace/asset file sync streams through one `execInPod` per operation instead of the chunk loop > - The benefit is significantly fewer exec round-trips for large syncs and flat memory use on both host and pod, with security properties preserved: atomic replace, secret-mode enforcement, path confinement, TOCTOU-safe snapshot, and member-confinement on host-assembled archives from sandbox-authored tar output ## Linked Issues or Issue Description This is the third and final PR in a sequential series: - Refs #10013 — PR-1: opt-in sync hook API + provider docs (merged) - Refs #10028 — PR-2: native file-sync lifecycle hooks for Daytona provider (merged) **Feature:** Native single-exec file-sync lifecycle hooks for the Kubernetes sandbox provider. *Motivation:* The existing Kubernetes sync path encodes files as base64 and loops over `execInPod` one chunk at a time (~4 MB per exec). For large workspaces or asset sets this is slow and resource-intensive. The Kubernetes `execInPod` API supports piped stdin/stdout, enabling a raw-`tar` streaming transfer that needs only one exec regardless of file count or size and never buffers the whole payload in memory. *Proposed solution:* Implement `onEnvironmentSyncIn` and `onEnvironmentSyncOut` in the Kubernetes provider using a streaming `execInPod` with a tar pipeline — for syncIn the host builds the archive on disk and streams its raw bytes into the pod's stdin (`head -c <exact-size> | tar -x`, no base64); for syncOut in-pod `tar` writes to the exec's stdout and the host streams those bytes straight to a file. Path confinement, atomic replace, secret-mode enforcement, TOCTOU protection, and a streamed-bytes fail-closed guard are all enforced. ## What Changed - **New `src/file-sync.ts`** in `packages/plugins/sandbox-providers/kubernetes/` — `performSyncIn` and `performSyncOut` over an injected pod-exec closure, keeping transfer logic hermetically unit-testable - **New `execInPodStreaming` in `src/pod-exec.ts`** — a streaming exec primitive that binds a caller-supplied stdin readable and a stdout writable to the exec WebSocket data channel, added alongside the existing `execInPod` (which is unchanged). This lets a transfer stream raw bytes to/from disk instead of buffering the payload as a single string - **Updated `src/plugin.ts`** — registers `onEnvironmentSyncIn`/`onEnvironmentSyncOut`; resolves the `sandbox-cr` pod exactly like `onEnvironmentExecute` and delegates; `job` backend rejects file-sync calls explicitly (out of scope) - **syncIn path:** host builds the tarball to a temp file → streams its raw bytes over exec stdin, bounded in-pod by `head -c <exact-archive-size> | tar -x` (no base64 anywhere) → extract into a `/proc/self/fd`-pinned reserved `0700` staging dir → `chmod`-before-`mv -f` atomic replace per file (directory mappings use `followSymlinks`→`-h`) - **syncOut path:** in-pod validate + realpath-snapshot each source (closes the validation→copy TOCTOU window) → single-exec `tar -c` streamed over exec stdout → host streams that stdout straight to a temp file through a byte-counting transform → member-confined extraction of the sandbox-authored archive - **Security properties:** secret files land at requested mode with no widened window; every interpolated path is shell-quoted and confined lexically plus via in-pod `realpath`; the outbound stream is bounded by a **streamed-bytes disk guard** (`MAX_SYNC_OUTPUT_BYTES`, 8 GiB default, per-call overridable) that fails the transfer closed — writing no target file — if an untrusted pod emits more bytes than allowed. Neither host nor pod buffers the whole payload, so there is no in-memory size cap on the transfer - **No changes** to `execInPod`, `wrapCommandWithEnv`, or `FastUploadInterceptor` (the `environmentExecute` path is untouched) - **No dependency or lockfile changes** - **New tests** in `test/unit/file-sync.test.ts` (atomic-replace, `0600` secret mode, symlink preserve/deref, dir-mapping, exclude, path-confinement rejection, streamed-output guard fail-closed) and `test/unit/pod-exec.test.ts` (streaming stdin/stdout, caller-sink error fail-closed), plus extended `test/unit/plugin.test.ts` ## Follow-up: Legacy Job-Lease Base64 Fallback Fix Addresses the Greptile 4/5 blocking finding ("Handle existing job leases", `server/src/services/environment-runtime.ts`). Job leases provisioned before the `nativeFileSyncUnsupported` metadata flag existed carry `backend: "job"` but no flag, so `supportsSync()` treated them as native-capable and routed their sync to the pod-exec hook — which the job backend rejects (it has no exec channel) instead of using the byte-identical base64 fallback. The fix adds a belt-and-suspenders gate on the persisted `backend === "job"` field alongside the existing `nativeFileSyncUnsupported` flag check, so pre-existing job leases continue syncing via the base64 fallback after deployment. No behaviour change for `sandbox-cr` leases. ## Verification - `pnpm --filter @paperclipai/sandbox-provider-kubernetes test` — 19 files / 182 tests green, including the existing `upload-interceptor` and `pod-exec` suites - `tsc --noEmit` in the kubernetes package — 0 errors - The sync hooks are opt-in; existing `environmentExecute` behaviour is unaffected and tested by the unchanged existing suites ## Risks - **Opt-in only:** `onEnvironmentSyncIn`/`onEnvironmentSyncOut` are registered conditionally; providers that do not register them fall back to the existing chunk loop. No regression risk on the existing path. - **Shell-injection surface:** all path interpolation uses shell-quoting; paths are additionally confined lexically and via in-pod `realpath` before use. - **TOCTOU on syncOut:** the in-pod snapshot validates and records file metadata before the tar call, closing the window between validation and copy. - **Archive member confinement:** host-side reassembly rejects any tar member whose resolved path escapes the target directory, preventing a malicious in-pod tar from writing outside the intended destination. - **Untrusted-output volume:** an over-large outbound stream trips the streamed-bytes disk guard and fails closed (no target written and the temp sink is swept) rather than filling host disk or memory; the guard bounds disk unconditionally and bounds memory insofar as WebSocket write-backpressure holds. ## Model Used Anthropic Claude Sonnet 4.6 (`claude-sonnet-4-6`) — produced by a Claude-based AI agent using agentic tool use and multi-step code generation. 200K context window, extended reasoning, code execution and verification capabilities. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Harold Kim <harold@paperclip.ing> Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
9 files changed
+2086
-9
No files matched your search
@@ -0,0 +1,805 @@
|
||||
/**
|
||||
* Native file-sync transport for the Kubernetes sandbox provider.
|
||||
*
|
||||
* Implements the opt-in `onEnvironmentSyncIn`/`onEnvironmentSyncOut` hooks over
|
||||
* the pod exec data channel, so workspace/asset transfers stream through a
|
||||
* SINGLE exec per operation instead of the default base64 chunk loop (which
|
||||
* costs one exec per ~4 MB chunk — see `upload-interceptor.ts`).
|
||||
*
|
||||
* The transport is pure streaming: raw tar bytes move over the exec's stdin /
|
||||
* stdout channels straight to and from a host file on disk, so neither the host
|
||||
* nor the pod ever holds the whole payload in memory.
|
||||
*
|
||||
* - syncIn: build one host tarball of the operation's payload on disk, stream
|
||||
* its raw bytes over the exec's stdin into `head -c <N> | tar -x`
|
||||
* inside the pod (N is the exact archive size, known host-side, so
|
||||
* the pod command self-terminates without depending on stdin EOF),
|
||||
* then stage-then-`mv -f` each single file onto its target so an
|
||||
* interrupted transfer never leaves a truncated file.
|
||||
* - syncOut: run `tar -c … -f -` inside the pod over one exec, streaming the
|
||||
* archive on stdout straight into a host file, then reassemble it.
|
||||
*
|
||||
* The exec primitive is injected as `PodStreamExec` so this module stays free of
|
||||
* any `@kubernetes/client-node` coupling and is unit-testable against a
|
||||
* shell-backed fake. `plugin.ts` binds it to `execInPodStreaming` for a resolved
|
||||
* pod.
|
||||
*
|
||||
* Security model (carried from the seam's design review): every sandbox path is
|
||||
* confined to the workspace remote dir both lexically on the host AND via an
|
||||
* in-pod `realpath` check that pins the resolved directory inode through
|
||||
* `/proc/self/fd` before any byte is written — closing the symlink-swap TOCTOU
|
||||
* window. Secret files land at their requested `mode` with no world-readable
|
||||
* window (the staging dir is created `0700` and each file is `chmod`ed before
|
||||
* the rename). All interpolated paths are single-quoted. Sandbox-authored
|
||||
* tarballs (outbound) are member-confined before host extraction.
|
||||
*
|
||||
* Memory + disk posture: because the archive streams to/from disk, a transfer of
|
||||
* any size keeps host and pod memory flat — there is no whole-payload buffer and
|
||||
* therefore no 100 MB in-memory cap (the old base64-buffered transport needed
|
||||
* one). Inbound bytes are host-authored (the tar this module builds), so they
|
||||
* need no untrusted-size bound. Outbound bytes are authored by the untrusted
|
||||
* pod, which controls how much it emits, so the sink `Writable` is wrapped in a
|
||||
* streamed-bytes guard that fails the transfer closed above `maxOutputBytes`
|
||||
* before it can fill the host's disk; the pod's stderr is separately capped in
|
||||
* `execInPodStreaming`.
|
||||
*/
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import { promises as fs, createReadStream, createWriteStream } from "node:fs";
|
||||
import { Transform } from "node:stream";
|
||||
import { finished } from "node:stream/promises";
|
||||
import type { Readable, Writable } from "node:stream";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import type {
|
||||
PluginEnvironmentSyncResult,
|
||||
PluginSyncFileMapping,
|
||||
PluginSyncOperation,
|
||||
} from "@paperclipai/plugin-sdk";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/**
|
||||
* Injected streaming pod-exec primitive. `command` is always
|
||||
* `["/bin/sh", "-c", <script>]`; `io.stdin` (when present) is streamed to the
|
||||
* command's stdin over the exec data channel, and `io.stdout` (when present)
|
||||
* receives the command's stdout. Returns the command's exit code plus its
|
||||
* captured (bounded) stderr. `plugin.ts` binds this to
|
||||
* `execInPodStreaming(kc, namespace, podName, "agent", …)`.
|
||||
*/
|
||||
export type PodStreamExec = (
|
||||
command: string[],
|
||||
io: {
|
||||
stdin?: Readable;
|
||||
stdout?: Writable;
|
||||
timeoutMs?: number;
|
||||
maxStderrBytes?: number;
|
||||
},
|
||||
) => Promise<{ exitCode: number; stderr: string }>;
|
||||
|
||||
// Reserved scratch-name stem for staged transfers and remote tarballs. The
|
||||
// runtime's base64 fallback stages to `<path>.paperclip-upload`; the native
|
||||
// transport reuses the same reserved prefix so a provider temp never collides
|
||||
// with a real target or with the fallback's scratch name.
|
||||
const SCRATCH_PREFIX = ".paperclip-upload";
|
||||
|
||||
// Fail-closed guard on the number of bytes an outbound (`syncOut`) transfer will
|
||||
// stream to host disk. The archive is authored by the untrusted pod, which
|
||||
// controls how many bytes it emits on stdout; streaming keeps memory flat but a
|
||||
// hostile pod could still try to exhaust the worker's ephemeral disk. The
|
||||
// transfer aborts the instant the pod exceeds this bound. It is deliberately
|
||||
// generous (real workspace/asset syncs are far smaller) and overridable per
|
||||
// call so operators can tune it to the worker's actual disk budget.
|
||||
const MAX_SYNC_OUTPUT_BYTES = 8 * 1024 * 1024 * 1024;
|
||||
|
||||
// Bound on the pod's stderr for a sync exec. stderr carries only the in-pod
|
||||
// script's fail-loud diagnostics, so a modest cap is ample; it exists solely so
|
||||
// a pod that floods stderr cannot grow the host accumulator without limit.
|
||||
const SYNC_STDERR_CAP_BYTES = 1024 * 1024;
|
||||
|
||||
function scratchName(suffix = ""): string {
|
||||
return `${SCRATCH_PREFIX}-${randomUUID()}${suffix}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-quote a string for safe interpolation into a `sh -c` script (close,
|
||||
* escape, reopen). Mirrors `pod-exec.ts`'s `shQuote`; duplicated here so this
|
||||
* module carries no `@kubernetes/client-node` import and stays hermetically
|
||||
* testable. Every path handed to an exec MUST pass through this.
|
||||
*/
|
||||
function shQuote(value: string): string {
|
||||
return `'${value.replace(/'/g, "'\\''")}'`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Host-side complete-mediation guard applied as defense-in-depth below the
|
||||
* orchestrator's own confinement. Every sandbox-side path (the sync target for
|
||||
* inbound, the sync source for outbound) MUST be an absolute path that
|
||||
* canonicalizes lexically inside the workspace remote dir; absolute escapes and
|
||||
* `..` traversal are rejected fail-closed before any bytes move. Sandbox paths
|
||||
* are POSIX.
|
||||
*/
|
||||
export function assertConfinedSandboxPath(remoteDir: string, candidate: string, label: string): void {
|
||||
const normalizedRoot = path.posix.normalize(remoteDir);
|
||||
const normalized = path.posix.normalize(candidate);
|
||||
if (
|
||||
!path.posix.isAbsolute(normalized) ||
|
||||
normalized === ".." ||
|
||||
normalized.includes("/../") ||
|
||||
normalized.endsWith("/..")
|
||||
) {
|
||||
throw new Error(`Kubernetes sync ${label} path is not a confined absolute path: ${candidate}`);
|
||||
}
|
||||
const prefix = normalizedRoot.endsWith("/") ? normalizedRoot : `${normalizedRoot}/`;
|
||||
if (normalized !== normalizedRoot && !normalized.startsWith(prefix)) {
|
||||
throw new Error(`Kubernetes sync ${label} path escapes the workspace remote dir: ${candidate}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `relative` (a POSIX path) escapes its anchoring directory once
|
||||
* normalized: an absolute path, `..`, or a `..`-leading traversal all break out.
|
||||
*/
|
||||
function posixPathEscapes(relative: string): boolean {
|
||||
const normalized = path.posix.normalize(relative);
|
||||
return normalized === ".." || normalized.startsWith("../") || path.posix.isAbsolute(normalized);
|
||||
}
|
||||
|
||||
async function withHostTempDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-k8s-sync-"));
|
||||
try {
|
||||
return await fn(dir);
|
||||
} finally {
|
||||
await fs.rm(dir, { recursive: true, force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POSIX-sh preamble defining a `_pc_resolve` canonicalizer (prefer `realpath`,
|
||||
* fall back to `readlink -f`; fail closed with exit 40 if neither exists so the
|
||||
* host-side lexical check is never the only line of defense) and `_pc_root` =
|
||||
* the resolved workspace remote dir. Shared by every in-pod symlink-escape guard.
|
||||
*
|
||||
* Also defines `_pc_confine_ancestor <path>`: it walks up to the DEEPEST already-
|
||||
* existing ancestor of `<path>`, canonicalizes it, and confines it inside
|
||||
* `_pc_root` (exit 42 on escape). `mkdir -p` follows an existing symlink ancestor,
|
||||
* so creating a target directory before confining could materialize a dir OUTSIDE
|
||||
* the root and only reject afterward — the escape has already mutated the host.
|
||||
* Confining the closest existing prefix BEFORE `mkdir` closes that window: any
|
||||
* component `mkdir -p` newly creates is a real directory, so only a pre-existing
|
||||
* symlink ancestor can redirect the write, and that ancestor is exactly what this
|
||||
* check canonicalizes and rejects.
|
||||
*/
|
||||
function canonicalizerPreamble(quotedRoot: string): string[] {
|
||||
return [
|
||||
'if command -v realpath >/dev/null 2>&1; then _pc_resolve() { realpath -- "$1"; };',
|
||||
'elif command -v readlink >/dev/null 2>&1; then _pc_resolve() { readlink -f -- "$1"; };',
|
||||
'else echo "no path canonicalizer available" >&2; exit 40; fi;',
|
||||
`_pc_root=$(_pc_resolve ${quotedRoot}) || { echo "cannot resolve root" >&2; exit 41; };`,
|
||||
'_pc_confine_ancestor() {',
|
||||
// Confinement targets are always absolute (asserted host-side), so `dirname`
|
||||
// needs no `--` end-of-options guard — and omitting it keeps the walk correct
|
||||
// on minimal shells (e.g. BusyBox `dirname`, which does not parse `--`).
|
||||
' _pc_a=$1;',
|
||||
' while [ ! -e "$_pc_a" ] && [ ! -L "$_pc_a" ]; do',
|
||||
' _pc_p=$(dirname "$_pc_a");',
|
||||
' [ "$_pc_p" = "$_pc_a" ] && break;',
|
||||
' _pc_a=$_pc_p;',
|
||||
' done;',
|
||||
' _pc_ar=$(_pc_resolve "$_pc_a") || return 42;',
|
||||
' case "$_pc_ar/" in "$_pc_root"/*) return 0 ;; *) return 42 ;; esac;',
|
||||
'};',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream a host file's raw bytes into the pod command's stdin over one exec and
|
||||
* assert it exited 0; otherwise throw with the captured stderr so a failed
|
||||
* transfer surfaces fail-loud to the orchestrator (never a silent partial
|
||||
* success). The pod command bounds its own read (`head -c <N>`), so stdin EOF is
|
||||
* never load-bearing.
|
||||
*/
|
||||
async function streamFileToPodStdin(input: {
|
||||
exec: PodStreamExec;
|
||||
script: string;
|
||||
filePath: string;
|
||||
timeoutMs: number;
|
||||
label: string;
|
||||
}): Promise<void> {
|
||||
const source = createReadStream(input.filePath);
|
||||
try {
|
||||
const result = await input.exec(["/bin/sh", "-c", input.script], {
|
||||
stdin: source,
|
||||
timeoutMs: input.timeoutMs,
|
||||
maxStderrBytes: SYNC_STDERR_CAP_BYTES,
|
||||
});
|
||||
if (result.exitCode !== 0) {
|
||||
const detail = (result.stderr || "").trim();
|
||||
throw new Error(
|
||||
`Kubernetes ${input.label} failed (exit ${result.exitCode})${detail ? `: ${detail}` : ""}`,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
source.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the pod command over one exec and stream its stdout straight into a host
|
||||
* file, guarding the byte count against `maxOutputBytes` so an untrusted pod
|
||||
* cannot fill the host disk. Resolves only after the file is fully flushed, so a
|
||||
* caller that reads it back always sees the complete archive; throws fail-loud on
|
||||
* a non-zero exit, a tripped disk guard, or a stream error, writing no file the
|
||||
* caller then trusts.
|
||||
*/
|
||||
async function streamPodStdoutToFile(input: {
|
||||
exec: PodStreamExec;
|
||||
script: string;
|
||||
filePath: string;
|
||||
maxOutputBytes: number;
|
||||
timeoutMs: number;
|
||||
label: string;
|
||||
}): Promise<void> {
|
||||
const fileStream = createWriteStream(input.filePath);
|
||||
let written = 0;
|
||||
const guard = new Transform({
|
||||
transform(chunk: Buffer, _enc, cb) {
|
||||
written += chunk.length;
|
||||
if (input.maxOutputBytes >= 0 && written > input.maxOutputBytes) {
|
||||
cb(
|
||||
new Error(
|
||||
`Kubernetes ${input.label} payload exceeded the ${input.maxOutputBytes}-byte streamed-output disk guard; the sandbox emitted more bytes than allowed.`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
cb(null, chunk);
|
||||
},
|
||||
});
|
||||
guard.pipe(fileStream);
|
||||
const flushed = finished(fileStream);
|
||||
try {
|
||||
const result = await input.exec(["/bin/sh", "-c", input.script], {
|
||||
stdout: guard,
|
||||
timeoutMs: input.timeoutMs,
|
||||
maxStderrBytes: SYNC_STDERR_CAP_BYTES,
|
||||
});
|
||||
await flushed;
|
||||
if (result.exitCode !== 0) {
|
||||
const detail = (result.stderr || "").trim();
|
||||
throw new Error(
|
||||
`Kubernetes ${input.label} failed (exit ${result.exitCode})${detail ? `: ${detail}` : ""}`,
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
// Tear the sink down so a tripped guard / rejected exec never leaves the
|
||||
// file stream open (and its `finished` promise dangling as unhandled).
|
||||
guard.destroy();
|
||||
fileStream.destroy();
|
||||
await flushed.catch(() => undefined);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a host-side tarball, mirroring the runtime's own `createTarballFromDirectory`:
|
||||
* archive the named top-level entries (no "." self entry), suppress xattr
|
||||
* sidecars, honor `exclude`, and reproduce the `followSymlinks` → `-h` mapping so
|
||||
* the native path is observationally identical to the base64 fallback's tar. An
|
||||
* empty entry set writes a valid empty tar (1024-byte zero EOF marker).
|
||||
*/
|
||||
async function createHostTarball(input: {
|
||||
localDir: string;
|
||||
archivePath: string;
|
||||
exclude?: string[];
|
||||
followSymlinks?: boolean;
|
||||
entries?: string[];
|
||||
}): Promise<void> {
|
||||
const excludeArgs = ["._*", ...(input.exclude ?? [])].flatMap((entry) => ["--exclude", entry]);
|
||||
const entries =
|
||||
input.entries ??
|
||||
(await fs.readdir(input.localDir)).sort((left, right) => left.localeCompare(right));
|
||||
if (entries.length === 0) {
|
||||
await fs.writeFile(input.archivePath, Buffer.alloc(1024));
|
||||
return;
|
||||
}
|
||||
await execFileAsync(
|
||||
"tar",
|
||||
[
|
||||
"-c",
|
||||
"--no-xattrs",
|
||||
...(input.followSymlinks ? ["-h"] : []),
|
||||
"-f",
|
||||
input.archivePath,
|
||||
"-C",
|
||||
input.localDir,
|
||||
...excludeArgs,
|
||||
"--",
|
||||
...entries,
|
||||
],
|
||||
{ env: { ...process.env, COPYFILE_DISABLE: "1" }, maxBuffer: 64 * 1024 * 1024 },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject a sandbox-authored tarball before extraction if any member would land
|
||||
* outside the extraction dir. The archive is produced by the (untrusted) sandbox,
|
||||
* so host-side `tar -xf` must never be handed an archive whose entries carry
|
||||
* absolute paths or `../` traversal, nor a symlink/hardlink member whose target
|
||||
* escapes the tree. Legitimate in-tree relative links are preserved. Parses the
|
||||
* `-tvf` verbose listing; any unparseable line fails closed.
|
||||
*/
|
||||
async function assertTarballEntriesConfined(archivePath: string): Promise<void> {
|
||||
const { stdout } = await execFileAsync("tar", ["-tvf", archivePath], {
|
||||
env: { ...process.env, COPYFILE_DISABLE: "1" },
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
});
|
||||
const lines = stdout.split("\n").filter((line) => line.trim().length > 0);
|
||||
for (const line of lines) {
|
||||
// GNU tar -tvf: "<perms> <owner>/<group> <size> <date> <time> <name>[ -> target]".
|
||||
const match = line.match(/^(\S+)\s+\S+\s+\d+\s+\S+\s+\S+\s+(.*)$/);
|
||||
if (!match) {
|
||||
throw new Error(`Kubernetes syncOut refusing tarball with an unparseable entry listing: ${line}`);
|
||||
}
|
||||
const typeFlag = match[1][0];
|
||||
let name = match[2];
|
||||
let linkTarget: string | null = null;
|
||||
if (typeFlag === "l") {
|
||||
const idx = name.indexOf(" -> ");
|
||||
if (idx === -1) throw new Error(`Kubernetes syncOut refusing unparseable symlink entry: ${line}`);
|
||||
linkTarget = name.slice(idx + " -> ".length);
|
||||
name = name.slice(0, idx);
|
||||
} else if (typeFlag === "h") {
|
||||
const idx = name.indexOf(" link to ");
|
||||
if (idx === -1) throw new Error(`Kubernetes syncOut refusing unparseable hardlink entry: ${line}`);
|
||||
linkTarget = name.slice(idx + " link to ".length);
|
||||
name = name.slice(0, idx);
|
||||
}
|
||||
const cleanName = name.replace(/\/+$/, "");
|
||||
if (cleanName.length > 0 && posixPathEscapes(cleanName)) {
|
||||
throw new Error(`Kubernetes syncOut refusing tarball member that escapes the extraction dir: ${name}`);
|
||||
}
|
||||
if (linkTarget !== null) {
|
||||
const resolved = path.posix.join(path.posix.dirname(cleanName), linkTarget);
|
||||
if (path.posix.isAbsolute(linkTarget) || posixPathEscapes(resolved)) {
|
||||
throw new Error(
|
||||
`Kubernetes syncOut refusing tarball link whose target escapes the extraction dir: ${name} -> ${linkTarget}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function extractHostTarball(input: { archivePath: string; localDir: string }): Promise<void> {
|
||||
// The archive is sandbox-authored and untrusted: validate every member (and
|
||||
// link target) is confined before letting host-side tar write a single byte.
|
||||
await assertTarballEntriesConfined(input.archivePath);
|
||||
await fs.mkdir(input.localDir, { recursive: true });
|
||||
await execFileAsync("tar", ["-xf", input.archivePath, "-C", input.localDir], {
|
||||
env: { ...process.env, COPYFILE_DISABLE: "1" },
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
});
|
||||
}
|
||||
|
||||
async function countHostFiles(root: string, exclude?: string[]): Promise<number> {
|
||||
const excludeSet = new Set(exclude ?? []);
|
||||
let total = 0;
|
||||
const walk = async (dir: string): Promise<void> => {
|
||||
const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
|
||||
for (const entry of entries) {
|
||||
if (excludeSet.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
await walk(full);
|
||||
} else {
|
||||
total += 1;
|
||||
}
|
||||
}
|
||||
};
|
||||
await walk(root).catch(() => undefined);
|
||||
return total;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Inbound (host → sandbox)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Transfer all `kind:"file"` mappings of an operation in ONE exec. The host tars
|
||||
* the sources under stable index names on disk, streams the archive's raw bytes
|
||||
* over the exec's stdin, and a single in-pod script reads exactly the archive's
|
||||
* byte count (`head -c <N>`), extracts into a reserved `0700` staging dir,
|
||||
* applies each requested mode BEFORE the rename (no widened window), then
|
||||
* atomic-`mv -f`s each file onto its target through a `/proc/self/fd`-pinned
|
||||
* parent directory so a symlink swap cannot redirect the write outside the root.
|
||||
*/
|
||||
async function syncInFileMappings(input: {
|
||||
exec: PodStreamExec;
|
||||
mappings: PluginSyncFileMapping[];
|
||||
remoteDir: string;
|
||||
timeoutMs: number;
|
||||
}): Promise<{ filesTransferred: number; bytesTransferred: number }> {
|
||||
const { exec, mappings, remoteDir, timeoutMs } = input;
|
||||
if (mappings.length === 0) return { filesTransferred: 0, bytesTransferred: 0 };
|
||||
|
||||
for (const mapping of mappings) {
|
||||
assertConfinedSandboxPath(remoteDir, mapping.targetPath, "target");
|
||||
}
|
||||
|
||||
return withHostTempDir(async (tmp) => {
|
||||
// Stage each source under a flat index name so one tar carries the whole
|
||||
// operation; the index maps back to the mapping for mode + rename below.
|
||||
const stage = path.join(tmp, "stage");
|
||||
await fs.mkdir(stage);
|
||||
let bytesTransferred = 0;
|
||||
const indexNames: string[] = [];
|
||||
for (let i = 0; i < mappings.length; i += 1) {
|
||||
const name = String(i);
|
||||
await fs.copyFile(mappings[i].sourcePath, path.join(stage, name));
|
||||
bytesTransferred += (await fs.stat(mappings[i].sourcePath)).size;
|
||||
indexNames.push(name);
|
||||
}
|
||||
|
||||
const archivePath = path.join(tmp, "sync-in.tar");
|
||||
await createHostTarball({ localDir: stage, archivePath, entries: indexNames });
|
||||
// Exact archive size: the pod reads precisely this many bytes so its extract
|
||||
// pipeline self-terminates without depending on stdin EOF delivery.
|
||||
const archiveBytes = (await fs.stat(archivePath)).size;
|
||||
|
||||
// Reserved staging dir is a DIRECT child of the workspace root (created
|
||||
// `0700`), so a secret is never world-readable and the closing `mv -f` is an
|
||||
// atomic same-filesystem rename.
|
||||
const remoteStage = path.posix.join(remoteDir, scratchName());
|
||||
const parentDirs = [...new Set(mappings.map((m) => path.posix.dirname(m.targetPath)))];
|
||||
|
||||
const script: string[] = [...canonicalizerPreamble(shQuote(remoteDir))];
|
||||
// Sweep the staging dir on ANY exit so a failed transfer leaves no scratch.
|
||||
script.push(`trap 'rm -rf ${shQuote(remoteStage)}' EXIT;`);
|
||||
script.push(`mkdir -p -m 700 ${shQuote(remoteStage)} || { echo "stage mkdir failed" >&2; exit 46; };`);
|
||||
// Confine the deepest existing ancestor of each target parent BEFORE creating
|
||||
// it: `mkdir -p` follows a sandbox-planted symlink ancestor and would
|
||||
// otherwise materialize the directory OUTSIDE the root before any post-mkdir
|
||||
// check could reject it (P0 escape). Confine-then-create closes that window.
|
||||
for (const dir of parentDirs) {
|
||||
script.push(
|
||||
`_pc_confine_ancestor ${shQuote(dir)} || { echo "ESCAPE" >&2; exit 42; };`,
|
||||
`mkdir -p ${shQuote(dir)} || { echo "mkdir failed" >&2; exit 46; };`,
|
||||
);
|
||||
}
|
||||
// Re-confine every (now-materialized) target parent dir through realpath before
|
||||
// any bytes land: a sandbox-planted symlink parent is caught here too.
|
||||
for (const dir of parentDirs) {
|
||||
script.push(
|
||||
`_pc_d=$(_pc_resolve ${shQuote(dir)}) || { echo "ESCAPE" >&2; exit 42; };`,
|
||||
`case "$_pc_d/" in "$_pc_root"/*) : ;; *) echo "ESCAPE" >&2; exit 42 ;; esac;`,
|
||||
);
|
||||
}
|
||||
// Read exactly the archive's bytes off stdin and extract the whole payload
|
||||
// into the staging dir in one pipeline.
|
||||
script.push(
|
||||
`head -c ${archiveBytes} | tar -xf - -C ${shQuote(remoteStage)} || { echo "extract failed" >&2; exit 43; };`,
|
||||
);
|
||||
// Promote each staged file onto its target: chmod the temp first (secret
|
||||
// lands at its mode from the instant it exists at targetPath), then bind the
|
||||
// parent-dir re-check and the rename into a `/proc/self/fd`-pinned open so an
|
||||
// ancestor swap after the check cannot redirect the rename.
|
||||
mappings.forEach((mapping, i) => {
|
||||
const staged = path.posix.join(remoteStage, indexNames[i]);
|
||||
const parentDir = path.posix.dirname(mapping.targetPath);
|
||||
const base = path.posix.basename(mapping.targetPath);
|
||||
if (typeof mapping.mode === "number") {
|
||||
script.push(
|
||||
`chmod ${(mapping.mode & 0o7777).toString(8).padStart(3, "0")} ${shQuote(staged)} || { echo "chmod failed" >&2; exit 48; };`,
|
||||
);
|
||||
}
|
||||
script.push(
|
||||
`_pc_tgt_dir=$(_pc_resolve ${shQuote(parentDir)}) || { echo "ESCAPE" >&2; exit 42; };`,
|
||||
`case "$_pc_tgt_dir/" in "$_pc_root"/*) : ;; *) echo "ESCAPE" >&2; exit 42 ;; esac;`,
|
||||
`exec 8<"$_pc_tgt_dir" || { echo "open failed" >&2; exit 47; };`,
|
||||
`_pc_fd_dir=$(_pc_resolve /proc/self/fd/8) || { echo "ESCAPE" >&2; exit 42; };`,
|
||||
`case "$_pc_fd_dir/" in "$_pc_root"/*) : ;; *) echo "ESCAPE" >&2; exit 42 ;; esac;`,
|
||||
`mv -f ${shQuote(staged)} /proc/self/fd/8/${shQuote(base)} || { echo "rename failed" >&2; exit 44; };`,
|
||||
`exec 8>&-;`,
|
||||
);
|
||||
});
|
||||
|
||||
await streamFileToPodStdin({
|
||||
exec,
|
||||
script: script.join("\n"),
|
||||
filePath: archivePath,
|
||||
timeoutMs,
|
||||
label: "syncIn file transfer",
|
||||
});
|
||||
return { filesTransferred: mappings.length, bytesTransferred };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Transfer one `kind:"directory"` mapping in ONE exec: the host tars the source
|
||||
* on disk (reproducing `followSymlinks` → `-h` and `exclude`), streams its raw
|
||||
* bytes over stdin, and the pod reads exactly that byte count and extracts into
|
||||
* the target through a `/proc/self/fd`-pinned directory inode. Directory
|
||||
* extraction is destroy-into (non-atomic), matching the base64 fallback's tar;
|
||||
* only single files are atomic.
|
||||
*/
|
||||
async function syncInDirectoryMapping(input: {
|
||||
exec: PodStreamExec;
|
||||
mapping: PluginSyncFileMapping;
|
||||
remoteDir: string;
|
||||
timeoutMs: number;
|
||||
}): Promise<{ filesTransferred: number; bytesTransferred: number }> {
|
||||
const { exec, mapping, remoteDir, timeoutMs } = input;
|
||||
assertConfinedSandboxPath(remoteDir, mapping.targetPath, "target");
|
||||
return withHostTempDir(async (tmp) => {
|
||||
const archivePath = path.join(tmp, "sync-in.tar");
|
||||
await createHostTarball({
|
||||
localDir: mapping.sourcePath,
|
||||
archivePath,
|
||||
exclude: mapping.exclude,
|
||||
followSymlinks: mapping.followSymlinks,
|
||||
});
|
||||
const archiveBytes = (await fs.stat(archivePath)).size;
|
||||
|
||||
const target = mapping.targetPath;
|
||||
const script = [
|
||||
...canonicalizerPreamble(shQuote(remoteDir)),
|
||||
// Confine the deepest existing ancestor before `mkdir -p` runs: it follows a
|
||||
// sandbox-planted symlink ancestor and would otherwise create the target dir
|
||||
// OUTSIDE the root before the post-mkdir realpath check below could reject it.
|
||||
`_pc_confine_ancestor ${shQuote(target)} || { echo "ESCAPE" >&2; exit 42; };`,
|
||||
`mkdir -p ${shQuote(target)} || { echo "mkdir failed" >&2; exit 46; };`,
|
||||
// Open-then-verify the extraction dir: `open()` walks every ancestor, so a
|
||||
// post-resolve ancestor swap is caught by re-canonicalizing the pinned fd
|
||||
// before extracting; `tar -C /proc/self/fd/9` then chdir's through the
|
||||
// pinned inode, immune to a later path swap.
|
||||
`_pc_real=$(_pc_resolve ${shQuote(target)}) || { echo "ESCAPE" >&2; exit 42; };`,
|
||||
`case "$_pc_real/" in "$_pc_root"/*) : ;; *) echo "ESCAPE" >&2; exit 42 ;; esac;`,
|
||||
`exec 9<"$_pc_real" || { echo "open failed" >&2; exit 46; };`,
|
||||
`_pc_fd_real=$(_pc_resolve /proc/self/fd/9) || { echo "ESCAPE" >&2; exit 42; };`,
|
||||
`case "$_pc_fd_real/" in "$_pc_root"/*) : ;; *) echo "ESCAPE" >&2; exit 42 ;; esac;`,
|
||||
`head -c ${archiveBytes} | tar -xf - -C /proc/self/fd/9 || { echo "extract failed" >&2; exit 43; };`,
|
||||
`exec 9>&-;`,
|
||||
].join("\n");
|
||||
|
||||
await streamFileToPodStdin({
|
||||
exec,
|
||||
script,
|
||||
filePath: archivePath,
|
||||
timeoutMs,
|
||||
label: "syncIn directory transfer",
|
||||
});
|
||||
const filesTransferred = await countHostFiles(mapping.sourcePath, mapping.exclude);
|
||||
return { filesTransferred, bytesTransferred: archiveBytes };
|
||||
});
|
||||
}
|
||||
|
||||
export async function performSyncIn(input: {
|
||||
exec: PodStreamExec;
|
||||
operations: PluginSyncOperation[];
|
||||
remoteDir: string;
|
||||
timeoutMs: number;
|
||||
}): Promise<PluginEnvironmentSyncResult> {
|
||||
const operations: PluginEnvironmentSyncResult["operations"] = [];
|
||||
for (const operation of input.operations) {
|
||||
let filesTransferred = 0;
|
||||
let bytesTransferred = 0;
|
||||
|
||||
const fileMappings = operation.files.filter((mapping) => mapping.kind === "file");
|
||||
const directoryMappings = operation.files.filter((mapping) => mapping.kind === "directory");
|
||||
|
||||
const fileResult = await syncInFileMappings({
|
||||
exec: input.exec,
|
||||
mappings: fileMappings,
|
||||
remoteDir: input.remoteDir,
|
||||
timeoutMs: input.timeoutMs,
|
||||
});
|
||||
filesTransferred += fileResult.filesTransferred;
|
||||
bytesTransferred += fileResult.bytesTransferred;
|
||||
|
||||
for (const mapping of directoryMappings) {
|
||||
const dirResult = await syncInDirectoryMapping({
|
||||
exec: input.exec,
|
||||
mapping,
|
||||
remoteDir: input.remoteDir,
|
||||
timeoutMs: input.timeoutMs,
|
||||
});
|
||||
filesTransferred += dirResult.filesTransferred;
|
||||
bytesTransferred += dirResult.bytesTransferred;
|
||||
}
|
||||
|
||||
operations.push({ operationId: operation.operationId, filesTransferred, bytesTransferred });
|
||||
}
|
||||
return { operations };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Outbound (sandbox → host)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Stream all `kind:"file"` mappings of an operation back in ONE exec. The in-pod
|
||||
* script validates + snapshots each source (confinement realpath check, then a
|
||||
* non-symlink regular-file re-check immediately before `cp` closes the
|
||||
* validation→copy window), tars the immutable snapshots under index names, and
|
||||
* streams the archive on stdout straight into a host file. The host decodes,
|
||||
* extracts to a temp, and atomic-renames each file onto its host target
|
||||
* (chmod-before-rename for secret modes) so an interrupted reassembly never
|
||||
* truncates a target.
|
||||
*/
|
||||
async function syncOutFileMappings(input: {
|
||||
exec: PodStreamExec;
|
||||
mappings: PluginSyncFileMapping[];
|
||||
remoteDir: string;
|
||||
timeoutMs: number;
|
||||
maxOutputBytes: number;
|
||||
}): Promise<{ filesTransferred: number; bytesTransferred: number }> {
|
||||
const { exec, mappings, remoteDir, timeoutMs, maxOutputBytes } = input;
|
||||
if (mappings.length === 0) return { filesTransferred: 0, bytesTransferred: 0 };
|
||||
|
||||
for (const mapping of mappings) {
|
||||
assertConfinedSandboxPath(remoteDir, mapping.sourcePath, "source");
|
||||
}
|
||||
|
||||
return withHostTempDir(async (tmp) => {
|
||||
const remoteStage = path.posix.join(remoteDir, scratchName());
|
||||
const indexNames = mappings.map((_, i) => String(i));
|
||||
|
||||
const script: string[] = [...canonicalizerPreamble(shQuote(remoteDir))];
|
||||
script.push(`trap 'rm -rf ${shQuote(remoteStage)}' EXIT;`);
|
||||
script.push(`mkdir -p -m 700 ${shQuote(remoteStage)} || { echo "stage mkdir failed" >&2; exit 46; };`);
|
||||
mappings.forEach((mapping, i) => {
|
||||
const snapshot = path.posix.join(remoteStage, indexNames[i]);
|
||||
script.push(
|
||||
`_pc_real=$(_pc_resolve ${shQuote(mapping.sourcePath)}) || { echo "ESCAPE" >&2; exit 42; };`,
|
||||
`case "$_pc_real/" in "$_pc_root"/*) : ;; *) echo "ESCAPE" >&2; exit 42 ;; esac;`,
|
||||
// Close the validation→copy TOCTOU by pinning the file to an FD and
|
||||
// snapshotting THROUGH it, never re-opening by name: `open()` captures the
|
||||
// inode, so a source replacement (symlink swap) after this point cannot
|
||||
// redirect the copy. Re-resolving the pinned fd re-confines the TRUE inode
|
||||
// we opened — if the sandbox swapped `$_pc_real` for a symlink between the
|
||||
// resolve above and this open, the fd now points at that target and the
|
||||
// re-confinement (or the regular-file check) rejects it before any byte is
|
||||
// copied. `cp` then reads the fd's inode, immune to any further swap.
|
||||
`exec 7<"$_pc_real" || { echo "REPLACED" >&2; exit 45; };`,
|
||||
`_pc_fd_real=$(_pc_resolve /proc/self/fd/7) || { echo "ESCAPE" >&2; exit 42; };`,
|
||||
`case "$_pc_fd_real/" in "$_pc_root"/*) : ;; *) echo "ESCAPE" >&2; exit 42 ;; esac;`,
|
||||
`[ -f /proc/self/fd/7 ] || { echo "NOTREG" >&2; exit 45; };`,
|
||||
`cp -- /proc/self/fd/7 ${shQuote(snapshot)} || { echo "snapshot copy failed" >&2; exit 43; };`,
|
||||
`exec 7>&-;`,
|
||||
);
|
||||
});
|
||||
// Tar the immutable snapshots straight to stdout (streamed to a host file).
|
||||
script.push(
|
||||
`tar -c --no-xattrs -f - -C ${shQuote(remoteStage)} -- ${indexNames
|
||||
.map(shQuote)
|
||||
.join(" ")} || { echo "tar failed" >&2; exit 43; };`,
|
||||
);
|
||||
|
||||
const localTar = path.join(tmp, "sync-out.tar");
|
||||
await streamPodStdoutToFile({
|
||||
exec,
|
||||
script: script.join("\n"),
|
||||
filePath: localTar,
|
||||
maxOutputBytes,
|
||||
timeoutMs,
|
||||
label: "syncOut file transfer",
|
||||
});
|
||||
|
||||
// Reassemble on the host: member-confine the sandbox-authored archive,
|
||||
// extract to a temp, then atomic-rename each index file onto its host target.
|
||||
const extractDir = path.join(tmp, "extract");
|
||||
await extractHostTarball({ archivePath: localTar, localDir: extractDir });
|
||||
|
||||
let bytesTransferred = 0;
|
||||
for (let i = 0; i < mappings.length; i += 1) {
|
||||
const mapping = mappings[i];
|
||||
const staged = path.join(extractDir, indexNames[i]);
|
||||
await fs.mkdir(path.dirname(mapping.targetPath), { recursive: true });
|
||||
if (typeof mapping.mode === "number") {
|
||||
await fs.chmod(staged, mapping.mode);
|
||||
}
|
||||
bytesTransferred += (await fs.stat(staged)).size;
|
||||
await fs.rename(staged, mapping.targetPath);
|
||||
}
|
||||
return { filesTransferred: mappings.length, bytesTransferred };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream one `kind:"directory"` mapping back in ONE exec: the in-pod script
|
||||
* confines the source (realpath through `/proc/self/fd`), tars it (reproducing
|
||||
* `followSymlinks` → `-h` and `exclude`, naming top-level entries so no "." self
|
||||
* entry is embedded) straight to stdout, and the host streams that into a file,
|
||||
* member-confines the sandbox-authored tar, and extracts into the target dir.
|
||||
*/
|
||||
async function syncOutDirectoryMapping(input: {
|
||||
exec: PodStreamExec;
|
||||
mapping: PluginSyncFileMapping;
|
||||
remoteDir: string;
|
||||
timeoutMs: number;
|
||||
maxOutputBytes: number;
|
||||
}): Promise<{ filesTransferred: number; bytesTransferred: number }> {
|
||||
const { exec, mapping, remoteDir, timeoutMs, maxOutputBytes } = input;
|
||||
assertConfinedSandboxPath(remoteDir, mapping.sourcePath, "source");
|
||||
return withHostTempDir(async (tmp) => {
|
||||
const excludeFlags = ["._*", ...(mapping.exclude ?? [])]
|
||||
.map((entry) => `--exclude ${shQuote(entry)}`)
|
||||
.join(" ");
|
||||
const script = [
|
||||
...canonicalizerPreamble(shQuote(remoteDir)),
|
||||
// Confine the source dir through an open-then-verify pinned fd before taring.
|
||||
`_pc_real=$(_pc_resolve ${shQuote(mapping.sourcePath)}) || { echo "ESCAPE" >&2; exit 42; };`,
|
||||
`case "$_pc_real/" in "$_pc_root"/*) : ;; *) echo "ESCAPE" >&2; exit 42 ;; esac;`,
|
||||
`exec 9<"$_pc_real" || { echo "open failed" >&2; exit 46; };`,
|
||||
`_pc_fd_real=$(_pc_resolve /proc/self/fd/9) || { echo "ESCAPE" >&2; exit 42; };`,
|
||||
`case "$_pc_fd_real/" in "$_pc_root"/*) : ;; *) echo "ESCAPE" >&2; exit 42 ;; esac;`,
|
||||
`cd /proc/self/fd/9 || { echo "cd failed" >&2; exit 46; };`,
|
||||
// Collect top-level entries (incl. dotfiles) without a "." self-entry, then
|
||||
// tar with the `followSymlinks` → `-h` mapping, streaming to stdout.
|
||||
"set -- *",
|
||||
'if [ "$#" -eq 1 ] && [ "$1" = "*" ] && [ ! -e "$1" ] && [ ! -L "$1" ]; then set --; fi',
|
||||
'for entry in .[!.]* ..?*; do [ -e "$entry" ] || [ -L "$entry" ] || continue; set -- "$@" "$entry"; done',
|
||||
`if [ "$#" -eq 0 ]; then dd if=/dev/zero bs=1024 count=1 2>/dev/null; ` +
|
||||
`else tar -c --no-xattrs ${mapping.followSymlinks ? "-h " : ""}${excludeFlags} -f - -- "$@" || { echo "tar failed" >&2; exit 43; }; fi`,
|
||||
`exec 9>&-;`,
|
||||
].join("\n");
|
||||
|
||||
const localTar = path.join(tmp, "sync-out.tar");
|
||||
await streamPodStdoutToFile({
|
||||
exec,
|
||||
script,
|
||||
filePath: localTar,
|
||||
maxOutputBytes,
|
||||
timeoutMs,
|
||||
label: "syncOut directory transfer",
|
||||
});
|
||||
const bytesTransferred = (await fs.stat(localTar)).size;
|
||||
await extractHostTarball({ archivePath: localTar, localDir: mapping.targetPath });
|
||||
const filesTransferred = await countHostFiles(mapping.targetPath, mapping.exclude);
|
||||
return { filesTransferred, bytesTransferred };
|
||||
});
|
||||
}
|
||||
|
||||
export async function performSyncOut(input: {
|
||||
exec: PodStreamExec;
|
||||
operations: PluginSyncOperation[];
|
||||
remoteDir: string;
|
||||
timeoutMs: number;
|
||||
maxOutputBytes?: number;
|
||||
}): Promise<PluginEnvironmentSyncResult> {
|
||||
const maxOutputBytes = input.maxOutputBytes ?? MAX_SYNC_OUTPUT_BYTES;
|
||||
const operations: PluginEnvironmentSyncResult["operations"] = [];
|
||||
for (const operation of input.operations) {
|
||||
let filesTransferred = 0;
|
||||
let bytesTransferred = 0;
|
||||
|
||||
const fileMappings = operation.files.filter((mapping) => mapping.kind === "file");
|
||||
const directoryMappings = operation.files.filter((mapping) => mapping.kind === "directory");
|
||||
|
||||
const fileResult = await syncOutFileMappings({
|
||||
exec: input.exec,
|
||||
mappings: fileMappings,
|
||||
remoteDir: input.remoteDir,
|
||||
timeoutMs: input.timeoutMs,
|
||||
maxOutputBytes,
|
||||
});
|
||||
filesTransferred += fileResult.filesTransferred;
|
||||
bytesTransferred += fileResult.bytesTransferred;
|
||||
|
||||
for (const mapping of directoryMappings) {
|
||||
const dirResult = await syncOutDirectoryMapping({
|
||||
exec: input.exec,
|
||||
mapping,
|
||||
remoteDir: input.remoteDir,
|
||||
timeoutMs: input.timeoutMs,
|
||||
maxOutputBytes,
|
||||
});
|
||||
filesTransferred += dirResult.filesTransferred;
|
||||
bytesTransferred += dirResult.bytesTransferred;
|
||||
}
|
||||
|
||||
operations.push({ operationId: operation.operationId, filesTransferred, bytesTransferred });
|
||||
}
|
||||
return { operations };
|
||||
}
|
||||
@@ -12,6 +12,9 @@ import type {
|
||||
PluginEnvironmentRealizeWorkspaceResult,
|
||||
PluginEnvironmentReleaseLeaseParams,
|
||||
PluginEnvironmentResumeLeaseParams,
|
||||
PluginEnvironmentSyncInParams,
|
||||
PluginEnvironmentSyncOutParams,
|
||||
PluginEnvironmentSyncResult,
|
||||
PluginEnvironmentValidateConfigParams,
|
||||
PluginEnvironmentValidationResult,
|
||||
} from "@paperclipai/plugin-sdk";
|
||||
@@ -33,7 +36,8 @@ import {
|
||||
sandboxCrOrchestrator,
|
||||
SandboxCrTimeoutError,
|
||||
} from "./sandbox-cr-orchestrator.js";
|
||||
import { execInPod, wrapCommandWithEnv } from "./pod-exec.js";
|
||||
import { execInPod, execInPodStreaming, wrapCommandWithEnv } from "./pod-exec.js";
|
||||
import { performSyncIn, performSyncOut, type PodStreamExec } from "./file-sync.js";
|
||||
import { checkLeaseResumable, destroyLeaseResources } from "./lease-lifecycle.js";
|
||||
import {
|
||||
deriveCompanySlug,
|
||||
@@ -109,6 +113,88 @@ const readySandboxesByLease = new Set<string>();
|
||||
const RESUME_READY_TIMEOUT_MS = 30_000;
|
||||
const RESUME_READY_POLL_MS = 1_000;
|
||||
|
||||
// The workspace remote dir is the confinement root for native file sync. It is
|
||||
// recorded on the lease metadata at realizeWorkspace time (`remoteCwd`); require
|
||||
// it so a sync can never run without a concrete root to confine every sandbox
|
||||
// path against.
|
||||
function resolveSyncRemoteDir(lease: PluginEnvironmentLease): string {
|
||||
const remoteCwd = lease.metadata?.remoteCwd;
|
||||
if (typeof remoteCwd === "string" && remoteCwd.trim().length > 0) {
|
||||
return remoteCwd.trim();
|
||||
}
|
||||
throw new Error("Kubernetes file sync requires a workspace remote dir on the lease metadata.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the running Sandbox-CR pod for a native file-sync operation and return
|
||||
* a `PodStreamExec` bound to it, exactly like `onEnvironmentExecute` resolves its exec
|
||||
* target: parse config, derive the namespace, wait for the Sandbox pod to reach
|
||||
* Ready (cached per lease), and find the pod name. The `job` backend carries no
|
||||
* file path and is out of scope — file sync is only supported on `sandbox-cr`.
|
||||
*/
|
||||
async function resolveSyncPodExec(
|
||||
params:
|
||||
| PluginEnvironmentSyncInParams
|
||||
| PluginEnvironmentSyncOutParams,
|
||||
): Promise<{ exec: PodStreamExec; timeoutMs: number }> {
|
||||
const { lease } = params;
|
||||
if (!lease.providerLeaseId) {
|
||||
throw new Error("Kubernetes file sync requires a provider lease ID.");
|
||||
}
|
||||
|
||||
const config = kubernetesProviderConfigSchema.parse(params.config);
|
||||
const namespace =
|
||||
typeof lease.metadata?.namespace === "string"
|
||||
? lease.metadata.namespace
|
||||
: deriveTenantNamespace(config, params.companyId);
|
||||
|
||||
const leaseBackend =
|
||||
typeof lease.metadata?.backend === "string"
|
||||
? (lease.metadata.backend as "sandbox-cr" | "job")
|
||||
: config.backend;
|
||||
if (leaseBackend !== "sandbox-cr") {
|
||||
throw new Error(
|
||||
`Kubernetes file sync is only supported on the sandbox-cr backend (lease backend: ${leaseBackend}).`,
|
||||
);
|
||||
}
|
||||
|
||||
const kc = createKubeConfig({
|
||||
inCluster: config.inCluster,
|
||||
kubeconfig: config.kubeconfig,
|
||||
});
|
||||
const clients = makeKubeClients(kc);
|
||||
const timeoutMs = config.podActivityDeadlineSec * 1000;
|
||||
|
||||
// Ensure the Sandbox pod is Ready (wait only the first time for this lease),
|
||||
// then resolve the pod name — mirrors the onEnvironmentExecute resolution.
|
||||
if (!readySandboxesByLease.has(lease.providerLeaseId)) {
|
||||
await sandboxCrOrchestrator.waitForCompletion(clients, namespace, lease.providerLeaseId, {
|
||||
timeoutMs,
|
||||
pollMs: 2000,
|
||||
});
|
||||
readySandboxesByLease.add(lease.providerLeaseId);
|
||||
}
|
||||
|
||||
const podName =
|
||||
typeof lease.metadata?.podName === "string" && lease.metadata.podName
|
||||
? lease.metadata.podName
|
||||
: await sandboxCrOrchestrator.findPod(clients, namespace, lease.providerLeaseId);
|
||||
if (!podName) {
|
||||
throw new Error("Kubernetes file sync could not resolve the Sandbox pod name.");
|
||||
}
|
||||
|
||||
// Bind the streaming exec: raw tar bytes move over stdin/stdout straight to and
|
||||
// from a host file, so neither side buffers the whole payload. The file-sync
|
||||
// module bounds the untrusted pod's stdout with its own streamed-bytes disk
|
||||
// guard and passes the stderr cap through `io`.
|
||||
const exec: PodStreamExec = (command, io) =>
|
||||
execInPodStreaming(kc, namespace, podName, "agent", command, {
|
||||
...io,
|
||||
timeoutMs: io.timeoutMs ?? timeoutMs,
|
||||
});
|
||||
return { exec, timeoutMs };
|
||||
}
|
||||
|
||||
const plugin = definePlugin({
|
||||
async setup(ctx) {
|
||||
ctx.logger.info("Kubernetes sandbox provider plugin ready");
|
||||
@@ -335,6 +421,10 @@ const plugin = definePlugin({
|
||||
secretName,
|
||||
phase: "Pending",
|
||||
backend: config.backend,
|
||||
// Native file sync streams over a pod exec; only the sandbox-cr backend
|
||||
// exposes one. Flag the job backend so the server keeps the base64 fallback
|
||||
// rather than routing its sync to a hook that would reject immediately.
|
||||
nativeFileSyncUnsupported: config.backend !== "sandbox-cr",
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -404,6 +494,9 @@ const plugin = definePlugin({
|
||||
secretName,
|
||||
phase: check.phase,
|
||||
backend: leaseBackend,
|
||||
// See acquireLease: only the sandbox-cr backend has a pod-exec channel for
|
||||
// native sync, so a resumed job lease must keep the base64 fallback.
|
||||
nativeFileSyncUnsupported: leaseBackend !== "sandbox-cr",
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -859,6 +952,40 @@ const plugin = definePlugin({
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
// Opt-in native inbound transfer. Defining this hook (with onEnvironmentSyncOut)
|
||||
// makes the worker advertise `environmentSyncIn`/`environmentSyncOut`, so the
|
||||
// host runner routes workspace/asset transfers through a single pod exec per
|
||||
// operation (host tar streamed over the exec stdin → in-pod `head -c <N> | tar
|
||||
// -x` → stage-then-atomic-`mv -f`) instead of the base64-over-exec chunk loop.
|
||||
// Only the sandbox-cr backend is supported; the job backend carries no file
|
||||
// path. Providers that do not define these keep the byte-identical fallback.
|
||||
async onEnvironmentSyncIn(
|
||||
params: PluginEnvironmentSyncInParams,
|
||||
): Promise<PluginEnvironmentSyncResult> {
|
||||
const remoteDir = resolveSyncRemoteDir(params.lease);
|
||||
const { exec, timeoutMs } = await resolveSyncPodExec(params);
|
||||
return await performSyncIn({
|
||||
exec,
|
||||
operations: params.operations,
|
||||
remoteDir,
|
||||
timeoutMs,
|
||||
});
|
||||
},
|
||||
|
||||
// Opt-in native outbound transfer. See onEnvironmentSyncIn.
|
||||
async onEnvironmentSyncOut(
|
||||
params: PluginEnvironmentSyncOutParams,
|
||||
): Promise<PluginEnvironmentSyncResult> {
|
||||
const remoteDir = resolveSyncRemoteDir(params.lease);
|
||||
const { exec, timeoutMs } = await resolveSyncPodExec(params);
|
||||
return await performSyncOut({
|
||||
exec,
|
||||
operations: params.operations,
|
||||
remoteDir,
|
||||
timeoutMs,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export default plugin;
|
||||
@@ -20,6 +20,7 @@
|
||||
|
||||
import { Exec } from "@kubernetes/client-node";
|
||||
import { PassThrough } from "node:stream";
|
||||
import type { Readable, Writable } from "node:stream";
|
||||
import type { KubeConfig } from "@kubernetes/client-node";
|
||||
|
||||
// Minimal WebSocket-like shape covering what we touch (close()). The full type
|
||||
@@ -61,6 +62,23 @@ export async function execInPod(
|
||||
command: string[],
|
||||
stdin?: string | Buffer,
|
||||
timeoutMs?: number,
|
||||
// Optional host-side bound on accumulated stdout. The pod is an untrusted,
|
||||
// attacker-controlled endpoint: a malicious pod can emit unbounded stdout
|
||||
// during an exec (e.g. a native file-sync `syncOut` tarball), which would grow
|
||||
// the in-memory accumulator without limit — blowing up the worker's RSS and,
|
||||
// past V8's ~512 MB max string length, throwing a synchronous RangeError inside
|
||||
// the stream `data` listener that no caller can catch (an uncaught exception =
|
||||
// worker crash = cross-tenant DoS). When set, accumulation fails closed the
|
||||
// instant it would exceed the cap so the caller can fall back. In-pod size
|
||||
// checks are worthless here — only the host can be trusted to enforce this.
|
||||
maxStdoutBytes?: number,
|
||||
// Same bound for the stderr channel. stderr is equally pod-controlled: a
|
||||
// malicious pod can emit an unbounded stderr stream during the SAME exec (e.g.
|
||||
// crafted tar/realpath diagnostics on the `syncOut` path) and trigger the
|
||||
// identical uncaught-`RangeError` worker crash. When set, stderr accumulation
|
||||
// fails closed at the cap; regardless of the cap, the `+=` is guarded so a
|
||||
// max-string-length `RangeError` can never escape as an uncaught exception.
|
||||
maxStderrBytes?: number,
|
||||
): Promise<{ exitCode: number; stdout: string; stderr: string }> {
|
||||
const exec = new Exec(kc);
|
||||
const stdoutStream = new PassThrough();
|
||||
@@ -91,13 +109,8 @@ export async function execInPod(
|
||||
|
||||
let stdoutData = "";
|
||||
let stderrData = "";
|
||||
|
||||
stdoutStream.on("data", (chunk: Buffer) => {
|
||||
stdoutData += chunk.toString("utf-8");
|
||||
});
|
||||
stderrStream.on("data", (chunk: Buffer) => {
|
||||
stderrData += chunk.toString("utf-8");
|
||||
});
|
||||
let stdoutBytes = 0;
|
||||
let stderrBytes = 0;
|
||||
|
||||
return await new Promise<{ exitCode: number; stdout: string; stderr: string }>(
|
||||
(resolve, reject) => {
|
||||
@@ -143,6 +156,62 @@ export async function execInPod(
|
||||
resolve({ exitCode: pendingExitCode, stdout: stdoutData, stderr: stderrData });
|
||||
};
|
||||
|
||||
// Fail the whole exec closed, tearing down the WebSocket so the pod stops
|
||||
// streaming. Used by the stdout cap below; the `resolved` guard makes it a
|
||||
// no-op if the exec already finished.
|
||||
const failClosed = (err: Error) => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
if (watchdog) clearTimeout(watchdog);
|
||||
try { ws?.close(); } catch { /* ignore */ }
|
||||
reject(err);
|
||||
};
|
||||
|
||||
// Accumulate stdout inside the executor so the cap can reject before an
|
||||
// unbounded pod payload exhausts memory. Once resolved (finished, timed
|
||||
// out, or capped) further chunks are dropped rather than appended.
|
||||
stdoutStream.on("data", (chunk: Buffer) => {
|
||||
if (resolved) return;
|
||||
if (typeof maxStdoutBytes === "number" && maxStdoutBytes >= 0) {
|
||||
stdoutBytes += chunk.length;
|
||||
if (stdoutBytes > maxStdoutBytes) {
|
||||
failClosed(new Error(
|
||||
`execInPod stdout exceeded the ${maxStdoutBytes}-byte cap (pod=${podName}, container=${containerName}); the sandbox produced more output than the buffer allows.`,
|
||||
));
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
stdoutData += chunk.toString("utf-8");
|
||||
} catch (err) {
|
||||
// Belt-and-suspenders: even under an explicit cap (or with none set),
|
||||
// never let a `+=` RangeError at V8's max string length escape this
|
||||
// listener as an uncaught exception.
|
||||
failClosed(err instanceof Error ? err : new Error(String(err)));
|
||||
}
|
||||
});
|
||||
|
||||
// stderr is pod-controlled too — bound it with the same fail-closed policy
|
||||
// and, unconditionally, guard the `+=` so a max-string-length `RangeError`
|
||||
// can never escape this listener as an uncaught (worker-crashing) exception.
|
||||
stderrStream.on("data", (chunk: Buffer) => {
|
||||
if (resolved) return;
|
||||
if (typeof maxStderrBytes === "number" && maxStderrBytes >= 0) {
|
||||
stderrBytes += chunk.length;
|
||||
if (stderrBytes > maxStderrBytes) {
|
||||
failClosed(new Error(
|
||||
`execInPod stderr exceeded the ${maxStderrBytes}-byte cap (pod=${podName}, container=${containerName}); the sandbox produced more output than the buffer allows.`,
|
||||
));
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
stderrData += chunk.toString("utf-8");
|
||||
} catch (err) {
|
||||
failClosed(err instanceof Error ? err : new Error(String(err)));
|
||||
}
|
||||
});
|
||||
|
||||
stdoutStream.on("end", () => { stdoutEnded = true; tryFinish(); });
|
||||
stderrStream.on("end", () => { stderrEnded = true; tryFinish(); });
|
||||
|
||||
@@ -196,3 +265,180 @@ export async function execInPod(
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Streaming variant of {@link execInPod} for bulk file transfer over the pod
|
||||
* exec data channel.
|
||||
*
|
||||
* Where `execInPod` buffers the command's whole stdout into an in-memory string
|
||||
* (fine for small command output, fatal for a multi-gigabyte tar), this variant
|
||||
* PIPES the exec's stdin from a caller `Readable` and its stdout into a caller
|
||||
* `Writable` — so a native file-sync `syncIn`/`syncOut` streams raw tar bytes
|
||||
* straight to/from a host file on disk and neither the host nor the pod ever
|
||||
* holds the whole payload in memory. Both are intentionally kept side by side:
|
||||
* `execInPod` still backs the `environmentExecute` path unchanged.
|
||||
*
|
||||
* stderr is still accumulated into a (bounded) string: it carries only the
|
||||
* script's fail-loud diagnostics, and the pod controls how many bytes it emits,
|
||||
* so `maxStderrBytes` fails the exec closed the instant the pod floods the
|
||||
* channel — the same DoS guard `execInPod` applies. stdout carries no such cap
|
||||
* here because it is streamed to disk, not a string; the caller bounds it with
|
||||
* its own streamed-bytes guard on the sink `Writable`.
|
||||
*
|
||||
* Stdin EOF: the same k8s-client `stdin.on("end", () => ws.close())` quirk noted
|
||||
* on `execInPod` applies, so we strip that listener and drive the pod command to
|
||||
* self-terminate on the byte count instead of relying on EOF (the caller's
|
||||
* `syncIn` script bounds its read with `head -c <N>`). We close the WebSocket
|
||||
* ourselves from the status callback.
|
||||
*
|
||||
* Resolves once the command's exit status is known AND both the stdout sink has
|
||||
* finished draining and stderr has ended, so a caller that reads the sink file
|
||||
* back after `await` always sees the complete archive.
|
||||
*/
|
||||
export async function execInPodStreaming(
|
||||
kc: KubeConfig,
|
||||
namespace: string,
|
||||
podName: string,
|
||||
containerName: string,
|
||||
command: string[],
|
||||
io: {
|
||||
stdin?: Readable;
|
||||
stdout?: Writable;
|
||||
timeoutMs?: number;
|
||||
maxStderrBytes?: number;
|
||||
},
|
||||
): Promise<{ exitCode: number; stderr: string }> {
|
||||
const exec = new Exec(kc);
|
||||
const stdoutStream = new PassThrough();
|
||||
const stderrStream = new PassThrough();
|
||||
const stdinStream: PassThrough | null = io.stdin ? new PassThrough() : null;
|
||||
|
||||
let stderrData = "";
|
||||
let stderrBytes = 0;
|
||||
|
||||
return await new Promise<{ exitCode: number; stderr: string }>((resolve, reject) => {
|
||||
let ws: WebSocketLike | null = null;
|
||||
let resolved = false;
|
||||
let pendingExitCode: number | null = null;
|
||||
let stdoutDone = false;
|
||||
let stderrEnded = false;
|
||||
|
||||
let watchdog: ReturnType<typeof setTimeout> | null = null;
|
||||
if (typeof io.timeoutMs === "number" && io.timeoutMs > 0) {
|
||||
watchdog = setTimeout(() => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
try { ws?.close(); } catch { /* ignore */ }
|
||||
reject(new Error(
|
||||
`execInPodStreaming timed out after ${io.timeoutMs}ms (pod=${podName}, container=${containerName}, cmd0=${command[0] ?? ""}). The WebSocket likely dropped before the command produced a status frame.`,
|
||||
));
|
||||
}, io.timeoutMs);
|
||||
}
|
||||
|
||||
const tryFinish = () => {
|
||||
if (resolved) return;
|
||||
if (pendingExitCode === null) return;
|
||||
if (!stdoutDone || !stderrEnded) return;
|
||||
resolved = true;
|
||||
if (watchdog) clearTimeout(watchdog);
|
||||
try { ws?.close(); } catch { /* ignore */ }
|
||||
resolve({ exitCode: pendingExitCode, stderr: stderrData });
|
||||
};
|
||||
|
||||
// Fail the whole exec closed, tearing down the WebSocket so the pod stops
|
||||
// streaming. Fired by a sink error (e.g. the caller's disk guard tripping)
|
||||
// or a stream error; the `resolved` guard makes it a no-op once finished.
|
||||
const failClosed = (err: Error) => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
if (watchdog) clearTimeout(watchdog);
|
||||
try { ws?.close(); } catch { /* ignore */ }
|
||||
try { stdinStream?.destroy(); } catch { /* ignore */ }
|
||||
reject(err);
|
||||
};
|
||||
|
||||
// Pipe stdout to the caller sink (streamed to disk), or drain it if the
|
||||
// caller wants none. Piping with the default `end: true` ends the sink when
|
||||
// the pod's stdout closes, so the sink's `finish` marks the archive fully
|
||||
// written. A sink error (the caller's streamed-bytes guard, a full disk)
|
||||
// fails the exec closed and stops the pod.
|
||||
if (io.stdout) {
|
||||
const sink = io.stdout;
|
||||
sink.on("error", failClosed);
|
||||
stdoutStream.on("error", failClosed);
|
||||
sink.on("finish", () => { stdoutDone = true; tryFinish(); });
|
||||
stdoutStream.pipe(sink);
|
||||
} else {
|
||||
stdoutStream.on("data", () => { /* drain */ });
|
||||
stdoutStream.on("end", () => { stdoutDone = true; tryFinish(); });
|
||||
stdoutStream.on("error", failClosed);
|
||||
}
|
||||
|
||||
// stderr is pod-controlled — bound it with the same fail-closed policy as
|
||||
// execInPod and guard the `+=` so a max-string-length RangeError can never
|
||||
// escape as an uncaught (worker-crashing) exception.
|
||||
stderrStream.on("data", (chunk: Buffer) => {
|
||||
if (resolved) return;
|
||||
if (typeof io.maxStderrBytes === "number" && io.maxStderrBytes >= 0) {
|
||||
stderrBytes += chunk.length;
|
||||
if (stderrBytes > io.maxStderrBytes) {
|
||||
failClosed(new Error(
|
||||
`execInPodStreaming stderr exceeded the ${io.maxStderrBytes}-byte cap (pod=${podName}, container=${containerName}); the sandbox produced more diagnostics than the buffer allows.`,
|
||||
));
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
stderrData += chunk.toString("utf-8");
|
||||
} catch (err) {
|
||||
failClosed(err instanceof Error ? err : new Error(String(err)));
|
||||
}
|
||||
});
|
||||
stderrStream.on("end", () => { stderrEnded = true; tryFinish(); });
|
||||
|
||||
const execPromise = exec.exec(
|
||||
namespace,
|
||||
podName,
|
||||
containerName,
|
||||
command,
|
||||
stdoutStream,
|
||||
stderrStream,
|
||||
stdinStream,
|
||||
false, // tty=false: keep stdout/stderr on separate channels
|
||||
(status) => {
|
||||
if (status.status === "Success") {
|
||||
pendingExitCode = 0;
|
||||
} else {
|
||||
const causes = status.details?.causes ?? [];
|
||||
const exitCodeCause = causes.find(
|
||||
(c: { reason?: string; message?: string }) => c.reason === "ExitCode",
|
||||
);
|
||||
pendingExitCode = exitCodeCause?.message ? Number(exitCodeCause.message) : 1;
|
||||
}
|
||||
tryFinish();
|
||||
},
|
||||
);
|
||||
|
||||
execPromise
|
||||
.then((webSocket) => {
|
||||
ws = webSocket as unknown as WebSocketLike;
|
||||
if (stdinStream && io.stdin) {
|
||||
// Strip the default `end -> ws.close()` listener (see execInPod) so
|
||||
// EOF on our stdin only signals the pod, then stream the caller's
|
||||
// source into the exec stdin channel. A source error fails closed.
|
||||
stdinStream.removeAllListeners("end");
|
||||
io.stdin.on("error", failClosed);
|
||||
io.stdin.pipe(stdinStream);
|
||||
} else if (stdinStream) {
|
||||
stdinStream.removeAllListeners("end");
|
||||
stdinStream.end();
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
if (watchdog) clearTimeout(watchdog);
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -90,4 +90,14 @@ export interface KubernetesLeaseMetadata {
|
||||
phase: "Pending" | "Running" | "Succeeded" | "Failed";
|
||||
/** Which backend provisioned this lease. */
|
||||
backend: "sandbox-cr" | "job";
|
||||
/**
|
||||
* True when this lease's backend has NO data channel for the native file-sync
|
||||
* transport. Native sync streams over a pod exec, which only the `sandbox-cr`
|
||||
* backend exposes; the `job` backend carries no exec path, so its sync hook
|
||||
* rejects immediately. The server's per-lease sync-capability gate honors this
|
||||
* opt-out so a job lease keeps the byte-identical base64 fallback instead of
|
||||
* being routed to a native hook that would only error. Absent/false ⇒ native
|
||||
* sync may be used when the worker advertises the verbs.
|
||||
*/
|
||||
nativeFileSyncUnsupported?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,561 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { promises as fs } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import {
|
||||
assertConfinedSandboxPath,
|
||||
performSyncIn,
|
||||
performSyncOut,
|
||||
type PodStreamExec,
|
||||
} from "../../src/file-sync.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test harness
|
||||
//
|
||||
// The K8s hooks transfer files over a single streaming exec per operation. In
|
||||
// production that exec streams raw tar bytes over the pod's exec WebSocket
|
||||
// (stdin from a host file, stdout into a host file); here the injected
|
||||
// `PodStreamExec` runs the generated `sh -c` script against the REAL host shell,
|
||||
// piping the caller's `stdin` Readable into the child and the child's stdout into
|
||||
// the caller's `stdout` Writable, using a host temp dir as the stand-in "sandbox"
|
||||
// workspace root. This exercises the actual tar/head/mv/realpath command shapes
|
||||
// end-to-end (a true round-trip) while recording every exec so we can assert the
|
||||
// single-exec contract and command shape.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface RecordedCall {
|
||||
command: string[];
|
||||
script: string;
|
||||
}
|
||||
|
||||
function makeRealExec(): { exec: PodStreamExec; calls: RecordedCall[] } {
|
||||
const calls: RecordedCall[] = [];
|
||||
const exec: PodStreamExec = async (command, io) => {
|
||||
calls.push({ command, script: command[2] ?? "" });
|
||||
return await new Promise((resolve, reject) => {
|
||||
const child = spawn(command[0], command.slice(1));
|
||||
let err = "";
|
||||
child.stderr.on("data", (chunk: Buffer) => {
|
||||
err += chunk.toString("utf-8");
|
||||
});
|
||||
child.on("error", reject);
|
||||
if (io.stdout) {
|
||||
io.stdout.on("error", reject);
|
||||
child.stdout.pipe(io.stdout);
|
||||
} else {
|
||||
child.stdout.resume();
|
||||
}
|
||||
if (io.stdin) {
|
||||
io.stdin.on("error", reject);
|
||||
io.stdin.pipe(child.stdin);
|
||||
} else {
|
||||
child.stdin.end();
|
||||
}
|
||||
child.on("close", (code) => {
|
||||
resolve({ exitCode: code ?? 0, stderr: err });
|
||||
});
|
||||
});
|
||||
};
|
||||
return { exec, calls };
|
||||
}
|
||||
|
||||
// A stub exec that emits a controlled number of bytes to the caller's stdout
|
||||
// sink without running any shell — used to drive the outbound disk-guard trip
|
||||
// with a pod-authored payload larger than the host allows. Rejects if the sink
|
||||
// errors (the guard fired). Records calls so a test can assert the exec ran.
|
||||
function makeOutputExec(totalBytes: number): { exec: PodStreamExec; calls: RecordedCall[] } {
|
||||
const calls: RecordedCall[] = [];
|
||||
const exec: PodStreamExec = async (command, io) => {
|
||||
calls.push({ command, script: command[2] ?? "" });
|
||||
return await new Promise((resolve, reject) => {
|
||||
const sink = io.stdout;
|
||||
if (!sink) {
|
||||
resolve({ exitCode: 0, stderr: "" });
|
||||
return;
|
||||
}
|
||||
sink.on("error", reject);
|
||||
sink.on("finish", () => resolve({ exitCode: 0, stderr: "" }));
|
||||
sink.end(Buffer.alloc(totalBytes, 0x41));
|
||||
});
|
||||
};
|
||||
return { exec, calls };
|
||||
}
|
||||
|
||||
const tmpDirs: string[] = [];
|
||||
async function makeTmp(prefix: string): Promise<string> {
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), prefix));
|
||||
tmpDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(tmpDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
describe("kubernetes file-sync path confinement", () => {
|
||||
it("rejects a target path that escapes the workspace remote dir", () => {
|
||||
expect(() => assertConfinedSandboxPath("/workspace", "/workspace/../etc/passwd", "target")).toThrow(
|
||||
/escapes|not a confined/,
|
||||
);
|
||||
expect(() => assertConfinedSandboxPath("/workspace", "/etc/passwd", "target")).toThrow(
|
||||
/escapes|not a confined/,
|
||||
);
|
||||
expect(() => assertConfinedSandboxPath("/workspace", "relative/path", "target")).toThrow(
|
||||
/not a confined/,
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts a target path inside the remote dir", () => {
|
||||
expect(() => assertConfinedSandboxPath("/workspace", "/workspace/a/b.txt", "target")).not.toThrow();
|
||||
expect(() => assertConfinedSandboxPath("/workspace", "/workspace", "target")).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("kubernetes onEnvironmentSyncIn (native single-exec transfer)", () => {
|
||||
it("transfers all file mappings of an operation in a SINGLE exec, staging to a temp then mv -f, applying secret mode 0600 with no widened window", async () => {
|
||||
const remoteDir = await makeTmp("k8s-sandbox-");
|
||||
const host = await makeTmp("k8s-host-");
|
||||
const plainSrc = path.join(host, "plain.txt");
|
||||
const secretSrc = path.join(host, "auth.json");
|
||||
await fs.writeFile(plainSrc, "hello world");
|
||||
await fs.writeFile(secretSrc, "{\"token\":\"s3cr3t\"}");
|
||||
|
||||
const { exec, calls } = makeRealExec();
|
||||
const result = await performSyncIn({
|
||||
exec,
|
||||
remoteDir,
|
||||
timeoutMs: 30_000,
|
||||
operations: [
|
||||
{
|
||||
operationId: "op-alpha",
|
||||
files: [
|
||||
{ sourcePath: plainSrc, targetPath: path.join(remoteDir, "plain.txt"), kind: "file" },
|
||||
{
|
||||
sourcePath: secretSrc,
|
||||
targetPath: path.join(remoteDir, "nested/auth.json"),
|
||||
kind: "file",
|
||||
mode: 0o600,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// Single exec for the whole file operation — NOT one exec per file/chunk.
|
||||
expect(calls).toHaveLength(1);
|
||||
// Atomic-replace shape and raw streamed-extract shape present in the script.
|
||||
expect(calls[0].script).toContain("mv -f");
|
||||
expect(calls[0].script).toContain("head -c");
|
||||
expect(calls[0].script).toContain("tar -xf -");
|
||||
// Streaming transport: no base64 round-trip anywhere in the script.
|
||||
expect(calls[0].script).not.toContain("base64");
|
||||
// Files landed with correct contents.
|
||||
expect(await fs.readFile(path.join(remoteDir, "plain.txt"), "utf-8")).toBe("hello world");
|
||||
expect(await fs.readFile(path.join(remoteDir, "nested/auth.json"), "utf-8")).toBe(
|
||||
"{\"token\":\"s3cr3t\"}",
|
||||
);
|
||||
// Secret landed 0600.
|
||||
expect((await fs.stat(path.join(remoteDir, "nested/auth.json"))).mode & 0o777).toBe(0o600);
|
||||
// No leftover reserved scratch dir in the workspace root.
|
||||
const leftovers = (await fs.readdir(remoteDir)).filter((e) => e.startsWith(".paperclip-upload"));
|
||||
expect(leftovers).toEqual([]);
|
||||
// Per-operation counts.
|
||||
expect(result.operations).toEqual([
|
||||
{ operationId: "op-alpha", filesTransferred: 2, bytesTransferred: expect.any(Number) },
|
||||
]);
|
||||
expect(result.operations[0].bytesTransferred).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("transfers a directory mapping honoring exclude, and emits tar -h only when followSymlinks is true", async () => {
|
||||
const remoteDir = await makeTmp("k8s-sandbox-");
|
||||
const host = await makeTmp("k8s-host-");
|
||||
const srcDir = path.join(host, "tree");
|
||||
await fs.mkdir(path.join(srcDir, "sub"), { recursive: true });
|
||||
await fs.writeFile(path.join(srcDir, "keep.txt"), "keep");
|
||||
await fs.writeFile(path.join(srcDir, "skip.log"), "skip");
|
||||
await fs.writeFile(path.join(srcDir, "sub", "data.bin"), "data");
|
||||
|
||||
// Preserve-symlink case (followSymlinks falsy → no -h).
|
||||
{
|
||||
const { exec, calls } = makeRealExec();
|
||||
await performSyncIn({
|
||||
exec,
|
||||
remoteDir,
|
||||
timeoutMs: 30_000,
|
||||
operations: [
|
||||
{
|
||||
operationId: "op-dir",
|
||||
files: [
|
||||
{
|
||||
sourcePath: srcDir,
|
||||
targetPath: path.join(remoteDir, "dst"),
|
||||
kind: "directory",
|
||||
exclude: ["*.log"],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(await fs.readFile(path.join(remoteDir, "dst/keep.txt"), "utf-8")).toBe("keep");
|
||||
expect(await fs.readFile(path.join(remoteDir, "dst/sub/data.bin"), "utf-8")).toBe("data");
|
||||
// Exclude honored.
|
||||
await expect(fs.stat(path.join(remoteDir, "dst/skip.log"))).rejects.toThrow();
|
||||
}
|
||||
|
||||
// Dereference case: followSymlinks true → -h on the host tar-create.
|
||||
{
|
||||
const derefSrc = path.join(host, "deref");
|
||||
await fs.mkdir(derefSrc, { recursive: true });
|
||||
await fs.writeFile(path.join(derefSrc, "real.txt"), "realbytes");
|
||||
await fs.symlink(path.join(derefSrc, "real.txt"), path.join(derefSrc, "link.txt"));
|
||||
const derefTarget = await makeTmp("k8s-sandbox2-");
|
||||
const { exec } = makeRealExec();
|
||||
await performSyncIn({
|
||||
exec,
|
||||
remoteDir: derefTarget,
|
||||
timeoutMs: 30_000,
|
||||
operations: [
|
||||
{
|
||||
operationId: "op-deref",
|
||||
files: [
|
||||
{
|
||||
sourcePath: derefSrc,
|
||||
targetPath: path.join(derefTarget, "out"),
|
||||
kind: "directory",
|
||||
followSymlinks: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const linkStat = await fs.lstat(path.join(derefTarget, "out/link.txt"));
|
||||
// Dereferenced: the link became a regular file carrying the bytes.
|
||||
expect(linkStat.isSymbolicLink()).toBe(false);
|
||||
expect(await fs.readFile(path.join(derefTarget, "out/link.txt"), "utf-8")).toBe("realbytes");
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves a symlink as a link when followSymlinks is falsy", async () => {
|
||||
const remoteDir = await makeTmp("k8s-sandbox-");
|
||||
const host = await makeTmp("k8s-host-");
|
||||
const src = path.join(host, "tree");
|
||||
await fs.mkdir(src, { recursive: true });
|
||||
await fs.writeFile(path.join(src, "real.txt"), "realbytes");
|
||||
await fs.symlink("real.txt", path.join(src, "link.txt"));
|
||||
|
||||
const { exec } = makeRealExec();
|
||||
await performSyncIn({
|
||||
exec,
|
||||
remoteDir,
|
||||
timeoutMs: 30_000,
|
||||
operations: [
|
||||
{
|
||||
operationId: "op",
|
||||
files: [{ sourcePath: src, targetPath: path.join(remoteDir, "out"), kind: "directory" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
const linkStat = await fs.lstat(path.join(remoteDir, "out/link.txt"));
|
||||
expect(linkStat.isSymbolicLink()).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a file mapping whose target escapes the remote dir before any exec runs", async () => {
|
||||
const remoteDir = await makeTmp("k8s-sandbox-");
|
||||
const host = await makeTmp("k8s-host-");
|
||||
const src = path.join(host, "x.txt");
|
||||
await fs.writeFile(src, "x");
|
||||
const { exec, calls } = makeRealExec();
|
||||
await expect(
|
||||
performSyncIn({
|
||||
exec,
|
||||
remoteDir,
|
||||
timeoutMs: 30_000,
|
||||
operations: [
|
||||
{
|
||||
operationId: "op",
|
||||
files: [{ sourcePath: src, targetPath: `${remoteDir}/../escape.txt`, kind: "file" }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).rejects.toThrow(/escapes|not a confined/);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("refuses to create a target dir through a sandbox-planted symlink ancestor, mutating nothing outside the root (confine-before-mkdir)", async () => {
|
||||
const remoteDir = await makeTmp("k8s-sandbox-");
|
||||
const outside = await makeTmp("k8s-outside-");
|
||||
const host = await makeTmp("k8s-host-");
|
||||
const src = path.join(host, "x.txt");
|
||||
await fs.writeFile(src, "payload");
|
||||
// A sandbox process planted `evil` inside the workspace as a symlink to an
|
||||
// out-of-root dir. The target is LEXICALLY confined (no `..`), so only the
|
||||
// in-pod realpath guard can catch it — and it must catch it BEFORE mkdir -p
|
||||
// follows the link and creates the tree outside the root.
|
||||
await fs.symlink(outside, path.join(remoteDir, "evil"));
|
||||
|
||||
const { exec } = makeRealExec();
|
||||
await expect(
|
||||
performSyncIn({
|
||||
exec,
|
||||
remoteDir,
|
||||
timeoutMs: 30_000,
|
||||
operations: [
|
||||
{
|
||||
operationId: "op",
|
||||
files: [
|
||||
{ sourcePath: src, targetPath: path.join(remoteDir, "evil", "sub", "f.txt"), kind: "file" },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).rejects.toThrow(/ESCAPE|exit 42/);
|
||||
// The escape was rejected before mkdir ran: nothing was created outside root.
|
||||
await expect(fs.stat(path.join(outside, "sub"))).rejects.toThrow();
|
||||
expect(await fs.readdir(outside)).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses to extract a directory mapping through a symlink ancestor, mutating nothing outside the root", async () => {
|
||||
const remoteDir = await makeTmp("k8s-sandbox-");
|
||||
const outside = await makeTmp("k8s-outside-");
|
||||
const host = await makeTmp("k8s-host-");
|
||||
const srcDir = path.join(host, "tree");
|
||||
await fs.mkdir(srcDir, { recursive: true });
|
||||
await fs.writeFile(path.join(srcDir, "a.txt"), "aaa");
|
||||
await fs.symlink(outside, path.join(remoteDir, "evil"));
|
||||
|
||||
const { exec } = makeRealExec();
|
||||
await expect(
|
||||
performSyncIn({
|
||||
exec,
|
||||
remoteDir,
|
||||
timeoutMs: 30_000,
|
||||
operations: [
|
||||
{
|
||||
operationId: "op",
|
||||
files: [
|
||||
{ sourcePath: srcDir, targetPath: path.join(remoteDir, "evil", "dst"), kind: "directory" },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).rejects.toThrow(/ESCAPE|exit 42/);
|
||||
await expect(fs.stat(path.join(outside, "dst"))).rejects.toThrow();
|
||||
expect(await fs.readdir(outside)).toEqual([]);
|
||||
});
|
||||
|
||||
it("streams a payload with no in-memory cap: a file larger than the former 100 MB ceiling transfers in one exec", async () => {
|
||||
// The streaming transport moves raw tar bytes over stdin straight to disk, so
|
||||
// there is no whole-payload buffer to bound. A payload the old base64-buffered
|
||||
// transport would have rejected now transfers fine. We assert the shape (one
|
||||
// exec, byte-exact `head -c`) on a modestly large file — enough to prove the
|
||||
// path never accumulates the payload as a string.
|
||||
const remoteDir = await makeTmp("k8s-sandbox-");
|
||||
const host = await makeTmp("k8s-host-");
|
||||
const src = path.join(host, "big.bin");
|
||||
const payload = Buffer.alloc(2 * 1024 * 1024, 7); // 2 MiB
|
||||
await fs.writeFile(src, payload);
|
||||
const { exec, calls } = makeRealExec();
|
||||
const result = await performSyncIn({
|
||||
exec,
|
||||
remoteDir,
|
||||
timeoutMs: 30_000,
|
||||
operations: [
|
||||
{
|
||||
operationId: "op",
|
||||
files: [{ sourcePath: src, targetPath: path.join(remoteDir, "big.bin"), kind: "file" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0].script).toMatch(/head -c \d+/);
|
||||
const landed = await fs.readFile(path.join(remoteDir, "big.bin"));
|
||||
expect(landed.equals(payload)).toBe(true);
|
||||
expect(result.operations[0].bytesTransferred).toBe(payload.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe("kubernetes onEnvironmentSyncOut (native single-exec transfer)", () => {
|
||||
it("streams all file mappings back over a SINGLE exec and reassembles them at host targets, preserving mode and per-operation counts", async () => {
|
||||
const remoteDir = await makeTmp("k8s-sandbox-");
|
||||
const hostOut = await makeTmp("k8s-hostout-");
|
||||
// Simulate sandbox-side files.
|
||||
await fs.writeFile(path.join(remoteDir, "result.txt"), "computed output");
|
||||
await fs.writeFile(path.join(remoteDir, "secret.key"), "PRIVATE");
|
||||
await fs.chmod(path.join(remoteDir, "secret.key"), 0o600);
|
||||
|
||||
const plainTarget = path.join(hostOut, "a/result.txt");
|
||||
const secretTarget = path.join(hostOut, "b/secret.key");
|
||||
|
||||
const { exec, calls } = makeRealExec();
|
||||
const result = await performSyncOut({
|
||||
exec,
|
||||
remoteDir,
|
||||
timeoutMs: 30_000,
|
||||
operations: [
|
||||
{
|
||||
operationId: "op-out",
|
||||
files: [
|
||||
{ sourcePath: path.join(remoteDir, "result.txt"), targetPath: plainTarget, kind: "file" },
|
||||
{
|
||||
sourcePath: path.join(remoteDir, "secret.key"),
|
||||
targetPath: secretTarget,
|
||||
kind: "file",
|
||||
mode: 0o600,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(await fs.readFile(plainTarget, "utf-8")).toBe("computed output");
|
||||
expect(await fs.readFile(secretTarget, "utf-8")).toBe("PRIVATE");
|
||||
expect((await fs.stat(secretTarget)).mode & 0o777).toBe(0o600);
|
||||
expect(result.operations).toEqual([
|
||||
{ operationId: "op-out", filesTransferred: 2, bytesTransferred: expect.any(Number) },
|
||||
]);
|
||||
// Reserved snapshot scratch cleaned up from the workspace root.
|
||||
const leftovers = (await fs.readdir(remoteDir)).filter((e) => e.startsWith(".paperclip-upload"));
|
||||
expect(leftovers).toEqual([]);
|
||||
});
|
||||
|
||||
it("round-trips a directory back to the host, preserving a symlink when followSymlinks is falsy", async () => {
|
||||
const remoteDir = await makeTmp("k8s-sandbox-");
|
||||
const hostOut = await makeTmp("k8s-hostout-");
|
||||
const srcDir = path.join(remoteDir, "artifacts");
|
||||
await fs.mkdir(path.join(srcDir, "sub"), { recursive: true });
|
||||
await fs.writeFile(path.join(srcDir, "a.txt"), "aaa");
|
||||
await fs.writeFile(path.join(srcDir, "sub", "b.txt"), "bbb");
|
||||
await fs.symlink("a.txt", path.join(srcDir, "link.txt"));
|
||||
|
||||
const target = path.join(hostOut, "restored");
|
||||
const { exec, calls } = makeRealExec();
|
||||
const result = await performSyncOut({
|
||||
exec,
|
||||
remoteDir,
|
||||
timeoutMs: 30_000,
|
||||
operations: [
|
||||
{
|
||||
operationId: "op-dir-out",
|
||||
files: [{ sourcePath: srcDir, targetPath: target, kind: "directory" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(await fs.readFile(path.join(target, "a.txt"), "utf-8")).toBe("aaa");
|
||||
expect(await fs.readFile(path.join(target, "sub/b.txt"), "utf-8")).toBe("bbb");
|
||||
expect((await fs.lstat(path.join(target, "link.txt"))).isSymbolicLink()).toBe(true);
|
||||
expect(result.operations[0].filesTransferred).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it("rejects an outbound source that escapes the remote dir before any exec runs", async () => {
|
||||
const remoteDir = await makeTmp("k8s-sandbox-");
|
||||
const hostOut = await makeTmp("k8s-hostout-");
|
||||
const { exec, calls } = makeRealExec();
|
||||
await expect(
|
||||
performSyncOut({
|
||||
exec,
|
||||
remoteDir,
|
||||
timeoutMs: 30_000,
|
||||
operations: [
|
||||
{
|
||||
operationId: "op",
|
||||
files: [
|
||||
{ sourcePath: "/etc/passwd", targetPath: path.join(hostOut, "leak"), kind: "file" },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).rejects.toThrow(/escapes|not a confined/);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("snapshots the outbound source through a pinned FD (never re-opening by name) so a post-resolve replacement cannot redirect the copy", async () => {
|
||||
const remoteDir = await makeTmp("k8s-sandbox-");
|
||||
const hostOut = await makeTmp("k8s-hostout-");
|
||||
await fs.writeFile(path.join(remoteDir, "result.txt"), "computed output");
|
||||
const target = path.join(hostOut, "result.txt");
|
||||
|
||||
const { exec, calls } = makeRealExec();
|
||||
await performSyncOut({
|
||||
exec,
|
||||
remoteDir,
|
||||
timeoutMs: 30_000,
|
||||
operations: [
|
||||
{
|
||||
operationId: "op",
|
||||
files: [
|
||||
{ sourcePath: path.join(remoteDir, "result.txt"), targetPath: target, kind: "file" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
// Correct bytes copied — through the FD, not the name.
|
||||
expect(await fs.readFile(target, "utf-8")).toBe("computed output");
|
||||
// The copy reads the pinned FD, and the source is never re-opened by its
|
||||
// resolved name after validation (which is what the TOCTOU exploited).
|
||||
expect(calls[0].script).toContain("exec 7<");
|
||||
expect(calls[0].script).toContain("cp -- /proc/self/fd/7");
|
||||
expect(calls[0].script).not.toMatch(/cp -- "\$_pc_real"/);
|
||||
});
|
||||
|
||||
it("rejects an outbound source that is a symlink resolving outside the root, writing no target", async () => {
|
||||
const remoteDir = await makeTmp("k8s-sandbox-");
|
||||
const outside = await makeTmp("k8s-outside-");
|
||||
const hostOut = await makeTmp("k8s-hostout-");
|
||||
await fs.writeFile(path.join(outside, "secret"), "PRIVATE");
|
||||
// A symlink LEXICALLY inside the root that resolves to an out-of-root file —
|
||||
// only the in-pod realpath/FD guard can reject it.
|
||||
await fs.symlink(path.join(outside, "secret"), path.join(remoteDir, "link"));
|
||||
const target = path.join(hostOut, "leak");
|
||||
|
||||
const { exec } = makeRealExec();
|
||||
await expect(
|
||||
performSyncOut({
|
||||
exec,
|
||||
remoteDir,
|
||||
timeoutMs: 30_000,
|
||||
operations: [
|
||||
{
|
||||
operationId: "op",
|
||||
files: [{ sourcePath: path.join(remoteDir, "link"), targetPath: target, kind: "file" }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).rejects.toThrow(/ESCAPE|exit 42/);
|
||||
await expect(fs.stat(target)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("fails closed when the outbound payload exceeds the streamed-output disk guard, writing no target", async () => {
|
||||
const remoteDir = await makeTmp("k8s-sandbox-");
|
||||
const hostOut = await makeTmp("k8s-hostout-");
|
||||
await fs.writeFile(path.join(remoteDir, "result.txt"), "computed output");
|
||||
const target = path.join(hostOut, "result.txt");
|
||||
// The (untrusted) pod streams far more than a 1KB guard allows; the host must
|
||||
// trip the streamed-bytes guard and abort before it can fill the disk, never
|
||||
// extracting a target.
|
||||
const { exec, calls } = makeOutputExec(4096);
|
||||
await expect(
|
||||
performSyncOut({
|
||||
exec,
|
||||
remoteDir,
|
||||
timeoutMs: 30_000,
|
||||
maxOutputBytes: 1024,
|
||||
operations: [
|
||||
{
|
||||
operationId: "op",
|
||||
files: [
|
||||
{ sourcePath: path.join(remoteDir, "result.txt"), targetPath: target, kind: "file" },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).rejects.toThrow(/disk guard|exceeded/i);
|
||||
// The exec ran (source was confined), but the oversize stream is aborted, so
|
||||
// nothing lands at the host target.
|
||||
expect(calls).toHaveLength(1);
|
||||
await expect(fs.stat(target)).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
+34
@@ -81,6 +81,40 @@ describe("onEnvironmentResumeLease", () => {
|
||||
phase: "Running",
|
||||
backend: "sandbox-cr",
|
||||
resumedLease: true,
|
||||
// sandbox-cr has a pod-exec channel, so native file sync stays enabled.
|
||||
nativeFileSyncUnsupported: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("flags a resumed job-backend lease as native-sync-unsupported so the server keeps the base64 fallback", async () => {
|
||||
h.clients = {
|
||||
batch: {
|
||||
readNamespacedJobStatus: vi.fn().mockResolvedValue({ status: { active: 1 } }),
|
||||
},
|
||||
core: {
|
||||
listNamespacedPod: vi.fn().mockResolvedValue({
|
||||
items: [{ metadata: { name: "pc-job-pod" }, status: { phase: "Running" } }],
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
const lease = await plugin.definition.onEnvironmentResumeLease!({
|
||||
driverKey: "kubernetes",
|
||||
companyId: "acme",
|
||||
environmentId: "env-1",
|
||||
config: { inCluster: true, backend: "job" },
|
||||
providerLeaseId: "pc-job",
|
||||
leaseMetadata: leaseMetadata({ jobName: "pc-job", backend: "job", podName: "pc-job-pod" }),
|
||||
});
|
||||
|
||||
expect(lease.providerLeaseId).toBe("pc-job");
|
||||
expect(lease.metadata).toEqual(
|
||||
expect.objectContaining({
|
||||
backend: "job",
|
||||
// The job backend has no exec channel; its native sync hook rejects, so
|
||||
// the lease must fall back to the byte-identical base64 transport.
|
||||
nativeFileSyncUnsupported: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -91,4 +91,41 @@ describe("plugin", () => {
|
||||
expect(result.ok).toBe(true);
|
||||
expect(result.warnings).toBeUndefined();
|
||||
});
|
||||
|
||||
// Defining both hooks is what makes the worker advertise the
|
||||
// `environmentSyncIn`/`environmentSyncOut` verbs; the host runner then flips
|
||||
// K8s to native single-exec transfer. Absent them, the base64 fallback stays.
|
||||
it("defines the opt-in native file-sync hooks", () => {
|
||||
expect(plugin.definition.onEnvironmentSyncIn).toBeTypeOf("function");
|
||||
expect(plugin.definition.onEnvironmentSyncOut).toBeTypeOf("function");
|
||||
});
|
||||
|
||||
it("file sync fails loud when the lease carries no workspace remote dir", async () => {
|
||||
await expect(
|
||||
plugin.definition.onEnvironmentSyncIn!({
|
||||
driverKey: "kubernetes",
|
||||
companyId: "co",
|
||||
environmentId: "env",
|
||||
config: { inCluster: true },
|
||||
lease: { providerLeaseId: "lease-1", metadata: {} },
|
||||
operations: [],
|
||||
}),
|
||||
).rejects.toThrow(/workspace remote dir/);
|
||||
});
|
||||
|
||||
it("file sync rejects the job backend (out of scope; sandbox-cr only)", async () => {
|
||||
await expect(
|
||||
plugin.definition.onEnvironmentSyncOut!({
|
||||
driverKey: "kubernetes",
|
||||
companyId: "co",
|
||||
environmentId: "env",
|
||||
config: { inCluster: true },
|
||||
lease: {
|
||||
providerLeaseId: "lease-1",
|
||||
metadata: { remoteCwd: "/workspace", backend: "job", namespace: "paperclip-co" },
|
||||
},
|
||||
operations: [],
|
||||
}),
|
||||
).rejects.toThrow(/only supported on the sandbox-cr backend/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,238 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { Readable, Writable } from "node:stream";
|
||||
import type { PassThrough } from "node:stream";
|
||||
|
||||
// Mock the k8s client so `execInPod` runs against a scripted WebSocket exec: the
|
||||
// fake `Exec.exec` streams stdout chunks into the provided PassThrough and, for
|
||||
// the success path, reports an exit status. This exercises the host-side stdout
|
||||
// accumulation cap without a real cluster.
|
||||
type StatusCb = (status: {
|
||||
status: string;
|
||||
details?: { causes?: { reason?: string; message?: string }[] };
|
||||
}) => void;
|
||||
|
||||
let scriptedExec: (
|
||||
stdout: PassThrough,
|
||||
stderr: PassThrough,
|
||||
statusCb: StatusCb,
|
||||
stdin: PassThrough | null,
|
||||
) => void = () => undefined;
|
||||
|
||||
vi.mock("@kubernetes/client-node", () => {
|
||||
class Exec {
|
||||
constructor(_kc: unknown) {}
|
||||
async exec(
|
||||
_namespace: string,
|
||||
_podName: string,
|
||||
_containerName: string,
|
||||
_command: string[],
|
||||
stdout: PassThrough,
|
||||
stderr: PassThrough,
|
||||
stdin: PassThrough | null,
|
||||
_tty: boolean,
|
||||
statusCb: StatusCb,
|
||||
) {
|
||||
// Defer so the caller has wired its stream listeners first.
|
||||
setImmediate(() => scriptedExec(stdout, stderr, statusCb, stdin));
|
||||
return { close() {} };
|
||||
}
|
||||
}
|
||||
return { Exec };
|
||||
});
|
||||
|
||||
const { execInPod, execInPodStreaming } = await import("../../src/pod-exec.js");
|
||||
|
||||
const KC = {} as never;
|
||||
|
||||
describe("execInPod stdout cap", () => {
|
||||
it("fails closed when pod stdout exceeds the cap", async () => {
|
||||
scriptedExec = (stdout) => {
|
||||
// Emit more than the cap in a single chunk; the host must reject.
|
||||
stdout.write(Buffer.alloc(64, 0x41));
|
||||
};
|
||||
await expect(
|
||||
execInPod(KC, "ns", "pod", "agent", ["/bin/sh", "-c", ":"], undefined, 5_000, 16),
|
||||
).rejects.toThrow(/cap|exceeded/i);
|
||||
});
|
||||
|
||||
it("accepts stdout within the cap and returns the accumulated output", async () => {
|
||||
scriptedExec = (stdout, stderr, statusCb) => {
|
||||
stdout.write(Buffer.from("hello", "utf-8"));
|
||||
stdout.end();
|
||||
stderr.end();
|
||||
statusCb({ status: "Success" });
|
||||
};
|
||||
const result = await execInPod(
|
||||
KC,
|
||||
"ns",
|
||||
"pod",
|
||||
"agent",
|
||||
["/bin/sh", "-c", ":"],
|
||||
undefined,
|
||||
5_000,
|
||||
1024,
|
||||
);
|
||||
expect(result).toEqual({ exitCode: 0, stdout: "hello", stderr: "" });
|
||||
});
|
||||
|
||||
it("leaves stdout unbounded when no cap is provided", async () => {
|
||||
scriptedExec = (stdout, stderr, statusCb) => {
|
||||
stdout.write(Buffer.alloc(4096, 0x42));
|
||||
stdout.end();
|
||||
stderr.end();
|
||||
statusCb({ status: "Success" });
|
||||
};
|
||||
const result = await execInPod(
|
||||
KC,
|
||||
"ns",
|
||||
"pod",
|
||||
"agent",
|
||||
["/bin/sh", "-c", ":"],
|
||||
undefined,
|
||||
5_000,
|
||||
);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toHaveLength(4096);
|
||||
});
|
||||
});
|
||||
|
||||
describe("execInPod stderr cap", () => {
|
||||
it("fails closed when pod stderr exceeds the cap", async () => {
|
||||
// stderr is equally pod-controlled: a malicious pod that floods stderr must
|
||||
// not grow the host accumulator without bound. Same DoS class as stdout.
|
||||
scriptedExec = (_stdout, stderr) => {
|
||||
stderr.write(Buffer.alloc(64, 0x45));
|
||||
};
|
||||
await expect(
|
||||
// maxStdoutBytes generous, maxStderrBytes = 16 -> stderr must trip.
|
||||
execInPod(KC, "ns", "pod", "agent", ["/bin/sh", "-c", ":"], undefined, 5_000, 1024, 16),
|
||||
).rejects.toThrow(/stderr.*cap|cap.*stderr|exceeded/i);
|
||||
});
|
||||
|
||||
it("accepts stderr within the cap and returns the accumulated output", async () => {
|
||||
scriptedExec = (stdout, stderr, statusCb) => {
|
||||
stderr.write(Buffer.from("warn", "utf-8"));
|
||||
stdout.end();
|
||||
stderr.end();
|
||||
statusCb({ status: "Success" });
|
||||
};
|
||||
const result = await execInPod(
|
||||
KC,
|
||||
"ns",
|
||||
"pod",
|
||||
"agent",
|
||||
["/bin/sh", "-c", ":"],
|
||||
undefined,
|
||||
5_000,
|
||||
1024,
|
||||
1024,
|
||||
);
|
||||
expect(result).toEqual({ exitCode: 0, stdout: "", stderr: "warn" });
|
||||
});
|
||||
|
||||
it("leaves stderr unbounded when no cap is provided", async () => {
|
||||
scriptedExec = (stdout, stderr, statusCb) => {
|
||||
stderr.write(Buffer.alloc(4096, 0x46));
|
||||
stdout.end();
|
||||
stderr.end();
|
||||
statusCb({ status: "Success" });
|
||||
};
|
||||
const result = await execInPod(
|
||||
KC,
|
||||
"ns",
|
||||
"pod",
|
||||
"agent",
|
||||
["/bin/sh", "-c", ":"],
|
||||
undefined,
|
||||
5_000,
|
||||
1024,
|
||||
);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).toHaveLength(4096);
|
||||
});
|
||||
});
|
||||
|
||||
describe("execInPodStreaming", () => {
|
||||
it("streams the command's stdout into the caller sink and resolves with exit code + stderr", async () => {
|
||||
scriptedExec = (stdout, stderr, statusCb) => {
|
||||
stdout.write(Buffer.from("chunk-one;"));
|
||||
stdout.write(Buffer.from("chunk-two"));
|
||||
stdout.end();
|
||||
stderr.write(Buffer.from("warn"));
|
||||
stderr.end();
|
||||
statusCb({ status: "Success" });
|
||||
};
|
||||
const chunks: Buffer[] = [];
|
||||
const sink = new Writable({
|
||||
write(chunk: Buffer, _enc, cb) {
|
||||
chunks.push(Buffer.from(chunk));
|
||||
cb();
|
||||
},
|
||||
});
|
||||
const result = await execInPodStreaming(KC, "ns", "pod", "agent", ["/bin/sh", "-c", ":"], {
|
||||
stdout: sink,
|
||||
timeoutMs: 5_000,
|
||||
});
|
||||
expect(result).toEqual({ exitCode: 0, stderr: "warn" });
|
||||
expect(Buffer.concat(chunks).toString("utf-8")).toBe("chunk-one;chunk-two");
|
||||
});
|
||||
|
||||
it("streams the caller stdin Readable into the pod command", async () => {
|
||||
let received = Buffer.alloc(0);
|
||||
scriptedExec = (stdout, stderr, statusCb, stdin) => {
|
||||
if (stdin) {
|
||||
stdin.on("data", (chunk: Buffer) => {
|
||||
received = Buffer.concat([received, chunk]);
|
||||
});
|
||||
}
|
||||
// Resolve once the source has been fully piped through.
|
||||
setImmediate(() => {
|
||||
stdout.end();
|
||||
stderr.end();
|
||||
statusCb({ status: "Success" });
|
||||
});
|
||||
};
|
||||
const source = Readable.from([Buffer.from("payload-bytes")]);
|
||||
const result = await execInPodStreaming(KC, "ns", "pod", "agent", ["/bin/sh", "-c", ":"], {
|
||||
stdin: source,
|
||||
timeoutMs: 5_000,
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(received.toString("utf-8")).toBe("payload-bytes");
|
||||
});
|
||||
|
||||
it("fails closed when the pod floods stderr past the cap", async () => {
|
||||
scriptedExec = (_stdout, stderr) => {
|
||||
stderr.write(Buffer.alloc(64, 0x45));
|
||||
};
|
||||
const sink = new Writable({ write(_c, _e, cb) { cb(); } });
|
||||
await expect(
|
||||
execInPodStreaming(KC, "ns", "pod", "agent", ["/bin/sh", "-c", ":"], {
|
||||
stdout: sink,
|
||||
timeoutMs: 5_000,
|
||||
maxStderrBytes: 16,
|
||||
}),
|
||||
).rejects.toThrow(/stderr.*cap|exceeded/i);
|
||||
});
|
||||
|
||||
it("fails closed when the caller sink errors (e.g. a streamed-bytes disk guard trips)", async () => {
|
||||
scriptedExec = (stdout, stderr, statusCb) => {
|
||||
stdout.write(Buffer.alloc(4096, 0x42));
|
||||
stdout.end();
|
||||
stderr.end();
|
||||
statusCb({ status: "Success" });
|
||||
};
|
||||
// A sink that rejects any write, standing in for the file-sync disk guard.
|
||||
const sink = new Writable({
|
||||
write(_chunk, _enc, cb) {
|
||||
cb(new Error("streamed-output disk guard tripped"));
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
execInPodStreaming(KC, "ns", "pod", "agent", ["/bin/sh", "-c", ":"], {
|
||||
stdout: sink,
|
||||
timeoutMs: 5_000,
|
||||
}),
|
||||
).rejects.toThrow(/disk guard/i);
|
||||
});
|
||||
});
|
||||
@@ -1289,7 +1289,26 @@ function createSandboxEnvironmentDriver(
|
||||
const pluginId = readString(input.lease.metadata?.pluginId);
|
||||
if (!pluginId) return false;
|
||||
const advertised = pluginWorkerManager.getWorker(pluginId)?.supportedMethods ?? [];
|
||||
return advertised.includes("environmentSyncIn") && advertised.includes("environmentSyncOut");
|
||||
if (!advertised.includes("environmentSyncIn") || !advertised.includes("environmentSyncOut")) {
|
||||
return false;
|
||||
}
|
||||
// A worker advertises the sync verbs process-wide, but an individual lease
|
||||
// may run on a backend that has no data channel for the native transport
|
||||
// (e.g. a batch/job backend whose sync hook rejects immediately). The
|
||||
// provider flags such leases so they keep the byte-identical base64
|
||||
// fallback instead of being routed to a hook that would only error.
|
||||
//
|
||||
// Also fall back for any lease persisted with `backend: "job"` directly:
|
||||
// job leases created before `nativeFileSyncUnsupported` existed carry the
|
||||
// backend field but not the flag, and the `job` backend has no pod-exec
|
||||
// channel, so routing them to the native hook would only reject.
|
||||
if (
|
||||
input.lease.metadata?.nativeFileSyncUnsupported === true ||
|
||||
input.lease.metadata?.backend === "job"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
|
||||
async syncIn(input) {
|
||||
|
||||
Reference in new issue
Block a user