Skip to content

Commit 527f09e

Browse files
author
hzq
committed
Enforce local file limits on bytes actually read
Read regular inputs through EOF on the same descriptor. Allow short reads and in-budget growth without returning partial or oversized contents, and refuse special files without waiting for a writer. Improvement-Round: 5/10 after v0.0.74
1 parent a2cdb4a commit 527f09e

5 files changed

Lines changed: 354 additions & 8 deletions

File tree

‎docs/operations.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,8 @@ The gateway client copies each response chunk when it reads it. Files, skill res
158158

159159
CLI callers can complete the same workflow without the console: `oaa upload SELECTED_FILE`, `oaa invoke ... --idempotency-key KEY`, `oaa wait RESPONSE_ID`, `oaa output RESPONSE_ID`, `oaa artifacts RESPONSE_ID`, and `oaa download FILE_ID --out NEW_FILE`. Use `--url` and `--token-file` or `OAA_GATEWAY_URL` / `OAA_TOKEN_FILE`. Downloads never overwrite an existing file.
160160

161+
Uploads, worker file reads and selected bundle assets read a regular file from one open handle. Both its reported size and the bytes observed through EOF must fit the applicable limit. A file growing past the limit fails with `invalid_file` rather than returning a truncated payload. This is not a snapshot of concurrent in-place edits; finish saving the input first when a specific version matters.
162+
161163
`download --out` and `agent --out` write and flush a sibling staging file before publishing the requested name. A disk error or a killed process cannot make a partial download occupy that name. Concurrent downloads have one winner. On volumes without hard links, the CLI tries a system-provided exclusive move (on Linux this fallback uses `/usr/bin/python3` and libc). If neither primitive is available, `download_publish_unavailable` reports the complete staged file to recover; it does not report a successful download to the destination. A hard stop can leave a hidden `.oaa-download-*` directory. Other downloads do not reuse or delete it.
162164

163165
Publishing a native agent requires an enabled worker adapter as well as the MCP entry. Merely reading an MCP server does not export the caller's process, private plugins, or desktop login state.

‎docs/zh-CN/operations.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,8 @@ MCP 的任务工作流是 `oaa_upload_text`(可选)、`oaa_preview_route`、
165165

166166
CLI 调用方不用控制台也能完成同样的工作流:`oaa upload SELECTED_FILE`、`oaa invoke ... --idempotency-key KEY`、`oaa wait RESPONSE_ID`、`oaa output RESPONSE_ID`、`oaa artifacts RESPONSE_ID`、`oaa download FILE_ID --out NEW_FILE`。使用 `--url` 与 `--token-file`,或 `OAA_GATEWAY_URL` / `OAA_TOKEN_FILE`。下载从不覆盖已有文件。
167167

168+
上传、工作节点读取文件和打包选中的资源时,都从同一个已打开的普通文件读取。文件报告的大小和读到末尾的实际字节数都必须在各自的上限内;中途追加到超限会返回 `invalid_file`,不会把截断内容当作成功结果。它不提供并发原地改写的快照,需要特定版本时请先完成保存。
169+
168170
`download --out` 和 `agent --out` 先在目标旁边写完暂存文件并刷盘,再让完整文件出现在指定名称下。写盘失败或进程被强制结束不会让半份下载占住目标;两个下载同时写同名文件时只有一个能成功。不支持硬链接的卷会尝试系统提供的不覆盖移动操作(Linux 的这条备用路径使用 `/usr/bin/python3` 和 libc)。如果两种操作都不可用,`download_publish_unavailable` 会指出完整文件的暂存位置,不会把目标报成下载成功。强制结束可能留下隐藏的 `.oaa-download-*` 目录,后续下载不会复用或删除它。
169171

170172
发布一个原生智能体,除了 MCP 入口,还需要一个已启用的 worker 适配器。仅仅读取一个 MCP 服务器,并不会导出调用方的进程、私有插件或桌面登录状态。

