From e3af094fb4bbbc07ec49bbaef576cfc50c7bcb00 Mon Sep 17 00:00:00 2001 From: Mikei386 <44135113+Mikei386@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:04:16 +0100 Subject: [PATCH] fix: bound process output memory and HTTP request bodies --- README.md | 23 +++++++++ scripts/memory-benchmark.ts | 13 +++++ src/admin.test.ts | 19 +++++++- src/helpers.ts | 91 +++++++++++++++-------------------- src/index.ts | 4 ++ src/output-regression.test.ts | 29 +++++++++++ src/process-output.test.ts | 69 ++++++++++++++++++++++++++ src/process-output.ts | 65 +++++++++++++++++++++++++ 8 files changed, 259 insertions(+), 54 deletions(-) create mode 100644 scripts/memory-benchmark.ts create mode 100644 src/output-regression.test.ts create mode 100644 src/process-output.test.ts create mode 100644 src/process-output.ts diff --git a/README.md b/README.md index 7f038df..b4623ef 100644 --- a/README.md +++ b/README.md @@ -331,6 +331,29 @@ bash scripts/package.sh ### Lokaler Test +#### Speicherbegrenzung + +MUA begrenzt Befehlsausgaben bereits beim Lesen der Prozess-Pipes. Das +Shell-Werkzeug behält höchstens die letzten 100.000 Bytes von stdout und +20.000 Bytes von stderr. Größere Ausgaben werden weiter konsumiert, ohne +sie vollständig zu speichern oder den Befehl wegen der Ausgabelänge zu +beenden. `truncated`, `stdout_bytes` und `stderr_bytes` zeigen an, ob und +wie viel Ausgabe gekürzt wurde. + +Interne Befehle, deren Ausgabe anschließend strukturiert ausgewertet wird, +haben ein Budget von 1 MiB stdout und 64 KiB stderr. Bei Überschreitung +liefert MUA `OUTPUT_LIMIT` statt unvollständiger Daten. Timeouts geben auch +offene Pipe-Leser frei. Die HTTP-Grenze `MUA_MAX_REQUEST_BYTES` wird bereits +beim Empfang durchgesetzt, auch bei Anfragen ohne `Content-Length`. + +Die Regressionstests und ein rein synthetischer Speichertest laufen lokal, +ohne NAS-Verbindung: + +```bash +bun test +bun scripts/memory-benchmark.ts 64 +``` + Die PHP-Statushelper lassen sich unabhängig vom laufenden MUA-Dienst testen (PHP 8 erforderlich): diff --git a/scripts/memory-benchmark.ts b/scripts/memory-benchmark.ts new file mode 100644 index 0000000..31c4da6 --- /dev/null +++ b/scripts/memory-benchmark.ts @@ -0,0 +1,13 @@ +import { runShell } from "../src/helpers"; + +// Isolated synthetic producer. No NAS, network access or host file content. +const mib = Number(process.argv[2] ?? 64); +if (!Number.isInteger(mib) || mib < 1 || mib > 128) throw new Error("Use 1..128 MiB"); +const before = process.memoryUsage(); +const result = JSON.parse(await runShell(`head -c ${mib * 1024 * 1024} /dev/zero | tr '\\000' x`, 30)); +const after = process.memoryUsage(); +Bun.gc(true); +console.log(JSON.stringify({ + runtime: Bun.version, produced_mib: mib, returned_chars: result.stdout.length, + truncated: result.truncated ?? null, before, after, after_gc: process.memoryUsage(), +})); diff --git a/src/admin.test.ts b/src/admin.test.ts index 2a279c8..d3e2626 100644 --- a/src/admin.test.ts +++ b/src/admin.test.ts @@ -42,7 +42,7 @@ test("actual MCP transport advertises new tools and marks failed commands as err const token = crypto.randomUUID(); const child = Bun.spawn([process.execPath, fileURLToPath(new URL("./index.ts", import.meta.url))], { env: { ...process.env, MUA_HOST: "127.0.0.1", MUA_PORT: "39871", MUA_CONFIG_PORT: "39872", MUA_API_KEY: token, - MUA_ENABLED_TOOLS: "all", MUA_CONFIG_DIR: root, MUA_ADMIN_TOKEN_FILE: `${root}/admin.token`, MUA_AUDIT_LOG: `${root}/audit.log` }, + MUA_ENABLED_TOOLS: "all", MUA_MAX_REQUEST_BYTES: "16384", MUA_CONFIG_DIR: root, MUA_ADMIN_TOKEN_FILE: `${root}/admin.token`, MUA_AUDIT_LOG: `${root}/audit.log` }, stdout: "ignore", stderr: "ignore", }); try { @@ -70,6 +70,23 @@ test("actual MCP transport advertises new tools and marks failed commands as err expect(fail.result.structuredContent.exit_code).toBe(17); const denied = await rpc("tools/call", { name: "unraid_share_apply", arguments: { approval_ticket: "invalid", confirm: true } }); expect(denied.result.isError).toBe(true); + + // An oversized chunked upload must be rejected before its producer ends. + // Content-Length checks or trimming after req.text() are insufficient. + const abort = new AbortController(); + const timer = setTimeout(() => abort.abort(), 2000); + try { + const oversized = await fetch("http://127.0.0.1:39871/mcp", { + method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, + body: new ReadableStream({ start(controller) { controller.enqueue(new Uint8Array(16385)); } }), + signal: abort.signal, + }); + expect(oversized.status).toBe(413); + await oversized.body?.cancel(); + } finally { + clearTimeout(timer); + abort.abort(); + } } finally { child.kill(); await child.exited; rmSync(root, { recursive: true, force: true }); diff --git a/src/helpers.ts b/src/helpers.ts index 82af9a4..cba23c3 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -13,6 +13,7 @@ import { createConnection, type Socket } from "net"; import { hostname } from "node:os"; import { createHash, randomUUID } from "node:crypto"; import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { readProcessOutput } from "./process-output"; // ── Konstanten ────────────────────────────────────────────────────────── export const MUA_SERVER_NAME = "mua"; @@ -34,6 +35,7 @@ async function awaitProcess( stderr: Promise, timeoutSec: number, label: string, + outputAbort: AbortController, ): Promise<[TStdout, TStderr, number]> { const completion = Promise.all([stdout, stderr, proc.exited]) as Promise< [TStdout, TStderr, number] @@ -57,6 +59,9 @@ async function awaitProcess( return await Promise.race([completion, timeout]); } finally { if (timer !== undefined) clearTimeout(timer); + // A timeout must release both pipe readers, including pipes inherited by + // a descendant after the original shell has exited. + outputAbort.abort(); } } @@ -72,7 +77,9 @@ export function executionFailure(error: unknown, phase: string, timeoutSec: numb return { error: "local_process_failure", execution: localExecutionContext(), phase, cause: timedOut ? `timed out after ${timeoutSec} seconds` : code, connection_failure: false, - explanation: "Local process error; not evidence of a failed host connection or login. No command or credentials included." }; + explanation: code === "OUTPUT_LIMIT" + ? "Command output exceeded the capture budget (stdout 1 MiB, stderr 64 KiB). Narrow the command or request a bounded tail. No partial structured result returned." + : "Local process error; not evidence of a failed host connection or login. No command or credentials included." }; } /** @@ -92,16 +99,21 @@ export async function runLocal( cwd: "/", }); phase = "execution"; + const outputAbort = new AbortController(); const [stdout, stderr, code] = await awaitProcess( proc, - new Response(proc.stdout).text(), - new Response(proc.stderr).text(), + readProcessOutput(proc.stdout, 1_048_576, { stopOnLimit: false, signal: outputAbort.signal }), + readProcessOutput(proc.stderr, 65_536, { stopOnLimit: false, signal: outputAbort.signal }), timeoutSec, label, + outputAbort, ); + if (stdout.truncated || stderr.truncated) { + throw Object.assign(new Error("Command output exceeded capture budget"), { code: "OUTPUT_LIMIT" }); + } if (code !== 0) throw Object.assign(new Error("Command exited unsuccessfully"), { code: `COMMAND_EXIT_${code}` }); - let result = stdout.trim(); - if (result === "" && stderr.trim() !== "") result = stderr.trim(); + let result = stdout.text.trim(); + if (result === "" && stderr.text.trim() !== "") result = stderr.text.trim(); return result; } catch (e) { throw new Error(JSON.stringify(executionFailure(e, phase, timeoutSec))); @@ -122,18 +134,23 @@ export async function runShell(cmd: string, timeoutSec = 60): Promise { cwd: "/", }); phase = "execution"; + const outputAbort = new AbortController(); const [stdout, stderr, code] = await awaitProcess( proc, - new Response(proc.stdout).text(), - new Response(proc.stderr).text(), + readProcessOutput(proc.stdout, 100_000, { mode: "tail", stopOnLimit: false, signal: outputAbort.signal }), + readProcessOutput(proc.stderr, 20_000, { mode: "tail", stopOnLimit: false, signal: outputAbort.signal }), timeoutSec, "run_shell", + outputAbort, ); return JSON.stringify({ exit_code: code, execution: localExecutionContext(), - stdout: sanitizeLogOutput(stdout.trim(), 100000), - stderr: sanitizeLogOutput(stderr.trim(), 20000), + stdout: (stdout.truncated ? "... [truncated] ..." : "") + sanitizeLogOutput(stdout.text.trim(), 100000), + stderr: (stderr.truncated ? "... [truncated] ..." : "") + sanitizeLogOutput(stderr.text.trim(), 20000), + truncated: stdout.truncated || stderr.truncated, + stdout_bytes: stdout.bytesRead, + stderr_bytes: stderr.bytesRead, }); } catch (e) { throw new Error(JSON.stringify(executionFailure(e, phase, timeoutSec))); @@ -230,8 +247,9 @@ async function runArgv( ): Promise { try { const proc = spawn(argv, { stdout: "pipe", stderr: "pipe", cwd: "/" }); - const stdoutPromise = readStreamLimited(proc.stdout, maxStdout); - const stderrPromise = readStreamLimited(proc.stderr, maxStderr); + const outputAbort = new AbortController(); + const stdoutPromise = readProcessOutput(proc.stdout, maxStdout, { signal: outputAbort.signal }); + const stderrPromise = readProcessOutput(proc.stderr, maxStderr, { signal: outputAbort.signal }); stopProcessWhenTruncated(proc, stdoutPromise); stopProcessWhenTruncated(proc, stderrPromise); const [stdout, stderr, code] = await awaitProcess( @@ -240,6 +258,7 @@ async function runArgv( stderrPromise, timeoutSec, label, + outputAbort, ); if (code !== 0) { throw new Error(`${label} failed (exit ${code}): ${sanitizeLogOutput(stderr.text || stdout.text, maxStderr)}`); @@ -257,44 +276,6 @@ const READ_ONLY_PROGRAMS = new Set([ "uptime", "wc", "whoami", ]); -async function readStreamLimited( - stream: ReadableStream, - maxBytes: number, -): Promise<{ text: string; truncated: boolean }> { - const reader = stream.getReader(); - const chunks: Uint8Array[] = []; - let kept = 0; - let truncated = false; - while (true) { - const { done, value } = await reader.read(); - if (done) break; - const available = Math.max(0, maxBytes - kept); - if (kept < maxBytes) { - const slice = value.subarray(0, available); - if (slice.length > 0) chunks.push(slice); - kept += slice.length; - } - if (value.length > available) { - truncated = true; - // Do not keep draining an unbounded producer after the configured - // output budget is full. Closing the pipe also helps the producer exit. - try { - await reader.cancel(); - } catch { - // The process may close the stream concurrently. - } - break; - } - } - const combined = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0)); - let offset = 0; - for (const chunk of chunks) { - combined.set(chunk, offset); - offset += chunk.length; - } - return { text: new TextDecoder().decode(combined), truncated }; -} - function stopProcessWhenTruncated( proc: { kill: () => void }, output: Promise<{ text: string; truncated: boolean }>, @@ -372,8 +353,9 @@ export async function runReadOnlyCommand( try { const proc = spawn([program, ...args], { stdout: "pipe", stderr: "pipe", cwd: "/" }); - const stdoutPromise = readStreamLimited(proc.stdout, maxOutputChars); - const stderrPromise = readStreamLimited(proc.stderr, Math.min(8_000, maxOutputChars)); + const outputAbort = new AbortController(); + const stdoutPromise = readProcessOutput(proc.stdout, maxOutputChars, { signal: outputAbort.signal }); + const stderrPromise = readProcessOutput(proc.stderr, Math.min(8_000, maxOutputChars), { signal: outputAbort.signal }); stopProcessWhenTruncated(proc, stdoutPromise); stopProcessWhenTruncated(proc, stderrPromise); const [stdout, stderr, code] = await awaitProcess( @@ -382,6 +364,7 @@ export async function runReadOnlyCommand( stderrPromise, timeoutSec, `read-only ${program}`, + outputAbort, ); return JSON.stringify({ exit_code: code, @@ -515,8 +498,9 @@ export async function toolboxExec( ["/usr/bin/docker", "exec", selected.name, "/bin/sh", "-lc", command], { stdout: "pipe", stderr: "pipe", cwd: "/" }, ); - const stdoutPromise = readStreamLimited(proc.stdout, 100_000); - const stderrPromise = readStreamLimited(proc.stderr, 20_000); + const outputAbort = new AbortController(); + const stdoutPromise = readProcessOutput(proc.stdout, 100_000, { signal: outputAbort.signal }); + const stderrPromise = readProcessOutput(proc.stderr, 20_000, { signal: outputAbort.signal }); stopProcessWhenTruncated(proc, stdoutPromise); stopProcessWhenTruncated(proc, stderrPromise); const [stdout, stderr, code] = await awaitProcess( @@ -525,6 +509,7 @@ export async function toolboxExec( stderrPromise, timeoutSec, `toolbox ${selected.name}`, + outputAbort, ); return JSON.stringify({ container: selected.name, diff --git a/src/index.ts b/src/index.ts index 815429e..ec022a0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -287,6 +287,9 @@ const server = Bun.serve({ port: PORT, hostname: HOST, idleTimeout: 120, // Sekunden (für lange docker stats / audit) + // Enforce the limit while receiving, including chunked uploads without + // Content-Length. Checking after req.text() is too late to bound memory. + maxRequestBodySize: MAX_REQUEST_BYTES, async fetch(req) { const url = new URL(req.url); const path = url.pathname; @@ -459,6 +462,7 @@ try { port: CONFIG_PORT, hostname: "127.0.0.1", // nur localhost idleTimeout: 30, + maxRequestBodySize: MAX_REQUEST_BYTES, async fetch(req) { const url = new URL(req.url); const path = url.pathname; diff --git a/src/output-regression.test.ts b/src/output-regression.test.ts new file mode 100644 index 0000000..b231ff2 --- /dev/null +++ b/src/output-regression.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, test } from "bun:test"; +import { runLocal, runShell } from "./helpers"; + +// Synthetic output only: these commands never read host files or contact Unraid. +const largeOutput = "head -c 8388608 /dev/zero | tr '\\000' x"; + +describe("bounded command output", () => { + test("shell retains the tail, reports truncation and lets the command finish", async () => { + const result = JSON.parse(await runShell(`${largeOutput}; printf '\\ncommand-completed'`, 5)); + expect(result.exit_code).toBe(0); + expect(result.truncated).toBe(true); + expect(result.stdout_bytes).toBe(8_388_608 + 18); + expect(result.stdout.length).toBeLessThanOrEqual(100_020); + expect(result.stdout.endsWith("command-completed")).toBe(true); + }); + + test("shell bounds stderr independently and preserves the exit status", async () => { + const result = JSON.parse(await runShell(`(${largeOutput}; printf '\\nerror-completed') >&2; exit 17`, 5)); + expect(result.exit_code).toBe(17); + expect(result.truncated).toBe(true); + expect(result.stderr.length).toBeLessThanOrEqual(20_020); + expect(result.stderr.endsWith("error-completed")).toBe(true); + expect(result.stdout).toBe(""); + }); + + test("structured command helpers reject oversized output instead of returning partial data", async () => { + await expect(runLocal("synthetic-output", largeOutput, 5)).rejects.toThrow("OUTPUT_LIMIT"); + }); +}); diff --git a/src/process-output.test.ts b/src/process-output.test.ts new file mode 100644 index 0000000..72d6f29 --- /dev/null +++ b/src/process-output.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, test } from "bun:test"; +import { readProcessOutput } from "./process-output"; + +function source(parts: string[], onCancel = () => {}) { + const encoder = new TextEncoder(); + return new ReadableStream({ + start(controller) { + for (const part of parts) controller.enqueue(encoder.encode(part)); + controller.close(); + }, + cancel: onCancel, + }); +} + +describe("bounded pipe capture", () => { + test("preserves small UTF-8 output across chunk boundaries", async () => { + const bytes = new TextEncoder().encode("Grüße"); + const stream = new ReadableStream({ start(controller) { + for (const byte of bytes) controller.enqueue(Uint8Array.of(byte)); + controller.close(); + } }); + expect(await readProcessOutput(stream, bytes.length)).toEqual({ text: "Grüße", truncated: false, bytesRead: bytes.length }); + expect(stream.locked).toBe(false); + }); + + test("tail survives ring wraparound and oversized chunks", async () => { + for (const parts of [["ab", "cdef", "ghij", "kl"], ["abcdefghijkl"], ["abcdefghij", "kl"]]) { + expect(await readProcessOutput(source(parts), 5, { mode: "tail", stopOnLimit: false })).toEqual({ + text: "hijkl", truncated: true, bytesRead: 12, + }); + } + }); + + test("draining a bounded head consumes the whole stream without cancellation", async () => { + let cancelled = false; + expect(await readProcessOutput(source(["abcd", "efgh", "ijkl"], () => { cancelled = true; }), 5, { stopOnLimit: false })).toEqual({ + text: "abcde", truncated: true, bytesRead: 12, + }); + expect(cancelled).toBe(false); + }); + + test("read-only capture cancels a producer after the budget is exceeded", async () => { + let cancelled = false; + const stream = new ReadableStream({ + pull(controller) { controller.enqueue(new TextEncoder().encode("abcd")); }, + cancel() { cancelled = true; }, + }); + expect(await readProcessOutput(stream, 5)).toEqual({ text: "abcda", truncated: true, bytesRead: 8 }); + expect(cancelled).toBe(true); + expect(stream.locked).toBe(false); + }); + + test("abort cancels an idle pipe and releases its reader", async () => { + let cancelled = false; + const stream = new ReadableStream({ cancel() { cancelled = true; } }); + const abort = new AbortController(); + const pending = readProcessOutput(stream, 64, { stopOnLimit: false, signal: abort.signal }); + abort.abort(new Error("synthetic timeout")); + await expect(pending).rejects.toThrow("synthetic timeout"); + expect(cancelled).toBe(true); + expect(stream.locked).toBe(false); + }); + + test("stream failures release the reader", async () => { + const stream = new ReadableStream({ start(controller) { controller.error(new Error("synthetic failure")); } }); + await expect(readProcessOutput(stream, 64)).rejects.toThrow("synthetic failure"); + expect(stream.locked).toBe(false); + }); +}); diff --git a/src/process-output.ts b/src/process-output.ts new file mode 100644 index 0000000..0eaa8f0 --- /dev/null +++ b/src/process-output.ts @@ -0,0 +1,65 @@ +export interface ProcessOutput { + text: string; + truncated: boolean; + bytesRead: number; +} + +/** Keep a bounded head or tail while consuming a subprocess pipe. */ +export async function readProcessOutput( + stream: ReadableStream, + maxBytes: number, + options: { mode?: "head" | "tail"; stopOnLimit?: boolean; signal?: AbortSignal } = {}, +): Promise { + if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) { + throw new Error("Output budget must be a positive safe integer"); + } + const { mode = "head", stopOnLimit = true, signal } = options; + const reader = stream.getReader(); + const cancel = () => { void reader.cancel().catch(() => {}); }; + signal?.addEventListener("abort", cancel, { once: true }); + let buffer: Uint8Array | undefined; + let kept = 0; + let offset = 0; + let bytesRead = 0; + try { + if (signal?.aborted) cancel(); + signal?.throwIfAborted(); + while (true) { + const { done, value } = await reader.read(); + signal?.throwIfAborted(); + if (done) break; + if (value.length === 0) continue; + buffer ??= new Uint8Array(maxBytes); + bytesRead += value.length; + if (mode === "head") { + const part = value.subarray(0, Math.max(0, maxBytes - kept)); + buffer.set(part, kept); + kept += part.length; + } else if (value.length >= maxBytes) { + buffer.set(value.subarray(value.length - maxBytes)); + kept = maxBytes; + offset = 0; + } else { + const first = Math.min(value.length, maxBytes - offset); + buffer.set(value.subarray(0, first), offset); + buffer.set(value.subarray(first), 0); + offset = (offset + value.length) % maxBytes; + kept = Math.min(maxBytes, kept + value.length); + } + if (bytesRead > maxBytes && stopOnLimit) { + cancel(); + break; + } + } + let ordered = buffer?.subarray(0, kept) ?? new Uint8Array(0); + if (mode === "tail" && kept === maxBytes && offset > 0) { + ordered = new Uint8Array(kept); + ordered.set(buffer!.subarray(offset)); + ordered.set(buffer!.subarray(0, offset), maxBytes - offset); + } + return { text: new TextDecoder().decode(ordered), truncated: bytesRead > maxBytes, bytesRead }; + } finally { + signal?.removeEventListener("abort", cancel); + reader.releaseLock(); + } +}