@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.
- package/dist/src/blob-types.d.ts +6 -2
- package/dist/src/blob-types.js +17 -5
- package/dist/src/capture.d.ts +18 -0
- package/dist/src/capture.js +58 -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.d.ts +18 -0
- package/dist/src/run-outputs.js +90 -19
- package/dist/src/runner.js +26 -8
- 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 +58 -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 +88 -19
- package/src/runner.ts +27 -8
- package/src/safe-open.ts +164 -0
- package/src/store.ts +22 -4
- package/src/workspace-revisions.ts +27 -10
|
@@ -0,0 +1,160 @@
|
|
|
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
|
+
const C = fs.constants;
|
|
30
|
+
// Missing on Windows: 0 there.
|
|
31
|
+
const NOFOLLOW = C.O_NOFOLLOW ?? 0;
|
|
32
|
+
const NONBLOCK = C.O_NONBLOCK ?? 0;
|
|
33
|
+
const NOCTTY = C.O_NOCTTY ?? 0;
|
|
34
|
+
export class UnsafeFileError extends Error {
|
|
35
|
+
code = "EUNSAFEFILE";
|
|
36
|
+
constructor(file, why) {
|
|
37
|
+
super(`${path.basename(file)}: ${why}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Open a regular file for reading without following a link at its last step
|
|
41
|
+
* or waiting on a FIFO. The caller closes `fd`. Throws UnsafeFileError. */
|
|
42
|
+
export function openPlain(file, opts = {}) {
|
|
43
|
+
if (!NOFOLLOW) {
|
|
44
|
+
// No O_NOFOLLOW here: look first, as every caller did before.
|
|
45
|
+
if (fs.lstatSync(file).isSymbolicLink())
|
|
46
|
+
throw new UnsafeFileError(file, "a symbolic link (refused, never followed)");
|
|
47
|
+
}
|
|
48
|
+
let fd;
|
|
49
|
+
try {
|
|
50
|
+
fd = fs.openSync(file, C.O_RDONLY | NOFOLLOW | NONBLOCK | NOCTTY);
|
|
51
|
+
}
|
|
52
|
+
catch (err) {
|
|
53
|
+
const code = err.code;
|
|
54
|
+
if (code === "ELOOP")
|
|
55
|
+
throw new UnsafeFileError(file, "a symbolic link (refused, never followed)");
|
|
56
|
+
if (code === "ENXIO")
|
|
57
|
+
throw new UnsafeFileError(file, "not a regular file");
|
|
58
|
+
throw err;
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
const st = fs.fstatSync(fd);
|
|
62
|
+
if (!st.isFile())
|
|
63
|
+
throw new UnsafeFileError(file, "not a regular file");
|
|
64
|
+
if (opts.ino !== undefined && (st.ino !== opts.ino || (opts.dev !== undefined && st.dev !== opts.dev))) {
|
|
65
|
+
throw new UnsafeFileError(file, "changed while it was being read (another file took its place)");
|
|
66
|
+
}
|
|
67
|
+
if (opts.maxBytes !== undefined && st.size > opts.maxBytes)
|
|
68
|
+
throw new UnsafeFileError(file, `larger than ${opts.maxBytes} bytes`);
|
|
69
|
+
if (opts.root !== undefined) {
|
|
70
|
+
const real = fs.realpathSync(file);
|
|
71
|
+
const root = fs.realpathSync(opts.root);
|
|
72
|
+
if (!(real === root || real.startsWith(root + path.sep)))
|
|
73
|
+
throw new UnsafeFileError(file, "leads out of its folder through a symbolic link");
|
|
74
|
+
const there = fs.lstatSync(real);
|
|
75
|
+
if (there.ino !== st.ino || there.dev !== st.dev)
|
|
76
|
+
throw new UnsafeFileError(file, "changed while it was being read (another file took its place)");
|
|
77
|
+
}
|
|
78
|
+
return { fd, st };
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
fs.closeSync(fd);
|
|
82
|
+
throw err;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** The whole file as bytes, from the checked descriptor. */
|
|
86
|
+
export function readPlain(file, opts = {}) {
|
|
87
|
+
const { fd, st } = openPlain(file, opts);
|
|
88
|
+
try {
|
|
89
|
+
// Never trust the size past the cap: a file growing under the read stops there.
|
|
90
|
+
if (opts.maxBytes === undefined)
|
|
91
|
+
return fs.readFileSync(fd);
|
|
92
|
+
const buf = Buffer.alloc(Math.min(st.size, opts.maxBytes) + 1);
|
|
93
|
+
let n = 0;
|
|
94
|
+
for (;;) {
|
|
95
|
+
const got = fs.readSync(fd, buf, n, buf.length - n, null);
|
|
96
|
+
if (!got)
|
|
97
|
+
break;
|
|
98
|
+
n += got;
|
|
99
|
+
if (n >= buf.length)
|
|
100
|
+
throw new UnsafeFileError(file, `larger than ${opts.maxBytes} bytes`);
|
|
101
|
+
}
|
|
102
|
+
return buf.subarray(0, n);
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
fs.closeSync(fd);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
export function readPlainText(file, opts = {}) {
|
|
109
|
+
return readPlain(file, opts).toString("utf8");
|
|
110
|
+
}
|
|
111
|
+
/** What the file is right now (size, device, inode), without following a link. */
|
|
112
|
+
export function statPlain(file, opts = {}) {
|
|
113
|
+
const { fd, st } = openPlain(file, opts);
|
|
114
|
+
fs.closeSync(fd);
|
|
115
|
+
return st;
|
|
116
|
+
}
|
|
117
|
+
/** A read stream over the checked descriptor (a byte range is inclusive, as
|
|
118
|
+
* createReadStream's). The descriptor is closed with the stream. */
|
|
119
|
+
export function plainStream(file, opts = {}) {
|
|
120
|
+
const { fd } = openPlain(file, opts);
|
|
121
|
+
// O_NONBLOCK was for the open; a regular file reads the same either way.
|
|
122
|
+
return fs.createReadStream(file, { fd, start: opts.start, end: opts.end, highWaterMark: opts.highWaterMark, signal: opts.signal, autoClose: true });
|
|
123
|
+
}
|
|
124
|
+
/** The whole file as bytes, read off the event loop from the checked descriptor. */
|
|
125
|
+
export async function readPlainAsync(file, opts = {}) {
|
|
126
|
+
const { fd } = openPlain(file, opts);
|
|
127
|
+
try {
|
|
128
|
+
return await new Promise((resolve, reject) => fs.readFile(fd, (err, data) => (err ? reject(err) : resolve(data))));
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
fs.closeSync(fd);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/** copyFileSync, but from a checked descriptor: a link or a pipe swapped in
|
|
135
|
+
* since the caller's lstat is refused, not followed or waited on. The copy
|
|
136
|
+
* keeps the file's permission bits and is streamed (1 MiB at a time). */
|
|
137
|
+
export function copyPlain(from, to, opts = {}) {
|
|
138
|
+
const { fd, st } = openPlain(from, opts);
|
|
139
|
+
try {
|
|
140
|
+
const out = fs.openSync(to, C.O_WRONLY | C.O_CREAT | C.O_TRUNC, st.mode & 0o777);
|
|
141
|
+
try {
|
|
142
|
+
const buf = Buffer.allocUnsafe(1 << 20);
|
|
143
|
+
for (;;) {
|
|
144
|
+
const n = fs.readSync(fd, buf, 0, buf.length, null);
|
|
145
|
+
if (!n)
|
|
146
|
+
break;
|
|
147
|
+
let at = 0;
|
|
148
|
+
while (at < n)
|
|
149
|
+
at += fs.writeSync(out, buf, at, n - at);
|
|
150
|
+
}
|
|
151
|
+
fs.fchmodSync(out, st.mode & 0o777);
|
|
152
|
+
}
|
|
153
|
+
finally {
|
|
154
|
+
fs.closeSync(out);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
finally {
|
|
158
|
+
fs.closeSync(fd);
|
|
159
|
+
}
|
|
160
|
+
}
|
package/dist/src/store.d.ts
CHANGED
|
@@ -1545,7 +1545,7 @@ export interface RefusedOutput {
|
|
|
1545
1545
|
/** Relative to that agent's outputs/. */
|
|
1546
1546
|
path: string;
|
|
1547
1547
|
bytes: number;
|
|
1548
|
-
reason: "file-cap" | "run-cap" | "name" | "count";
|
|
1548
|
+
reason: "file-cap" | "run-cap" | "name" | "count" | "unsafe";
|
|
1549
1549
|
/** The cap in bytes that was exceeded (the count for "count"). */
|
|
1550
1550
|
limit?: number;
|
|
1551
1551
|
}
|
package/dist/src/store.js
CHANGED
|
@@ -67,6 +67,7 @@ import { readTransport, KINDS } from "./kinds.js";
|
|
|
67
67
|
import { providerPreset, looksOpenAiShaped, PROTECTED_PARAMS } from "./providers.js";
|
|
68
68
|
import { starterFiles, accountFiles, blankWorkspaceFiles } from "./starter.js";
|
|
69
69
|
import { trimSlashes, MAX_EDITABLE_FILE } from "./paths.js";
|
|
70
|
+
import { copyPlain, readPlainText, UnsafeFileError } from "./safe-open.js";
|
|
70
71
|
// Where workspaces live. The hosted app keeps many under data/; the CLI runs
|
|
71
72
|
// against one folder, which is what `foldrun run ./my-desk` has to mean.
|
|
72
73
|
/**
|
|
@@ -424,7 +425,7 @@ meta = {}) {
|
|
|
424
425
|
if (fs.existsSync(dir)) {
|
|
425
426
|
for (const rel of listWorkspaceFiles(tenant, workspace)) {
|
|
426
427
|
try {
|
|
427
|
-
before.set(rel,
|
|
428
|
+
before.set(rel, readPlainText(path.join(dir, rel)));
|
|
428
429
|
}
|
|
429
430
|
catch {
|
|
430
431
|
// vanished mid-read; not part of the revision
|
|
@@ -451,7 +452,17 @@ meta = {}) {
|
|
|
451
452
|
}
|
|
452
453
|
const to = path.join(snapshot, rel);
|
|
453
454
|
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
454
|
-
|
|
455
|
+
try {
|
|
456
|
+
// From a descriptor opened without following a link: the lstat above
|
|
457
|
+
// can be out of date by now (SYMRACE), and a swapped-in link would copy
|
|
458
|
+
// its target into the snapshot, then back into the workspace.
|
|
459
|
+
copyPlain(from, to);
|
|
460
|
+
}
|
|
461
|
+
catch (err) {
|
|
462
|
+
if (err instanceof UnsafeFileError || err.code === "ENOENT")
|
|
463
|
+
continue;
|
|
464
|
+
throw err;
|
|
465
|
+
}
|
|
455
466
|
preserved.push(rel);
|
|
456
467
|
}
|
|
457
468
|
}
|
|
@@ -2480,7 +2491,18 @@ export function readWorkspaceFile(tenant, workspace, rel) {
|
|
|
2480
2491
|
if (!fs.existsSync(p))
|
|
2481
2492
|
throw new Error(`file not found: ${rel}`);
|
|
2482
2493
|
assertLandsInside(dir, p, rel);
|
|
2483
|
-
|
|
2494
|
+
// The check above is by path. A link that stays inside the workspace is
|
|
2495
|
+
// allowed, so the read goes to where it really lands, opened without
|
|
2496
|
+
// following a link and found still inside the workspace: a file or folder
|
|
2497
|
+
// swapped for a link out since the check is refused (SYMRACE).
|
|
2498
|
+
try {
|
|
2499
|
+
return readPlainText(realLanding(p) ?? p, { root: dir });
|
|
2500
|
+
}
|
|
2501
|
+
catch (err) {
|
|
2502
|
+
if (err instanceof UnsafeFileError)
|
|
2503
|
+
throw new Error(`illegal path: ${rel} leads out of the workspace through a symlink`);
|
|
2504
|
+
throw err;
|
|
2505
|
+
}
|
|
2484
2506
|
}
|
|
2485
2507
|
export function writeWorkspaceFile(tenant, workspace, rel, content, meta = {}) {
|
|
2486
2508
|
// 512 KB: a folder tool's program is one file, and the gallery browser's is
|
|
@@ -48,6 +48,7 @@ import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requ
|
|
|
48
48
|
import { OpIdReused } from "./revision-store.js";
|
|
49
49
|
import { pruneStateRevisions } from "./state-retention.js";
|
|
50
50
|
import { setCallsBackend, dropWorkspaceCalls, settleCalls } from "./captured-calls.js";
|
|
51
|
+
import { plainStream, readPlain, readPlainAsync, UnsafeFileError } from "./safe-open.js";
|
|
51
52
|
import { dropTenantOutputs, dropWorkspaceOutputs, moveWorkspaceOutputs, settleRunOutputs } from "./run-outputs.js";
|
|
52
53
|
// ------------------------------------------------------------- the backend
|
|
53
54
|
/** Everything this module is told at boot, and every queue that goes with it,
|
|
@@ -1002,15 +1003,33 @@ export async function reconcileAll(opts = {}) {
|
|
|
1002
1003
|
/** A file this big is sent to the store from disk, never read whole. */
|
|
1003
1004
|
const LARGE_FILE = 8 * 1024 * 1024;
|
|
1004
1005
|
const LARGE_PIN_TTL_MS = 30 * 60_000;
|
|
1005
|
-
async function hashOf(abs, size) {
|
|
1006
|
+
async function hashOf(abs, size, expect = {}) {
|
|
1006
1007
|
// Read off the event loop: a dashboard process runs this too, and a desk can
|
|
1007
|
-
// hold thousands of files.
|
|
1008
|
+
// hold thousands of files. From a descriptor opened without following a link,
|
|
1009
|
+
// on the inode the scan listed (a swap since is refused: safe-open.ts).
|
|
1008
1010
|
if (size <= LARGE_FILE)
|
|
1009
|
-
return sha256Hex(await
|
|
1011
|
+
return sha256Hex(await readPlainAsync(abs, expect));
|
|
1010
1012
|
const h = crypto.createHash("sha256");
|
|
1011
|
-
await pipeline(
|
|
1013
|
+
await pipeline(plainStream(abs, expect), h);
|
|
1012
1014
|
return h.digest("hex");
|
|
1013
1015
|
}
|
|
1016
|
+
/** What a file holds now: its sha, null when there is none. A link or a pipe
|
|
1017
|
+
* that took its place since the caller's link check reads as something that
|
|
1018
|
+
* matches nothing — "changed meanwhile", so the file is left alone — instead
|
|
1019
|
+
* of being followed or waited on (safe-open.ts). */
|
|
1020
|
+
const NOT_A_FILE = "!not-a-regular-file";
|
|
1021
|
+
function shaOnDisk(abs) {
|
|
1022
|
+
try {
|
|
1023
|
+
return sha256Hex(readPlain(abs));
|
|
1024
|
+
}
|
|
1025
|
+
catch (err) {
|
|
1026
|
+
if (err.code === "ENOENT")
|
|
1027
|
+
return null;
|
|
1028
|
+
if (err instanceof UnsafeFileError)
|
|
1029
|
+
return NOT_A_FILE;
|
|
1030
|
+
throw err;
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1014
1033
|
/**
|
|
1015
1034
|
* The workspace's content as the folder holds it now: every regular file on
|
|
1016
1035
|
* one of the two sides (manifest.ts sideOf), whatever its bytes — the rule
|
|
@@ -1092,7 +1111,7 @@ async function scanFolder(tenant, workspace) {
|
|
|
1092
1111
|
assertManifestPath(f.rel);
|
|
1093
1112
|
if (lower.has(fold))
|
|
1094
1113
|
throw new Error("differs only by case");
|
|
1095
|
-
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 });
|
|
1114
|
+
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 });
|
|
1096
1115
|
lower.add(fold);
|
|
1097
1116
|
}
|
|
1098
1117
|
catch {
|
|
@@ -1286,7 +1305,7 @@ async function commitEntry(deps, tenant, workspace, entry) {
|
|
|
1286
1305
|
changes: todo,
|
|
1287
1306
|
restoredFrom: done.authored ? undefined : restoredFrom,
|
|
1288
1307
|
bytesOf: async (sha) => {
|
|
1289
|
-
const b = bytes.get(sha) ?? (onDisk.has(sha) ?
|
|
1308
|
+
const b = bytes.get(sha) ?? (onDisk.has(sha) ? readPlain(onDisk.get(sha)) : null);
|
|
1290
1309
|
if (!b)
|
|
1291
1310
|
throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
|
|
1292
1311
|
return b;
|
|
@@ -1467,7 +1486,7 @@ async function afterPublish(deps, ws, changes, r) {
|
|
|
1467
1486
|
// Never through a link, on any branch below (Codex review).
|
|
1468
1487
|
if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink()))
|
|
1469
1488
|
continue;
|
|
1470
|
-
const local =
|
|
1489
|
+
const local = shaOnDisk(abs);
|
|
1471
1490
|
// Only while the file is still what this pod published (or gone, for a delete).
|
|
1472
1491
|
if (c.op === "delete" ? local !== null : local !== c.sha)
|
|
1473
1492
|
continue;
|
|
@@ -1479,7 +1498,7 @@ async function afterPublish(deps, ws, changes, r) {
|
|
|
1479
1498
|
// through a link — the file or a folder on its way (Codex review).
|
|
1480
1499
|
if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink()))
|
|
1481
1500
|
continue;
|
|
1482
|
-
if ((
|
|
1501
|
+
if (shaOnDisk(abs) !== local)
|
|
1483
1502
|
continue;
|
|
1484
1503
|
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
1485
1504
|
// A new file renamed over the old one: replaces it, follows nothing.
|
|
@@ -1634,7 +1653,7 @@ async function syncNow(tenant, workspace) {
|
|
|
1634
1653
|
next[p] = s;
|
|
1635
1654
|
continue;
|
|
1636
1655
|
}
|
|
1637
|
-
if (fs.existsSync(f.abs) && (
|
|
1656
|
+
if (fs.existsSync(f.abs) && (shaOnDisk(f.abs) !== f.sha || modeOfFile(f.abs) !== f.mode)) {
|
|
1638
1657
|
ownChanges = true;
|
|
1639
1658
|
next[p] = s;
|
|
1640
1659
|
continue;
|
|
@@ -1707,7 +1726,7 @@ async function syncNow(tenant, workspace) {
|
|
|
1707
1726
|
// the scan saw, or it is this pod's change now and is left alone.
|
|
1708
1727
|
if (busy())
|
|
1709
1728
|
return "skipped";
|
|
1710
|
-
const nowSha =
|
|
1729
|
+
const nowSha = shaOnDisk(abs);
|
|
1711
1730
|
if (nowSha !== (f?.sha ?? null) || (f && modeOfFile(abs) !== f.mode)) {
|
|
1712
1731
|
ownChanges = true;
|
|
1713
1732
|
if (synced[p])
|
package/package.json
CHANGED
package/src/blob-types.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import fs from "node:fs";
|
|
7
7
|
import crypto from "node:crypto";
|
|
8
|
+
import { plainStream, statPlain, UnsafeFileError, type PlainOpts } from "./safe-open.ts";
|
|
8
9
|
|
|
9
10
|
export class BlobNotFound extends Error {
|
|
10
11
|
readonly key: string;
|
|
@@ -185,15 +186,25 @@ export function bufferSource(buf: Uint8Array): BlobSource {
|
|
|
185
186
|
|
|
186
187
|
/** A file on disk. The size is taken now; if the file is shorter (or longer)
|
|
187
188
|
* when it is read, the read throws BlobSourceError rather than send a body
|
|
188
|
-
* that no longer matches what was announced.
|
|
189
|
-
|
|
190
|
-
|
|
189
|
+
* that no longer matches what was announced. A link is never followed, and a
|
|
190
|
+
* different file (or a FIFO) swapped in since the size was taken is refused:
|
|
191
|
+
* each read opens the path without following links and must find the same
|
|
192
|
+
* inode (safe-open.ts, SYMRACE). */
|
|
193
|
+
export function fileSource(filePath: string, expect: PlainOpts = {}): BlobSource {
|
|
194
|
+
const seen = statPlain(filePath, expect);
|
|
195
|
+
const size = seen.size;
|
|
191
196
|
return {
|
|
192
197
|
size,
|
|
193
198
|
async *read(start, end, signal) {
|
|
194
199
|
const hi = Math.min(end, size);
|
|
195
200
|
if (hi <= start) return;
|
|
196
|
-
|
|
201
|
+
let stream: fs.ReadStream;
|
|
202
|
+
try {
|
|
203
|
+
stream = plainStream(filePath, { start, end: hi - 1, highWaterMark: 1 << 20, signal, dev: seen.dev, ino: seen.ino, root: expect.root });
|
|
204
|
+
} catch (err) {
|
|
205
|
+
if (err instanceof UnsafeFileError) throw new BlobSourceError(`${filePath} changed while it was being uploaded: ${err.message}`);
|
|
206
|
+
throw err;
|
|
207
|
+
}
|
|
197
208
|
let got = 0;
|
|
198
209
|
for await (const chunk of stream) {
|
|
199
210
|
got += (chunk as Buffer).length;
|
package/src/capture.ts
CHANGED
|
@@ -122,15 +122,72 @@ export function encodedForms(v: string): string[] {
|
|
|
122
122
|
return [...forms].filter((f) => f.length >= 12);
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
+
/** The shortest piece of a secret that is masked when a cut left only that
|
|
126
|
+
* much of it at an edge of a text. The same floor as a whole secret (8):
|
|
127
|
+
* fewer characters than that is no key. */
|
|
128
|
+
const EDGE_MIN = 8;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Every secret value in `text` → `[redacted:NAME]` (the runner's scrub), and
|
|
132
|
+
* also the piece of one a cut left at an end of the text. A sandbox cuts what
|
|
133
|
+
* it sends (a tool's output, a reply, an error line, the stderr tail) before
|
|
134
|
+
* the host sees it, so a secret on the cut arrives as a prefix at the end
|
|
135
|
+
* (or a suffix at the start), which no whole-value match recognises — and
|
|
136
|
+
* masking first and cutting second cannot help what was cut before it got
|
|
137
|
+
* here. An end that is the start of a value (8+ characters, `EDGE_MIN`) is
|
|
138
|
+
* masked as that value, plain or in any of the encoded forms in the list.
|
|
139
|
+
*/
|
|
140
|
+
export function scrubWith(redactions: [string, string][], text: string): string {
|
|
141
|
+
let out = text;
|
|
142
|
+
for (const [value, name] of redactions) out = out.split(value).join(`[redacted:${name}]`);
|
|
143
|
+
if (out.length < EDGE_MIN) return out;
|
|
144
|
+
for (const [value, name] of redactions) {
|
|
145
|
+
if (value.length <= EDGE_MIN) continue;
|
|
146
|
+
const mark = `[redacted:${name}]`;
|
|
147
|
+
// the end of the text begins the value: look only where a piece shorter
|
|
148
|
+
// than the whole value can fit
|
|
149
|
+
const tail = out.slice(-(value.length - 1));
|
|
150
|
+
const head8 = value.slice(0, EDGE_MIN);
|
|
151
|
+
for (let at = tail.indexOf(head8); at >= 0; at = tail.indexOf(head8, at + 1)) {
|
|
152
|
+
if (value.startsWith(tail.slice(at))) {
|
|
153
|
+
out = out.slice(0, out.length - (tail.length - at)) + mark;
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
// the start of the text ends the value
|
|
158
|
+
const lead = out.slice(0, value.length - 1);
|
|
159
|
+
const first8 = lead.slice(0, EDGE_MIN);
|
|
160
|
+
if (first8.length === EDGE_MIN) {
|
|
161
|
+
for (let j = value.indexOf(first8, 1); j >= 0 && value.length - j >= EDGE_MIN; j = value.indexOf(first8, j + 1)) {
|
|
162
|
+
if (out.startsWith(value.slice(j))) {
|
|
163
|
+
out = mark + out.slice(value.length - j);
|
|
164
|
+
break;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return out;
|
|
170
|
+
}
|
|
171
|
+
|
|
125
172
|
// A private key's whole block — scan.ts names a key header and leaves the
|
|
126
173
|
// body, which is right for a finding and wrong for a stored output.
|
|
127
174
|
// Unterminated too: a key cut short, or printed without its END line, is
|
|
128
175
|
// masked to the end of the text.
|
|
129
176
|
const PRIVATE_KEY = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$(?![\s\S]))/g;
|
|
130
177
|
|
|
178
|
+
/** What no vault value covers: a credential-shaped string (a GitHub, Anthropic
|
|
179
|
+
* or AWS key, a JWT, `token=…`, a bearer) and a private key's whole block.
|
|
180
|
+
* Applied after the step's own value masks, to every piece of stored text that
|
|
181
|
+
* came out of a sandbox or a model — a tool's output, a prompt, stderr — so a
|
|
182
|
+
* key a tool read off disk is not kept just because it was never a secret
|
|
183
|
+
* of ours. Ordinary text (ids, URLs, paths, hashes) is left as it was. */
|
|
184
|
+
export function maskPatterns(text: string): string {
|
|
185
|
+
return redactText(text).replace(PRIVATE_KEY, "[redacted:private key]");
|
|
186
|
+
}
|
|
187
|
+
|
|
131
188
|
/** Masked, then cut to the cap. */
|
|
132
189
|
export function maskCall(text: string, redactSecrets: (text: string) => string): { text: string; cut: boolean } {
|
|
133
|
-
const masked =
|
|
190
|
+
const masked = maskPatterns(redactSecrets(text));
|
|
134
191
|
return masked.length > CAPTURE_CAP ? { text: masked.slice(0, CAPTURE_CAP), cut: true } : { text: masked, cut: false };
|
|
135
192
|
}
|
|
136
193
|
|
package/src/data-import.ts
CHANGED
|
@@ -68,6 +68,7 @@ import {
|
|
|
68
68
|
} from "./manifest.ts";
|
|
69
69
|
import { headsOf, manifestsAt, publish, requestDigest, type Deps } from "./publish.ts";
|
|
70
70
|
import { BlobNotFound, BlobSourceError, downloadToFile, fileSource } from "./blob-store.ts";
|
|
71
|
+
import { plainStream, readPlain, type PlainOpts } from "./safe-open.ts";
|
|
71
72
|
import type { Revision, WorkspaceRef } from "./revision-store.ts";
|
|
72
73
|
import { isPlatformPath } from "./store.ts";
|
|
73
74
|
|
|
@@ -135,9 +136,11 @@ export interface ScanOptions {
|
|
|
135
136
|
workspaces?: string[];
|
|
136
137
|
}
|
|
137
138
|
|
|
138
|
-
export async function hashFile(abs: string): Promise<string> {
|
|
139
|
+
export async function hashFile(abs: string, expect: PlainOpts = {}): Promise<string> {
|
|
139
140
|
const h = crypto.createHash("sha256");
|
|
140
|
-
|
|
141
|
+
// Never through a link, never waiting on a pipe, and (with `st`) the file the
|
|
142
|
+
// scan listed: the scan's lstat said "regular file" earlier (safe-open.ts).
|
|
143
|
+
await pipeline(plainStream(abs, expect), h);
|
|
141
144
|
return h.digest("hex");
|
|
142
145
|
}
|
|
143
146
|
|
|
@@ -313,7 +316,7 @@ async function scanWorkspace(tenant: string, workspace: string, dir: string): Pr
|
|
|
313
316
|
if (from) ws.conflicts.push({ path: from, keptAs: rel });
|
|
314
317
|
let sha: string;
|
|
315
318
|
try {
|
|
316
|
-
sha = await hashFile(f.abs);
|
|
319
|
+
sha = await hashFile(f.abs, { dev: f.st.dev, ino: f.st.ino, root: dir });
|
|
317
320
|
} catch (err) {
|
|
318
321
|
ws.unmapped.push({ path: f.rel, reason: `unreadable (${(err as NodeJS.ErrnoException).code ?? "error"})`, files: 1, bytes: f.st.size });
|
|
319
322
|
continue;
|
|
@@ -508,7 +511,7 @@ export async function importWorkspace(scan: WorkspaceScan, opts: ImportOptions):
|
|
|
508
511
|
bytesOf: async (sha) => {
|
|
509
512
|
const f = bySha.get(sha);
|
|
510
513
|
if (!f) throw new Error(`no source file for ${sha.slice(0, 12)}…`);
|
|
511
|
-
const b =
|
|
514
|
+
const b = readPlain(f.abs);
|
|
512
515
|
if (sha256Hex(b) !== sha) throw new Error(`${f.path} changed while it was being imported`);
|
|
513
516
|
return b;
|
|
514
517
|
},
|
package/src/run-container.ts
CHANGED
|
@@ -51,6 +51,7 @@ import { putStepState, getStepState, dropStepState } from "./step-state.ts";
|
|
|
51
51
|
import { stageRunInputs, type RunInputFile } from "./storage.ts";
|
|
52
52
|
import { INPUTS_DIR, stagedLine } from "./run-inputs.ts";
|
|
53
53
|
import { textBesideInputs } from "./input-text.ts";
|
|
54
|
+
import { readPlain, readPlainText, UnsafeFileError } from "./safe-open.ts";
|
|
54
55
|
|
|
55
56
|
/** What crosses the boundary. Everything in here is values — pre-resolved
|
|
56
57
|
* secrets in headers, assembled prompt, serializable MCP configs. */
|
|
@@ -555,8 +556,8 @@ export function applyContainerChanges(
|
|
|
555
556
|
// the same rule as every file below.
|
|
556
557
|
const dir = path.join(containerWs, ".foldrun");
|
|
557
558
|
const file = path.join(dir, "copied-back.json");
|
|
558
|
-
if (fs.lstatSync(dir).isDirectory()
|
|
559
|
-
const m = JSON.parse(
|
|
559
|
+
if (fs.lstatSync(dir).isDirectory()) {
|
|
560
|
+
const m = JSON.parse(readPlainText(file, { root: containerWs, maxBytes: 16 * 1024 * 1024 }));
|
|
560
561
|
if (m && typeof m === "object" && !Array.isArray(m)) {
|
|
561
562
|
for (const [rel, h] of Object.entries(m as Record<string, unknown>)) {
|
|
562
563
|
// Every version the host handed back for the path counts: two jobs
|
|
@@ -592,7 +593,19 @@ export function applyContainerChanges(
|
|
|
592
593
|
if (opts.drop && (posix.startsWith(opts.drop) || `${posix}/` === opts.drop)) continue;
|
|
593
594
|
if (opts.keepOnly && !posix.startsWith(opts.keepOnly)) continue;
|
|
594
595
|
if (!allowedBack(rel)) continue;
|
|
595
|
-
|
|
596
|
+
// Read from a descriptor opened without following a link, inside the
|
|
597
|
+
// sandbox's folder: the walk's readdir said "regular file" a moment ago,
|
|
598
|
+
// and the step may have swapped it for a link to the host's
|
|
599
|
+
// /proc/self/environ, or a FIFO that would block this read forever
|
|
600
|
+
// (SYMRACE). Such a path is skipped and said, like any other refusal.
|
|
601
|
+
let next: Buffer;
|
|
602
|
+
try {
|
|
603
|
+
next = readPlain(abs, { root: containerWs });
|
|
604
|
+
} catch (err) {
|
|
605
|
+
if (!(err instanceof UnsafeFileError)) throw err;
|
|
606
|
+
note?.(`${posix} was not copied back: ${err.message}`);
|
|
607
|
+
continue;
|
|
608
|
+
}
|
|
596
609
|
// What the step was handed: its bytes (a staging dir) or its hash.
|
|
597
610
|
// null when the file did not exist then; undefined when no baseline.
|
|
598
611
|
let was: Buffer | string | null | undefined;
|
|
@@ -13,6 +13,8 @@ export function refusalText(r: RefusedOutput): string {
|
|
|
13
13
|
return `${r.agent}/${r.path} (${mib(r.bytes)}) was not kept: this run's outputs may total at most ${mib(r.limit ?? 0)}`;
|
|
14
14
|
case "count":
|
|
15
15
|
return `${r.agent}/${r.path} was not kept: a run keeps at most ${r.limit ?? 50_000} files per agent`;
|
|
16
|
+
case "unsafe":
|
|
17
|
+
return `${r.agent}/${r.path} was not kept: it was replaced by a link or a pipe while the run ended, so it was not read`;
|
|
16
18
|
default:
|
|
17
19
|
return `${r.agent}/${r.path} was not kept: its name cannot be stored (control characters, over 400 bytes, or differs from another file only by case)`;
|
|
18
20
|
}
|