@foldrun/core 23.4.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.
- package/dist/src/blob-types.d.ts +6 -2
- package/dist/src/blob-types.js +17 -5
- package/dist/src/capture.d.ts +7 -0
- package/dist/src/capture.js +10 -1
- package/dist/src/data-import.d.ts +2 -1
- package/dist/src/data-import.js +7 -4
- package/dist/src/run-container.js +18 -3
- package/dist/src/run-output-refusal.js +2 -0
- package/dist/src/run-outputs.js +50 -29
- package/dist/src/runner.js +26 -3
- package/dist/src/safe-open.d.ts +65 -0
- package/dist/src/safe-open.js +160 -0
- package/dist/src/store.d.ts +1 -1
- package/dist/src/store.js +25 -3
- package/dist/src/workspace-revisions.js +29 -10
- package/package.json +1 -1
- package/src/blob-types.ts +15 -4
- package/src/capture.ts +11 -1
- package/src/data-import.ts +7 -4
- package/src/run-container.ts +16 -3
- package/src/run-output-refusal.ts +2 -0
- package/src/run-outputs.ts +50 -29
- package/src/runner.ts +27 -4
- package/src/safe-open.ts +164 -0
- package/src/store.ts +22 -4
- package/src/workspace-revisions.ts +27 -10
package/src/safe-open.ts
ADDED
|
@@ -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,
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
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) ?
|
|
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 =
|
|
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 ((
|
|
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) && (
|
|
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 =
|
|
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];
|