File size: 8,817 Bytes
e249c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
// Bash executor tests cover bounded UTF-8 output and private sanitized spills.
import { readFile, rm, stat } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { executeBashWithOperations } from "./bash-executor.js";
import {
  expectNativeBashSpill,
  nativeBashSpillScenarios,
} from "./bash-output-spill.test-support.js";
import type { BashOperations } from "./tools/bash-operations.js";
import { DEFAULT_MAX_BYTES } from "./tools/truncate.js";

type OutputChunk = readonly [data: Buffer, stream?: "stdout" | "stderr"];

const ESC = String.fromCharCode(27);

function operationsForChunks(chunks: readonly OutputChunk[]): BashOperations {
  return {
    exec: async (_command, _cwd, options) => {
      for (const [data, stream] of chunks) {
        options.onData(data, stream);
      }
      return { exitCode: 0 };
    },
  };
}

describe("executeBashWithOperations", () => {
  it.runIf(process.platform !== "win32").each(nativeBashSpillScenarios)(
    "settles real Bash output for %s",
    async (scenario) => {
      await expectNativeBashSpill("executor", scenario);
    },
  );

  it("stores truncated full output in an owner-only temp file", async () => {
    const sanitizedOutput = "secret output\n".repeat(9000);
    const operations: BashOperations = {
      exec: async (_command, _cwd, options) => {
        options.onData(Buffer.from("\u001b[31msecret output\u001b[0m\n".repeat(9000)));
        return { exitCode: 0 };
      },
    };

    const result = await executeBashWithOperations("echo secret", "/tmp", operations);

    expect(result.truncated).toBe(true);
    expect(result.fullOutputPath).toBeDefined();
    // Full output can include secrets printed by a command, so the spill file
    // must be unreadable by group/other accounts.
    const mode = (await stat(result.fullOutputPath!)).mode & 0o777;
    expect(mode & 0o077).toBe(0);
    expect(await readFile(result.fullOutputPath!, "utf8")).toBe(sanitizedOutput);
    await rm(result.fullOutputPath!, { force: true });
  });

  it("preserves the exact UTF-8 tail across output chunk boundaries", async () => {
    const asciiChunk = "a".repeat(80 * 1024);
    const multibyteChunk = "界".repeat(10 * 1024);
    const expectedAsciiBytes = DEFAULT_MAX_BYTES - Buffer.byteLength(multibyteChunk, "utf8");
    const operations: BashOperations = {
      exec: async (_command, _cwd, options) => {
        options.onData(Buffer.from(asciiChunk));
        options.onData(Buffer.from(multibyteChunk));
        return { exitCode: 0 };
      },
    };

    const result = await executeBashWithOperations("printf output", "/tmp", operations);

    expect(result.truncated).toBe(true);
    expect(result.fullOutputPath).toBeDefined();
    expect(Buffer.byteLength(result.output, "utf8")).toBe(DEFAULT_MAX_BYTES);
    expect(result.output).toBe("a".repeat(expectedAsciiBytes) + multibyteChunk);
    await rm(result.fullOutputPath!, { force: true });
  });

  it("sanitizes ANSI and OSC sequences split across output chunks", async () => {
    const chunks: string[] = [];
    const operations: BashOperations = {
      exec: async (_command, _cwd, options) => {
        for (const chunk of [
          "A\u001B]0;title",
          "\u0007B",
          "C\u001B[31",
          "mD",
          "E\u009D0;title",
          "\u001B\\F",
          "G\u009B31",
          "mH",
        ]) {
          options.onData(Buffer.from(chunk));
        }
        return { exitCode: 0 };
      },
    };

    const result = await executeBashWithOperations("printf styled", "/tmp", operations, {
      onChunk: (chunk) => chunks.push(chunk),
    });

    expect(chunks.join("")).toBe("ABCDEFGH");
    expect(result.output).toBe("ABCDEFGH");
  });

  it("preserves delivery order when tagged UTF-8 chunks interleave", async () => {
    const chunks: string[] = [];
    const operations = operationsForChunks([
      [Buffer.from([0xe6, 0x97]), "stdout"], // leading bytes of 日
      [Buffer.from("E"), "stderr"],
      [Buffer.from([0xa5]), "stdout"],
    ]);

    const result = await executeBashWithOperations("printf output", "/tmp", operations, {
      onChunk: (chunk) => chunks.push(chunk),
    });

    expect(chunks.join("")).toBe("E日");
    expect(result.output).toBe("E日");
  });

  it.each([
    {
      name: "OSC on stdout",
      pending: [Buffer.from(`${ESC}]0;unterminated`), "stdout"] as const,
      visible: [Buffer.from("stderr visible\n"), "stderr"] as const,
    },
    {
      name: "CSI on stderr",
      pending: [Buffer.from(`${ESC}[31`), "stderr"] as const,
      visible: [Buffer.from("stdout visible\n"), "stdout"] as const,
    },
  ])("does not let unterminated $name consume the other stream", async ({ pending, visible }) => {
    const result = await executeBashWithOperations(
      "printf output",
      "/tmp",
      operationsForChunks([pending, visible]),
    );

    expect(result.output).toBe(visible[0].toString("utf8"));
  });

  it("keeps one sanitizer lane for legacy untagged operations", async () => {
    const operations = operationsForChunks([[Buffer.from(`${ESC}[`)], [Buffer.from("31mlegacy")]]);

    const result = await executeBashWithOperations("printf output", "/tmp", operations);

    expect(result.output).toBe("legacy");
  });

  it("flushes pending UTF-8 bytes from every tagged stream", async () => {
    const chunks: string[] = [];
    const operations = operationsForChunks([
      [Buffer.from([0xe6, 0x97]), "stdout"],
      [Buffer.from([0xe6, 0x97]), "stderr"],
    ]);

    const result = await executeBashWithOperations("printf output", "/tmp", operations, {
      onChunk: (chunk) => chunks.push(chunk),
    });

    expect(chunks.join("")).toBe("��");
    expect(result.output).toBe("��");
  });

  it("stores sanitized split ANSI output in spilled full output files", async () => {
    const chunks = ["A\u001B]0;title", "\u0007B\n"];
    const repeatedChunks = Array.from({ length: 9000 }, (_, index) => chunks[index % 2] ?? "");
    const expectedOutput = "AB\n".repeat(4500);
    const operations: BashOperations = {
      exec: async (_command, _cwd, options) => {
        for (const chunk of repeatedChunks) {
          options.onData(Buffer.from(chunk));
        }
        return { exitCode: 0 };
      },
    };

    const result = await executeBashWithOperations("printf styled", "/tmp", operations);

    expect(result.truncated).toBe(true);
    expect(result.fullOutputPath).toBeDefined();
    expect(await readFile(result.fullOutputPath!, "utf8")).toBe(expectedOutput);
    await rm(result.fullOutputPath!, { force: true });
  });

  it("sanitizes split compatibility escape grammar sequences", async () => {
    const chunks: string[] = [];
    const operations: BashOperations = {
      exec: async (_command, _cwd, options) => {
        options.onData(Buffer.from("A\u001B("));
        options.onData(Buffer.from("BB"));
        return { exitCode: 0 };
      },
    };

    const result = await executeBashWithOperations("printf styled", "/tmp", operations, {
      onChunk: (chunk) => chunks.push(chunk),
    });

    expect(chunks.join("")).toBe("AB");
    expect(result.output).toBe("AB");
  });

  it("does not retain unterminated OSC payload outside accumulator limits", async () => {
    const operations: BashOperations = {
      exec: async (_command, _cwd, options) => {
        options.onData(Buffer.from("safe\n\u001B]0;"));
        options.onData(Buffer.from("x".repeat(DEFAULT_MAX_BYTES * 3)));
        return { exitCode: 0 };
      },
    };

    const result = await executeBashWithOperations("printf styled", "/tmp", operations);

    expect(result.output).toBe("safe\n");
    expect(result.truncated).toBe(false);
    expect(result.fullOutputPath).toBeDefined();
    expect(await readFile(result.fullOutputPath!, "utf8")).toBe("safe\n");
    await rm(result.fullOutputPath!, { force: true });
  });

  it.each([
    { name: "success", abort: false },
    { name: "abort", abort: true },
  ])("flushes incomplete UTF-8 output on $name", async ({ abort }) => {
    const abortController = new AbortController();
    const chunks: string[] = [];
    const operations: BashOperations = {
      exec: async (_command, _cwd, options) => {
        options.onData(Buffer.from([0xf0, 0x9f, 0x98]));
        if (abort) {
          abortController.abort();
          throw new Error("aborted");
        }
        return { exitCode: 0 };
      },
    };

    const result = await executeBashWithOperations("printf output", "/tmp", operations, {
      signal: abortController.signal,
      onChunk: (chunk) => chunks.push(chunk),
    });

    expect(result.output).toBe("�");
    expect(chunks.join("")).toBe("�");
    expect(result.cancelled).toBe(abort);
    expect(result.exitCode).toBe(abort ? undefined : 0);
  });
});