@foldrun/core 23.3.0 → 24.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -43,7 +43,8 @@ import path from "node:path";
43
43
  import crypto from "node:crypto";
44
44
  import { dataRoot } from "./paths.ts";
45
45
  import { processState } from "./process-state.ts";
46
- import { BlobNotFound, type BlobStore } from "./blob-store.ts";
46
+ import { BlobNotFound, fileSource, hashRange, type BlobStore } from "./blob-store.ts";
47
+ import { plainStream, readPlain, statPlain, UnsafeFileError } from "./safe-open.ts";
47
48
  import { PUBLISH_PIN_TTL_MS, noPins, type BlobPins, type PinHolder } from "./blob-pins.ts";
48
49
  import {
49
50
  MAX_MANIFEST_FILES,
@@ -222,6 +223,14 @@ const releaseRecords = async (b: RunOutputsBackend, recs: readonly RunOutputReco
222
223
 
223
224
  /** How many files are in flight at once, and so at most this many buffered. */
224
225
  const UPLOAD_CONCURRENCY = 4;
226
+ /** Up to this size a file is read whole (4 lanes at most, so at most 4 x this in
227
+ * memory); past it, it is hashed and uploaded from disk in chunks. */
228
+ export const SMALL_OUTPUT_FILE_BYTES = 8 * 1024 * 1024;
229
+ /** No output is kept past this, whatever `runs.output_file_mb` says (0 = no
230
+ * setting, which is what the backfill uses): the streamed path bounds memory,
231
+ * not time or storage, and a file this big is not an output an agent should
232
+ * leave. Refused as "file-cap", so it is named, never silent. */
233
+ export const HARD_OUTPUT_FILE_BYTES = 32 * 1024 * 1024 * 1024;
225
234
  const MAX_REFUSALS_ON_RECORD = 100;
226
235
 
227
236
  interface Candidate {
@@ -229,10 +238,17 @@ interface Candidate {
229
238
  abs: string;
230
239
  size: number;
231
240
  mode: number;
241
+ /** The inode the walk saw: the read must find the same one (safe-open.ts). */
242
+ dev: number;
243
+ ino: number;
232
244
  }
233
245
 
234
246
  function walk(root: string): Candidate[] {
235
247
  const out: Candidate[] = [];
248
+ // The folder itself a link (an agent folder pointed elsewhere): its
249
+ // contents are not this run's outputs, and the per-file root check would
250
+ // take the link's target for the root. Nothing is kept from it.
251
+ if (fs.lstatSync(root).isSymbolicLink()) return out;
236
252
  const rec = (dir: string, rel: string) => {
237
253
  for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
238
254
  const abs = path.join(dir, e.name);
@@ -240,7 +256,7 @@ function walk(root: string): Candidate[] {
240
256
  if (e.isDirectory()) rec(abs, r);
241
257
  else if (e.isFile()) {
242
258
  const st = fs.lstatSync(abs);
243
- out.push({ rel: r, abs, size: st.size, mode: st.mode & 0o111 ? MODE_EXEC : MODE_FILE });
259
+ out.push({ rel: r, abs, size: st.size, mode: st.mode & 0o111 ? MODE_EXEC : MODE_FILE, dev: st.dev, ino: st.ino });
244
260
  }
245
261
  // symlinks, sockets and the like are not outputs (the volume copy skipped them too)
246
262
  }
@@ -271,6 +287,7 @@ export async function publishRunOutputs(
271
287
  ): Promise<PublishedOutputs> {
272
288
  safeName(agent, "agent");
273
289
  const fileMax = b.fileMaxBytes();
290
+ const fileCap = fileMax > 0 ? Math.min(fileMax, HARD_OUTPUT_FILE_BYTES) : HARD_OUTPUT_FILE_BYTES;
274
291
  const runMax = b.runMaxBytes();
275
292
  const refused: RefusedOutput[] = [];
276
293
  // What the run's other agents already hold counts against the run's cap.
@@ -296,8 +313,8 @@ export async function publishRunOutputs(
296
313
  refuse("count", MAX_MANIFEST_FILES);
297
314
  continue;
298
315
  }
299
- if (fileMax > 0 && c.size > fileMax) {
300
- refuse("file-cap", fileMax);
316
+ if (c.size > fileCap) {
317
+ refuse("file-cap", fileCap);
301
318
  continue;
302
319
  }
303
320
  if (runMax > 0 && used + c.size > runMax) {
@@ -319,25 +336,56 @@ export async function publishRunOutputs(
319
336
  let id: ManifestId | null = null;
320
337
  try {
321
338
  // Pin BEFORE the objects exist: a sweeper that looks now sees the pin.
322
- // Read each file once for its hash (a file can only be named by its
323
- // bytes), then upload; at most UPLOAD_CONCURRENCY buffers are live.
339
+ // A file can only be named by its bytes, so each is hashed first, then
340
+ // uploaded. A small one is read whole (as always); a bigger one is hashed
341
+ // and uploaded from disk in chunks, so at most UPLOAD_CONCURRENCY small
342
+ // buffers (and some 1 MiB chunks) are live, whatever the file's size.
324
343
  let next = 0;
325
344
  const lane = async () => {
326
345
  for (;;) {
327
346
  const i = next++;
328
347
  if (i >= kept.length) return;
329
348
  const c = kept[i];
330
- const body = fs.readFileSync(c.abs);
331
- // Grew since it was measured (an agent still writing): same rule, same cap.
332
- if (fileMax > 0 && body.length > fileMax) {
333
- refused.push({ agent, path: c.rel, bytes: body.length, reason: "file-cap", limit: fileMax });
334
- continue;
349
+ let sha: string;
350
+ let size: number;
351
+ // The walk looked with lstat; the read opens the path without following
352
+ // a link and must find the inode the walk saw (a file the agent swapped
353
+ // for a link to a secret, or a FIFO, since is refused, not read). The
354
+ // outputs folder is the root: a folder swapped for a link out is too.
355
+ const want = { dev: c.dev, ino: c.ino, root: dir };
356
+ try {
357
+ if (c.size <= SMALL_OUTPUT_FILE_BYTES) {
358
+ // A file that grew past twice the small size since the walk is not read whole.
359
+ const body = readPlain(c.abs, { ...want, maxBytes: 2 * SMALL_OUTPUT_FILE_BYTES });
360
+ // Grew since it was measured (an agent still writing): same rule, same cap.
361
+ if (body.length > fileCap) {
362
+ refused.push({ agent, path: c.rel, bytes: body.length, reason: "file-cap", limit: fileCap });
363
+ continue;
364
+ }
365
+ sha = sha256Hex(body);
366
+ size = body.length;
367
+ // Pin each blob before its put; a repeat extends the lease.
368
+ await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
369
+ await b.blobs.putIfAbsent(blobObjectKey(tenant, sha), body);
370
+ } else {
371
+ const source = fileSource(c.abs, want);
372
+ if (source.size > fileCap) {
373
+ refused.push({ agent, path: c.rel, bytes: source.size, reason: "file-cap", limit: fileCap });
374
+ continue;
375
+ }
376
+ // A file that changes under the read throws BlobSourceError (and the
377
+ // store checks the hash it is given): the publish fails, never stores
378
+ // bytes under a name they do not have.
379
+ sha = (await hashRange(source, 0, source.size)).sha256;
380
+ size = source.size;
381
+ await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
382
+ await b.blobs.putSourceIfAbsent(blobObjectKey(tenant, sha), source, { sha256: sha });
383
+ }
384
+ files[c.rel] = { sha, size, mode: c.mode };
385
+ } catch (err) {
386
+ if (!(err instanceof UnsafeFileError)) throw err;
387
+ refused.push({ agent, path: c.rel, bytes: c.size, reason: "unsafe" });
335
388
  }
336
- const sha = sha256Hex(body);
337
- // Pin each blob before its put; a repeat extends the lease.
338
- await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
339
- await b.blobs.putIfAbsent(blobObjectKey(tenant, sha), body);
340
- files[c.rel] = { sha, size: body.length, mode: c.mode };
341
389
  }
342
390
  };
343
391
  await Promise.all(Array.from({ length: Math.min(UPLOAD_CONCURRENCY, kept.length) }, lane));
@@ -462,6 +510,25 @@ export async function listRunOutputs(tenant: string, workspace: string, runId: s
462
510
  return out.sort((a, b) => a.agent.localeCompare(b.agent) || a.path.localeCompare(b.path));
463
511
  }
464
512
 
513
+ /** What the STORE holds for a run, with each file's hash — the volume is not
514
+ * asked (the backfill's verify compares these to the folder's bytes). */
515
+ export async function storedRunOutputs(tenant: string, workspace: string, runId: string): Promise<{ agent: string; path: string; sha: string; size: number }[]> {
516
+ const out: { agent: string; path: string; sha: string; size: number }[] = [];
517
+ if (!OUT.backend) return out;
518
+ for (const r of await recordsOf(tenant, workspace, runId)) {
519
+ const m = await loadManifest(readDeps(OUT.backend), tenant, r.manifest);
520
+ for (const [p, e] of Object.entries(m.files)) out.push({ agent: r.agent, path: p, sha: e.sha, size: e.size });
521
+ }
522
+ return out;
523
+ }
524
+
525
+ /** The blob is in the store at the size the manifest says (a head, no bytes read). */
526
+ export async function storedBlobIntact(tenant: string, sha: string, size: number): Promise<boolean> {
527
+ if (!OUT.backend) return false;
528
+ const h = await OUT.backend.blobs.head(blobObjectKey(tenant, sha));
529
+ return !!h && h.size === size;
530
+ }
531
+
465
532
  export interface OpenedOutput {
466
533
  size: number;
467
534
  /** The bytes, or one inclusive range of them. */
@@ -512,11 +579,13 @@ export async function openRunOutput(tenant: string, workspace: string, runId: st
512
579
  }
513
580
  const file = runOutputPathOnVolume(tenant, workspace, runId, agent, rel);
514
581
  if (!file) return null;
515
- const size = fs.statSync(file).size;
582
+ // Opened without following a link: the path was checked by
583
+ // runOutputPathOnVolume, and a swap since (link, FIFO) is refused (SYMRACE).
584
+ const seen = statPlain(file);
516
585
  return {
517
- size,
586
+ size: seen.size,
518
587
  // Node's own bridge keeps the file stream paused until the reader pulls.
519
- read: (range) => Readable.toWeb(fs.createReadStream(file, range ? { start: range.start, end: range.end } : undefined)) as ReadableStream<Uint8Array>,
588
+ read: (range) => Readable.toWeb(plainStream(file, { dev: seen.dev, ino: seen.ino, ...(range ? { start: range.start, end: range.end } : {}) })) as ReadableStream<Uint8Array>,
520
589
  };
521
590
  }
522
591
 
package/src/runner.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  import { opsLog, opsError } from "./ops-log.ts";
7
7
  import { globMatch } from "./bounded-match.ts";
8
8
  import { latestRevisionId } from "./history.ts";
9
- import { recordCallIo, redactionsFor } from "./capture.ts";
9
+ import { maskPatterns, recordCallIo, redactionsFor, scrubWith } from "./capture.ts";
10
10
  import { callSink, flushCalls } from "./captured-calls.ts";
11
11
  import { AUTH_REFUSAL, platformCause } from "./issues.ts";
12
12
  import { hookNames } from "./hooks.ts";
@@ -45,7 +45,7 @@ const isolatedRun = () => {
45
45
  import { gatherConsults, buildConsultTools } from "./agent-tools.ts";
46
46
  import { DELEGATE_TOOL, gatherSubagents, ownSandbox, subagentPrompt, subagentTools, SUBAGENT_NO_REMOTES, type DelegateSpec, type SubagentSpec } from "./subagents.ts";
47
47
  import { DELEGATE_SERVER, buildDelegateTools, delegatePromptLine, delegateToolNames, localDelegateChannel, readCopyBack } from "./delegate-tools.ts";
48
- import type { DelegationResult } from "./operator.ts";
48
+ import type { DelegationResult, OperatorEvent } from "./operator.ts";
49
49
  import type { StepDelegation } from "./store.ts";
50
50
  import { TEXT_SERVER, TEXT_TOOL, buildTextTools, textPromptLine } from "./text-tool.ts";
51
51
  import { ASK_TOOL, PEER_TOOLS, applyOperatorEvent, askPromptLine, askTimeoutSec, buildAskTool, buildPeerTools, inboxReader, localPeerBus, peersPromptLine, type PeerInfo } from "./operator.ts";
@@ -2292,10 +2292,27 @@ async function runStepBody(
2292
2292
  // read; the verdict at the end of this function reads it.
2293
2293
  let canActOutward = false;
2294
2294
  const eventsAtStart = step.events.length;
2295
- const redact = (text: string) => {
2296
- let out = text;
2297
- for (const [value, name] of redactions) out = out.split(value).join(`[redacted:${name}]`);
2298
- return out;
2295
+ const redact = (text: string) => scrubWith(redactions, text);
2296
+ // An event line, a question, a message: text that came out of a sandbox or a
2297
+ // model, read by viewers, A2A callers, notifications and exports. The values
2298
+ // above, then what no vault value covers (a key a tool printed, a private
2299
+ // key block) — the mask a captured call already gets. One place: the retry
2300
+ // row's error, the run's failure reason and a notification's summary are all
2301
+ // read back off these events.
2302
+ const mask = (text: string) => maskPatterns(redact(text));
2303
+ const maskOperator = (ev: OperatorEvent): OperatorEvent => {
2304
+ switch (ev.kind) {
2305
+ case "asked":
2306
+ return { ...ev, question: mask(ev.question), ...(ev.options ? { options: ev.options.map(mask) } : {}) };
2307
+ case "message":
2308
+ case "peer":
2309
+ case "told":
2310
+ return { ...ev, text: mask(ev.text) };
2311
+ case "answered":
2312
+ return { ...ev, answer: mask(ev.answer) };
2313
+ default:
2314
+ return ev;
2315
+ }
2299
2316
  };
2300
2317
 
2301
2318
  // The reply, the conclusion and an `output: json` value land on the same
@@ -2333,7 +2350,9 @@ async function runStepBody(
2333
2350
  let captureFull = false;
2334
2351
  const callsRoot = path.resolve(agentDir, "..", "..");
2335
2352
  const sink = runId ? callSink(step, { tenant, workspace: path.basename(callsRoot), runId, workspaceRoot: callsRoot }) : undefined;
2336
- const push = (type: StepRecord["events"][number]["type"], text: string, extra?: EventExtra) => {
2353
+ const push = (type: StepRecord["events"][number]["type"], text: string, given?: EventExtra) => {
2354
+ // A question or a message a model wrote is masked before it is stored or sent on.
2355
+ const extra: EventExtra | undefined = given?.operator ? { ...given, operator: maskOperator(given.operator) } : given;
2337
2356
  const t = new Date().toISOString();
2338
2357
  // The model has begun its first response: held only in memory, for
2339
2358
  // the fan-out gate (warmGate). Not a line in the trace.
@@ -2372,7 +2391,7 @@ async function runStepBody(
2372
2391
  rest = { ...others, captured: true };
2373
2392
  }
2374
2393
  }
2375
- step.events.push({ t, type, text: redact(text), ...rest });
2394
+ step.events.push({ t, type, text: mask(text), ...rest });
2376
2395
  // A person in the loop: the question, its answer, a message delivered —
2377
2396
  // onto the step, so the run page, the API and history show them.
2378
2397
  if (extra?.operator) {
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Reading a file a sandbox, an agent or a customer's upload could have
3
+ * touched — without following a link it swapped in after we looked.
4
+ *
5
+ * The walkers (run outputs, copy-back, folder scan, import) list a tree with
6
+ * lstat, which is honest at that moment. The read comes later, by path, and a
7
+ * path is looked up again: a regular file replaced by a symlink to /proc/self/environ
8
+ * or another tenant's file in between was followed and its bytes stored or
9
+ * served; one replaced by a FIFO blocked the whole worker in a synchronous
10
+ * read. So the read opens with O_NOFOLLOW (a link at the last step is ELOOP)
11
+ * and O_NONBLOCK (a FIFO opens at once instead of waiting for a writer), asks
12
+ * the OPEN file what it is (fstat: a regular file, within the size cap, the
13
+ * same device and inode the walk saw, when it knows them) and reads from that
14
+ * descriptor, so what was checked is what is read.
15
+ *
16
+ * `root`: a directory ON THE WAY can also be swapped for a link (the open only
17
+ * refuses a link at the last step). With a root given, after the open the
18
+ * file's real path must be inside the real root and be the very inode that was
19
+ * opened. That narrows the window to an attacker who flips a directory link
20
+ * back and forth across two syscalls; it does not close it (Node has no
21
+ * openat2 / RESOLVE_NO_SYMLINKS). Callers that need no link anywhere on the way
22
+ * must keep the directory off the sandbox's reach, as the live archive does.
23
+ *
24
+ * Windows has no O_NOFOLLOW: there the check stays what it was (lstat, then
25
+ * open, then fstat) — no weaker than before, with the same small window.
26
+ */
27
+ import fs from "node:fs";
28
+ import path from "node:path";
29
+
30
+ const C = fs.constants;
31
+ // Missing on Windows: 0 there.
32
+ const NOFOLLOW = C.O_NOFOLLOW ?? 0;
33
+ const NONBLOCK = C.O_NONBLOCK ?? 0;
34
+ const NOCTTY = C.O_NOCTTY ?? 0;
35
+
36
+ export class UnsafeFileError extends Error {
37
+ readonly code = "EUNSAFEFILE";
38
+ constructor(file: string, why: string) {
39
+ super(`${path.basename(file)}: ${why}`);
40
+ }
41
+ }
42
+
43
+ export interface PlainOpts {
44
+ /** Refuse a file bigger than this (checked on the open file, not on a stat before). */
45
+ maxBytes?: number;
46
+ /** The inode the walk saw: a different one was swapped in since. */
47
+ dev?: number | bigint;
48
+ ino?: number | bigint;
49
+ /** A real (symlink-free) directory the file must really be inside. */
50
+ root?: string;
51
+ }
52
+
53
+ /** Open a regular file for reading without following a link at its last step
54
+ * or waiting on a FIFO. The caller closes `fd`. Throws UnsafeFileError. */
55
+ export function openPlain(file: string, opts: PlainOpts = {}): { fd: number; st: fs.Stats } {
56
+ if (!NOFOLLOW) {
57
+ // No O_NOFOLLOW here: look first, as every caller did before.
58
+ if (fs.lstatSync(file).isSymbolicLink()) throw new UnsafeFileError(file, "a symbolic link (refused, never followed)");
59
+ }
60
+ let fd: number;
61
+ try {
62
+ fd = fs.openSync(file, C.O_RDONLY | NOFOLLOW | NONBLOCK | NOCTTY);
63
+ } catch (err) {
64
+ const code = (err as NodeJS.ErrnoException).code;
65
+ if (code === "ELOOP") throw new UnsafeFileError(file, "a symbolic link (refused, never followed)");
66
+ if (code === "ENXIO") throw new UnsafeFileError(file, "not a regular file");
67
+ throw err;
68
+ }
69
+ try {
70
+ const st = fs.fstatSync(fd);
71
+ if (!st.isFile()) throw new UnsafeFileError(file, "not a regular file");
72
+ if (opts.ino !== undefined && (st.ino !== opts.ino || (opts.dev !== undefined && st.dev !== opts.dev))) {
73
+ throw new UnsafeFileError(file, "changed while it was being read (another file took its place)");
74
+ }
75
+ if (opts.maxBytes !== undefined && st.size > opts.maxBytes) throw new UnsafeFileError(file, `larger than ${opts.maxBytes} bytes`);
76
+ if (opts.root !== undefined) {
77
+ const real = fs.realpathSync(file);
78
+ const root = fs.realpathSync(opts.root);
79
+ if (!(real === root || real.startsWith(root + path.sep))) throw new UnsafeFileError(file, "leads out of its folder through a symbolic link");
80
+ const there = fs.lstatSync(real);
81
+ if (there.ino !== st.ino || there.dev !== st.dev) throw new UnsafeFileError(file, "changed while it was being read (another file took its place)");
82
+ }
83
+ return { fd, st };
84
+ } catch (err) {
85
+ fs.closeSync(fd);
86
+ throw err;
87
+ }
88
+ }
89
+
90
+ /** The whole file as bytes, from the checked descriptor. */
91
+ export function readPlain(file: string, opts: PlainOpts = {}): Buffer {
92
+ const { fd, st } = openPlain(file, opts);
93
+ try {
94
+ // Never trust the size past the cap: a file growing under the read stops there.
95
+ if (opts.maxBytes === undefined) return fs.readFileSync(fd);
96
+ const buf = Buffer.alloc(Math.min(st.size, opts.maxBytes) + 1);
97
+ let n = 0;
98
+ for (;;) {
99
+ const got = fs.readSync(fd, buf, n, buf.length - n, null);
100
+ if (!got) break;
101
+ n += got;
102
+ if (n >= buf.length) throw new UnsafeFileError(file, `larger than ${opts.maxBytes} bytes`);
103
+ }
104
+ return buf.subarray(0, n);
105
+ } finally {
106
+ fs.closeSync(fd);
107
+ }
108
+ }
109
+
110
+ export function readPlainText(file: string, opts: PlainOpts = {}): string {
111
+ return readPlain(file, opts).toString("utf8");
112
+ }
113
+
114
+ /** What the file is right now (size, device, inode), without following a link. */
115
+ export function statPlain(file: string, opts: PlainOpts = {}): fs.Stats {
116
+ const { fd, st } = openPlain(file, opts);
117
+ fs.closeSync(fd);
118
+ return st;
119
+ }
120
+
121
+ /** A read stream over the checked descriptor (a byte range is inclusive, as
122
+ * createReadStream's). The descriptor is closed with the stream. */
123
+ export function plainStream(
124
+ file: string,
125
+ opts: PlainOpts & { start?: number; end?: number; highWaterMark?: number; signal?: AbortSignal } = {},
126
+ ): fs.ReadStream {
127
+ const { fd } = openPlain(file, opts);
128
+ // O_NONBLOCK was for the open; a regular file reads the same either way.
129
+ return fs.createReadStream(file, { fd, start: opts.start, end: opts.end, highWaterMark: opts.highWaterMark, signal: opts.signal, autoClose: true });
130
+ }
131
+
132
+ /** The whole file as bytes, read off the event loop from the checked descriptor. */
133
+ export async function readPlainAsync(file: string, opts: PlainOpts = {}): Promise<Buffer> {
134
+ const { fd } = openPlain(file, opts);
135
+ try {
136
+ return await new Promise<Buffer>((resolve, reject) => fs.readFile(fd, (err, data) => (err ? reject(err) : resolve(data))));
137
+ } finally {
138
+ fs.closeSync(fd);
139
+ }
140
+ }
141
+
142
+ /** copyFileSync, but from a checked descriptor: a link or a pipe swapped in
143
+ * since the caller's lstat is refused, not followed or waited on. The copy
144
+ * keeps the file's permission bits and is streamed (1 MiB at a time). */
145
+ export function copyPlain(from: string, to: string, opts: PlainOpts = {}): void {
146
+ const { fd, st } = openPlain(from, opts);
147
+ try {
148
+ const out = fs.openSync(to, C.O_WRONLY | C.O_CREAT | C.O_TRUNC, st.mode & 0o777);
149
+ try {
150
+ const buf = Buffer.allocUnsafe(1 << 20);
151
+ for (;;) {
152
+ const n = fs.readSync(fd, buf, 0, buf.length, null);
153
+ if (!n) break;
154
+ let at = 0;
155
+ while (at < n) at += fs.writeSync(out, buf, at, n - at);
156
+ }
157
+ fs.fchmodSync(out, st.mode & 0o777);
158
+ } finally {
159
+ fs.closeSync(out);
160
+ }
161
+ } finally {
162
+ fs.closeSync(fd);
163
+ }
164
+ }
package/src/store.ts CHANGED
@@ -76,6 +76,7 @@ import { starterFiles, accountFiles, blankWorkspaceFiles } from "./starter.ts";
76
76
  import { trimSlashes, MAX_EDITABLE_FILE } from "./paths.ts";
77
77
  import type { RunContext, RunInput, ConversationRecord } from "./conversation.ts";
78
78
  import type { RunInputFile } from "./storage.ts";
79
+ import { copyPlain, readPlainText, UnsafeFileError } from "./safe-open.ts";
79
80
 
80
81
  // Where workspaces live. The hosted app keeps many under data/; the CLI runs
81
82
  // against one folder, which is what `foldrun run ./my-desk` has to mean.
@@ -471,7 +472,7 @@ export function saveWorkspace(
471
472
  if (fs.existsSync(dir)) {
472
473
  for (const rel of listWorkspaceFiles(tenant, workspace)) {
473
474
  try {
474
- before.set(rel, fs.readFileSync(path.join(dir, rel), "utf8"));
475
+ before.set(rel, readPlainText(path.join(dir, rel)));
475
476
  } catch {
476
477
  // vanished mid-read; not part of the revision
477
478
  }
@@ -497,7 +498,15 @@ export function saveWorkspace(
497
498
  }
498
499
  const to = path.join(snapshot, rel);
499
500
  fs.mkdirSync(path.dirname(to), { recursive: true });
500
- fs.copyFileSync(from, to);
501
+ try {
502
+ // From a descriptor opened without following a link: the lstat above
503
+ // can be out of date by now (SYMRACE), and a swapped-in link would copy
504
+ // its target into the snapshot, then back into the workspace.
505
+ copyPlain(from, to);
506
+ } catch (err) {
507
+ if (err instanceof UnsafeFileError || (err as NodeJS.ErrnoException).code === "ENOENT") continue;
508
+ throw err;
509
+ }
501
510
  preserved.push(rel);
502
511
  }
503
512
  }
@@ -2974,7 +2983,16 @@ export function readWorkspaceFile(tenant: string, workspace: string, rel: string
2974
2983
  const p = path.join(dir, assertEditablePath(rel));
2975
2984
  if (!fs.existsSync(p)) throw new Error(`file not found: ${rel}`);
2976
2985
  assertLandsInside(dir, p, rel);
2977
- return fs.readFileSync(p, "utf8");
2986
+ // The check above is by path. A link that stays inside the workspace is
2987
+ // allowed, so the read goes to where it really lands, opened without
2988
+ // following a link and found still inside the workspace: a file or folder
2989
+ // swapped for a link out since the check is refused (SYMRACE).
2990
+ try {
2991
+ return readPlainText(realLanding(p) ?? p, { root: dir });
2992
+ } catch (err) {
2993
+ if (err instanceof UnsafeFileError) throw new Error(`illegal path: ${rel} leads out of the workspace through a symlink`);
2994
+ throw err;
2995
+ }
2978
2996
  }
2979
2997
 
2980
2998
  /** Who made a change and why — recorded on its revision. */
@@ -3955,7 +3973,7 @@ export interface RefusedOutput {
3955
3973
  /** Relative to that agent's outputs/. */
3956
3974
  path: string;
3957
3975
  bytes: number;
3958
- reason: "file-cap" | "run-cap" | "name" | "count";
3976
+ reason: "file-cap" | "run-cap" | "name" | "count" | "unsafe";
3959
3977
  /** The cap in bytes that was exceeded (the count for "count"). */
3960
3978
  limit?: number;
3961
3979
  }
@@ -67,6 +67,7 @@ import { OpIdReused, type HeadIds, type Revision, type WorkspaceRef } from "./re
67
67
  import { pruneStateRevisions, type StateRetention } from "./state-retention.ts";
68
68
  import type { SweepMarks } from "./blob-sweeper.ts";
69
69
  import { setCallsBackend, dropWorkspaceCalls, settleCalls } from "./captured-calls.ts";
70
+ import { plainStream, readPlain, readPlainAsync, UnsafeFileError, type PlainOpts } from "./safe-open.ts";
70
71
  import { dropTenantOutputs, dropWorkspaceOutputs, moveWorkspaceOutputs, settleRunOutputs } from "./run-outputs.ts";
71
72
 
72
73
  // ------------------------------------------------------------- the backend
@@ -1094,15 +1095,31 @@ interface FolderFile {
1094
1095
  mode: number;
1095
1096
  }
1096
1097
 
1097
- async function hashOf(abs: string, size: number): Promise<string> {
1098
+ async function hashOf(abs: string, size: number, expect: PlainOpts = {}): Promise<string> {
1098
1099
  // Read off the event loop: a dashboard process runs this too, and a desk can
1099
- // hold thousands of files.
1100
- if (size <= LARGE_FILE) return sha256Hex(await fs.promises.readFile(abs));
1100
+ // hold thousands of files. From a descriptor opened without following a link,
1101
+ // on the inode the scan listed (a swap since is refused: safe-open.ts).
1102
+ if (size <= LARGE_FILE) return sha256Hex(await readPlainAsync(abs, expect));
1101
1103
  const h = crypto.createHash("sha256");
1102
- await pipeline(fs.createReadStream(abs), h);
1104
+ await pipeline(plainStream(abs, expect), h);
1103
1105
  return h.digest("hex");
1104
1106
  }
1105
1107
 
1108
+ /** What a file holds now: its sha, null when there is none. A link or a pipe
1109
+ * that took its place since the caller's link check reads as something that
1110
+ * matches nothing — "changed meanwhile", so the file is left alone — instead
1111
+ * of being followed or waited on (safe-open.ts). */
1112
+ const NOT_A_FILE = "!not-a-regular-file";
1113
+ function shaOnDisk(abs: string): string | null {
1114
+ try {
1115
+ return sha256Hex(readPlain(abs));
1116
+ } catch (err) {
1117
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
1118
+ if (err instanceof UnsafeFileError) return NOT_A_FILE;
1119
+ throw err;
1120
+ }
1121
+ }
1122
+
1106
1123
  /**
1107
1124
  * The workspace's content as the folder holds it now: every regular file on
1108
1125
  * one of the two sides (manifest.ts sideOf), whatever its bytes — the rule
@@ -1169,7 +1186,7 @@ async function scanFolder(tenant: string, workspace: string): Promise<{ files: M
1169
1186
  try {
1170
1187
  assertManifestPath(f.rel);
1171
1188
  if (lower.has(fold)) throw new Error("differs only by case");
1172
- files.set(f.rel, { abs: f.abs, sha: await hashOf(f.abs, f.st.size), size: f.st.size, mode: f.st.mode & 0o111 ? MODE_EXEC : MODE_FILE });
1189
+ files.set(f.rel, { abs: f.abs, sha: await hashOf(f.abs, f.st.size, { dev: f.st.dev, ino: f.st.ino, root: dir }), size: f.st.size, mode: f.st.mode & 0o111 ? MODE_EXEC : MODE_FILE });
1173
1190
  lower.add(fold);
1174
1191
  } catch {
1175
1192
  left.add(f.rel);
@@ -1352,7 +1369,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1352
1369
  changes: todo,
1353
1370
  restoredFrom: done.authored ? undefined : restoredFrom,
1354
1371
  bytesOf: async (sha) => {
1355
- const b = bytes.get(sha) ?? (onDisk.has(sha) ? fs.readFileSync(onDisk.get(sha)!) : null);
1372
+ const b = bytes.get(sha) ?? (onDisk.has(sha) ? readPlain(onDisk.get(sha)!) : null);
1356
1373
  if (!b) throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1357
1374
  return b;
1358
1375
  },
@@ -1516,7 +1533,7 @@ async function afterPublish(deps: Deps, ws: WorkspaceRef, changes: Changes, r: P
1516
1533
  const abs = path.join(dir, p);
1517
1534
  // Never through a link, on any branch below (Codex review).
1518
1535
  if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink())) continue;
1519
- const local = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
1536
+ const local = shaOnDisk(abs);
1520
1537
  // Only while the file is still what this pod published (or gone, for a delete).
1521
1538
  if (c.op === "delete" ? local !== null : local !== c.sha) continue;
1522
1539
  if (winner) {
@@ -1525,7 +1542,7 @@ async function afterPublish(deps: Deps, ws: WorkspaceRef, changes: Changes, r: P
1525
1542
  // Again after the download: an edit made meanwhile is kept, and never
1526
1543
  // through a link — the file or a folder on its way (Codex review).
1527
1544
  if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink())) continue;
1528
- if ((fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null) !== local) continue;
1545
+ if (shaOnDisk(abs) !== local) continue;
1529
1546
  fs.mkdirSync(path.dirname(abs), { recursive: true });
1530
1547
  // A new file renamed over the old one: replaces it, follows nothing.
1531
1548
  const tmp = `${abs}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.mirror-tmp`;
@@ -1663,7 +1680,7 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
1663
1680
  next[p] = s;
1664
1681
  continue;
1665
1682
  }
1666
- if (fs.existsSync(f.abs) && (sha256Hex(fs.readFileSync(f.abs)) !== f.sha || modeOfFile(f.abs) !== f.mode)) {
1683
+ if (fs.existsSync(f.abs) && (shaOnDisk(f.abs) !== f.sha || modeOfFile(f.abs) !== f.mode)) {
1667
1684
  ownChanges = true;
1668
1685
  next[p] = s;
1669
1686
  continue;
@@ -1727,7 +1744,7 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
1727
1744
  // this very file while it ran (Codex review). The file must still be what
1728
1745
  // the scan saw, or it is this pod's change now and is left alone.
1729
1746
  if (busy()) return "skipped";
1730
- const nowSha = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
1747
+ const nowSha = shaOnDisk(abs);
1731
1748
  if (nowSha !== (f?.sha ?? null) || (f && modeOfFile(abs) !== f.mode)) {
1732
1749
  ownChanges = true;
1733
1750
  if (synced[p]) next[p] = synced[p];