‎src/core/local-file-bytes.ts‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import type { FileHandle } from 'node:fs/promises';
2+
import { constants as bufferLimits } from 'node:buffer';
3+
import { LIMITS } from './limits.js';
4+
5+
const READ_WINDOW = 1024 * 1024;
6+
const MAX_INITIAL_HINT = 8 * READ_WINDOW;
7+
8+
/** Return bytes only at EOF. A non-regular file, inadmissible size or the first byte over
9+
* budget refuses the whole read. The caller owns and closes the descriptor. */
10+
export async function readLocalFileBytes(
11+
file: FileHandle,
12+
budget: number,
13+
): Promise<Buffer | undefined> {
14+
const maximum = Math.min(budget, bufferLimits.MAX_LENGTH);
15+
const stat = await file.stat(),
16+
size = stat.size;
17+
if (
18+
!stat.isFile() ||
19+
!Number.isSafeInteger(budget) ||
20+
budget < 0 ||
21+
!Number.isSafeInteger(size) ||
22+
size < 0 ||
23+
size > maximum
24+
)
25+
return undefined;
26+
let block = Buffer.allocUnsafeSlow(size <= MAX_INITIAL_HINT ? size : 64 * 1024);
27+
let largeHint = size > MAX_INITIAL_HINT && size <= LIMITS.maxArtifactExportBytes ? size : 0;
28+
let full: Buffer[] | undefined;
29+
let used = 0,
30+
total = 0;
31+
const probe = Buffer.allocUnsafe(1);
32+
33+
for (;;) {
34+
if (used < block.length) {
35+
const { bytesRead } = await file.read(
36+
block,
37+
used,
38+
Math.min(block.length - used, READ_WINDOW),
39+
null,
40+
);
41+
if (!bytesRead) break;
42+
used += bytesRead;
43+
total += bytesRead;
44+
continue;
45+
}
46+
47+
// Reaching the reported size, even zero or the exact limit, is not EOF.
48+
if (!(await file.read(probe, 0, 1, null)).bytesRead) break;
49+
if (total === maximum) return undefined;
50+
const hint = largeHint;
51+
largeHint = 0;
52+
if (hint && (await file.stat()).size === hint) {
53+
// A large regular file can still use one contiguous result. Read a prefix and
54+
// recheck the same descriptor first rather than reserving a stale large size.
55+
const next = Buffer.allocUnsafeSlow(hint);
56+
block.copy(next, 0, 0, used);
57+
block = next;
58+
} else {
59+
if (block.length) (full ??= []).push(block);
60+
const growth = Math.min(READ_WINDOW, Math.max(4096, block.length * 2));
61+
block = Buffer.allocUnsafeSlow(Math.min(maximum - total, growth));
62+
used = 0;
63+
}
64+
block[used++] = probe[0]!;
65+
total++;
66+
}
67+
if (!full && used === block.length) return block;
68+
// Do not return unfilled bytes or keep a stale size hint alive through a short view.
69+
const out = Buffer.allocUnsafeSlow(total);
70+
let offset = 0;
71+
if (full) for (const part of full) offset += part.copy(out, offset);
72+
block.copy(out, offset, 0, used);
73+
return out;
74+
}

‎src/core/util.ts‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { TOOL_RESULT_JSON_BYTES } from './limits.js';
33
import { resolveWindowsCommand } from './which.js';
44
import { restrictToOwner } from './win-acl.js';
55
import { windowsUnsafeSegment } from './win-path.js';
6+
import { readLocalFileBytes } from './local-file-bytes.js';
67
import { constants, accessSync, statSync } from 'node:fs';
78
import { mkdir, lstat, realpath, readFile, open } from 'node:fs/promises';
89
import path from 'node:path';
@@ -198,7 +199,16 @@ export function relativeName(name: string): string {
198199
}
199200
return name;
200201
}
201-
export async function safePath(root: string, name: string, createParents = false): Promise<string> {
202+
const invalidFile = () =>
203+
new Fault('invalid_file', 'Not a regular file, or file exceeds size limit.', 413);
204+
export function safePath(root: string, name: string, createParents = false): Promise<string> {
205+
return checkedPath(root, name, createParents ? 'create-parents' : 'resolve');
206+
}
207+
async function checkedPath(
208+
root: string,
209+
name: string,
210+
mode: 'resolve' | 'create-parents' | 'read-file',
211+
): Promise<string> {
202212
relativeName(name);
203213
await mkdir(root, { recursive: true, mode: 0o700 });
204214
const base = await realpath(root);
@@ -210,9 +220,10 @@ export async function safePath(root: string, name: string, createParents = false
210220
const stat = await lstat(current);
211221
if (stat.isSymbolicLink() || (i < pieces.length - 1 && !stat.isDirectory()))
212222
throw new Fault('invalid_path', 'Symlinks and non-directory parents are not allowed.');
223+
if (mode === 'read-file' && i === pieces.length - 1 && !stat.isFile()) throw invalidFile();
213224
} catch (e) {
214225
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;
215-
if (i < pieces.length - 1 && createParents) await mkdir(current, { mode: 0o700 });
226+
if (i < pieces.length - 1 && mode === 'create-parents') await mkdir(current, { mode: 0o700 });
216227
}
217228
}
218229
return current;
@@ -247,13 +258,17 @@ export async function readBounded(
247258
name: string,
248259
max = 8 * 1024 * 1024,
249260
): Promise<Buffer> {
250-
const target = await safePath(root, name);
251-
const handle = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
261+
if (!Number.isSafeInteger(max) || max < 0)
262+
throw new Fault('invalid_file', 'File byte limit must be a non-negative safe integer.', 400);
263+
const target = await checkedPath(root, name, 'read-file');
264+
const handle = await open(
265+
target,
266+
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),
267+
);
252268
try {
253-
const s = await handle.stat();
254-
if (!s.isFile() || s.size > max)
255-
throw new Fault('invalid_file', 'Not a regular file, or file exceeds size limit.', 413);
256-
return await handle.readFile();
269+
const bytes = await readLocalFileBytes(handle, max);
270+
if (bytes === undefined) throw invalidFile();
271+
return bytes;
257272
} finally {
258273
await handle.close();
259274
}

0 commit comments

Comments
 (0)