Skip to content

Commit 4b2b5bc

Browse files
cxbAsDevsteipete
andauthored
fix(hooks): bound hook workspace manifest and HOOK.md reads (#101472)
* fix(hooks): bound hook workspace manifest and HOOK.md reads * fix(hooks): enforce maxBytes while reading hook metadata fd ClawSweeper review noted that openRootFileSync validates stat size before returning the fd, but the subsequent fs.readFileSync of the fd was unbounded. A file that grows after validation could still OOM workspace discovery. Replace the full fd read with a chunked bounded reader that throws once maxBytes is exceeded, and add regression coverage for the overflow case. * test(hooks): cover bounded hook reads through public workspace API * refactor(hooks): use canonical bounded fd reader for hook metadata * fix(hooks): warn and skip oversized hook metadata during discovery ClawSweeper review required the maintainer-selected oversized-metadata diagnostic contract: warn and skip. readRootFileUtf8 now catches the RangeError from the canonical readFileDescriptorBoundedSync helper and emits one warning per oversized package.json/HOOK.md identifying the path and the byte limit, while discovery continues for other hooks. The redundant open-time maxBytes stat check is removed so the shared bounded reader is the single owner of the byte cap; overflow always surfaces as RangeError, keeping the warning accurate for both static oversized files and post-open growth. Add focused tests: warning content for both oversized surfaces, continued discovery alongside an oversized hook, exact-limit acceptance, and the plain-hook fallback when a package manifest is oversized. * chore: retrigger CI after rebase * refactor(hooks): tighten bounded metadata coverage --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 2920ec1 commit 4b2b5bc

2 files changed

Lines changed: 110 additions & 3 deletions

File tree

src/hooks/workspace.test.ts

Lines changed: 95 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,16 @@
22
import fs from "node:fs";
33
import os from "node:os";
44
import path from "node:path";
5-
import { describe, expect, it } from "vitest";
5+
import { beforeEach, describe, expect, it, vi } from "vitest";
66
import { MANIFEST_KEY } from "../compat/legacy-names.js";
77
import { loadWorkspaceHookEntries } from "./workspace.js";
88

9+
const { warnMock } = vi.hoisted(() => ({ warnMock: vi.fn() }));
10+
11+
vi.mock("../logging/subsystem.js", () => ({
12+
createSubsystemLogger: () => ({ warn: warnMock }),
13+
}));
14+
915
function writeHookPackageManifest(pkgDir: string, hooks: string[]): void {
1016
fs.writeFileSync(
1117
path.join(pkgDir, "package.json"),
@@ -62,7 +68,38 @@ function loadWorkspaceEntriesFromHooksRoot(hooksRoot: string) {
6268
});
6369
}
6470

71+
const METADATA_MAX_BYTES = 1024 * 1024;
72+
73+
function writePlainHook(hooksRoot: string, name: string, content?: string): string {
74+
const hookDir = path.join(hooksRoot, name);
75+
fs.mkdirSync(hookDir, { recursive: true });
76+
fs.writeFileSync(path.join(hookDir, "HOOK.md"), content ?? `---\nname: ${name}\n---\n`);
77+
fs.writeFileSync(path.join(hookDir, "handler.js"), "export default async () => {};\n");
78+
return hookDir;
79+
}
80+
81+
function oversizedMetadataWarnings(filePath: string): string[] {
82+
return warnMock.mock.calls
83+
.map(([message]) => String(message))
84+
.filter((message) => message.includes(filePath) && message.includes(`${METADATA_MAX_BYTES}`));
85+
}
86+
87+
function padToExactBytes(content: string, targetBytes: number): string {
88+
const padding = targetBytes - Buffer.byteLength(content, "utf8");
89+
return padding > 0 ? content + " ".repeat(padding) : content;
90+
}
91+
92+
function exactSizeHookPackageManifest(targetBytes: number): string {
93+
const base = { name: "pkg", [MANIFEST_KEY]: { hooks: ["./nested"] }, pad: "" };
94+
const baseBytes = Buffer.byteLength(JSON.stringify(base), "utf8");
95+
return JSON.stringify({ ...base, pad: "x".repeat(targetBytes - baseBytes) });
96+
}
97+
6598
describe("hooks workspace", () => {
99+
beforeEach(() => {
100+
warnMock.mockClear();
101+
});
102+
66103
it("ignores package.json hook paths that traverse outside package directory", () => {
67104
const root = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-hooks-workspace-"));
68105
const hooksRoot = path.join(root, "hooks");
@@ -100,6 +137,63 @@ describe("hooks workspace", () => {
100137
expect(hookNames(entries)).toContain("nested");
101138
});
102139

140+
it("warns, skips oversized metadata, and continues discovering other hooks", () => {
141+
const root = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-hooks-oversized-mixed-"));
142+
const hooksRoot = path.join(root, "hooks");
143+
fs.mkdirSync(hooksRoot, { recursive: true });
144+
145+
const packageDir = path.join(hooksRoot, "big-package");
146+
fs.mkdirSync(packageDir);
147+
const manifestPath = path.join(packageDir, "package.json");
148+
fs.writeFileSync(manifestPath, "x".repeat(METADATA_MAX_BYTES + 1));
149+
150+
const bigHookDir = writePlainHook(hooksRoot, "big-hook", "x".repeat(METADATA_MAX_BYTES + 1));
151+
const bigHookMdPath = path.join(bigHookDir, "HOOK.md");
152+
writePlainHook(hooksRoot, "small-hook");
153+
154+
const entries = loadWorkspaceEntriesFromHooksRoot(hooksRoot);
155+
expect(hookNames(entries)).toEqual(["small-hook"]);
156+
expect(oversizedMetadataWarnings(manifestPath)).toHaveLength(1);
157+
expect(oversizedMetadataWarnings(bigHookMdPath)).toHaveLength(1);
158+
});
159+
160+
it("loads hooks whose metadata sits exactly at the byte limit", () => {
161+
const root = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-hooks-exact-limit-"));
162+
const hooksRoot = path.join(root, "hooks");
163+
fs.mkdirSync(hooksRoot, { recursive: true });
164+
165+
const pkgDir = path.join(hooksRoot, "pkg");
166+
const nested = path.join(pkgDir, "nested");
167+
fs.mkdirSync(nested, { recursive: true });
168+
fs.writeFileSync(
169+
path.join(pkgDir, "package.json"),
170+
exactSizeHookPackageManifest(METADATA_MAX_BYTES),
171+
);
172+
fs.writeFileSync(
173+
path.join(nested, "HOOK.md"),
174+
padToExactBytes("---\nname: exact-limit\n---\n", METADATA_MAX_BYTES),
175+
);
176+
fs.writeFileSync(path.join(nested, "handler.js"), "export default async () => {};\n");
177+
178+
const entries = loadWorkspaceEntriesFromHooksRoot(hooksRoot);
179+
expect(hookNames(entries)).toContain("exact-limit");
180+
expect(warnMock).not.toHaveBeenCalled();
181+
});
182+
183+
it("still loads a plain hook when its package.json is oversized", () => {
184+
const root = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-hooks-oversized-compat-"));
185+
const hooksRoot = path.join(root, "hooks");
186+
fs.mkdirSync(hooksRoot, { recursive: true });
187+
188+
const hookDir = writePlainHook(hooksRoot, "compat-hook");
189+
const manifestPath = path.join(hookDir, "package.json");
190+
fs.writeFileSync(manifestPath, "x".repeat(METADATA_MAX_BYTES + 1), "utf8");
191+
192+
const entries = loadWorkspaceEntriesFromHooksRoot(hooksRoot);
193+
expect(hookNames(entries)).toContain("compat-hook");
194+
expect(oversizedMetadataWarnings(manifestPath)).toHaveLength(1);
195+
});
196+
103197
it("ignores package.json hook paths that escape via symlink", () => {
104198
const root = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-hooks-workspace-link-"));
105199
const hooksRoot = path.join(root, "hooks");

src/hooks/workspace.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { normalizeTrimmedStringList } from "@openclaw/normalization-core/string-
55
import { MANIFEST_KEY } from "../compat/legacy-names.js";
66
import type { OpenClawConfig } from "../config/types.openclaw.js";
77
import { openRootFileSync } from "../infra/boundary-file-read.js";
8+
import { readFileDescriptorBoundedSync } from "../infra/file-descriptor-read.js";
89
import { createSubsystemLogger } from "../logging/subsystem.js";
910
import { isPathInsideWithRealpath } from "../security/scan-paths.js";
1011
import { CONFIG_DIR, resolveUserPath } from "../utils.js";
@@ -18,6 +19,10 @@ import { resolvePluginHookDirs } from "./plugin-hooks.js";
1819
import { resolveHookEntries } from "./policy.js";
1920
import type { Hook, HookEntry, HookSource, ParsedHookFrontmatter } from "./types.js";
2021

22+
// Hook descriptors are small metadata. Bounding the pinned descriptor read also
23+
// covers files that grow after the boundary open validates their identity.
24+
const HOOK_METADATA_MAX_BYTES = 1024 * 1024;
25+
2126
type HookPackageManifest = {
2227
name?: string;
2328
} & Partial<Record<typeof MANIFEST_KEY, { hooks?: string[] }>>;
@@ -34,6 +39,7 @@ function readHookPackageManifest(dir: string): HookPackageManifest | null {
3439
absolutePath: manifestPath,
3540
rootPath: dir,
3641
boundaryLabel: "hook package directory",
42+
maxBytes: HOOK_METADATA_MAX_BYTES,
3743
});
3844
if (raw === null) {
3945
return null;
@@ -73,6 +79,7 @@ function loadHookFromDir(params: {
7379
absolutePath: hookMdPath,
7480
rootPath: params.hookDir,
7581
boundaryLabel: "hook directory",
82+
maxBytes: HOOK_METADATA_MAX_BYTES,
7683
});
7784
if (content === null) {
7885
return null;
@@ -293,11 +300,17 @@ function readRootFileUtf8(params: {
293300
absolutePath: string;
294301
rootPath: string;
295302
boundaryLabel: string;
303+
maxBytes: number;
296304
}): string | null {
297305
return withOpenedRootFileSync(params, (opened) => {
298306
try {
299-
return fs.readFileSync(opened.fd, "utf-8");
300-
} catch {
307+
return readFileDescriptorBoundedSync(opened.fd, params.maxBytes).toString("utf-8");
308+
} catch (err) {
309+
if (err instanceof RangeError) {
310+
log.warn(
311+
`Ignoring oversized hook metadata ${params.absolutePath}: file exceeds the ${params.maxBytes}-byte limit`,
312+
);
313+
}
301314
return null;
302315
}
303316
});

0 commit comments

Comments
 (0)