Skip to content

Commit 89bb601

Browse files
authored
fix(qa): replace Linux-only /proc probes in the Telegram proof harness (#127718)
The Mantis lane and the Telegram user driver reached for /proc to enforce media containment and to prove a pid was still alive. Off Linux those paths do not exist, so the containment check compared a literal "/proc/self/fd/N" string against the output root and refused every file, while both liveness probes silently reported "gone": the lane stole a held harness lock and the driver deleted the observer pid file without ever signalling the process. Containment now uses each runtime's strongest portable construct. Python descends the media path one component at a time from an open directory descriptor (O_DIRECTORY|O_NOFOLLOW, dir_fd), which is race-free and also covers the intermediate directories the old leaf-only O_NOFOLLOW did not. Node has no openat(2), so publicRelativePath re-walks the resolved components after the descriptor is open and refuses any that became a symlink. Liveness moves to process.kill(pid, 0) and to ps state/args, which keeps the pid-reuse and zombie handling the /proc reads provided. The compound-command approval binding test asserted an operand count that only held where the host interpreters live in a root-owned prefix; a Homebrew python3 is writable, so it correctly binds as a third executable operand. Assert the script operands by path instead.
1 parent 0a70481 commit 89bb601

6 files changed

Lines changed: 117 additions & 33 deletions

‎scripts/e2e/telegram-mantis-lane.ts‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,16 @@ function publicRelativePath(root: string, file: string, label: string): string {
234234
if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {
235235
throw new Error(`${label} must be inside the Mantis output directory.`);
236236
}
237+
// Node has no openat(2), so containment is re-proven component by component: a directory
238+
// swapped for a symlink after the caller resolved the path would otherwise route an
239+
// already-open descriptor outside the root, which O_NOFOLLOW only prevents for the leaf.
240+
let cursor = resolvedRoot;
241+
for (const segment of relative.split(path.sep)) {
242+
cursor = path.join(cursor, segment);
243+
if (fs.lstatSync(cursor).isSymbolicLink()) {
244+
throw new Error(`${label} must be inside the Mantis output directory.`);
245+
}
246+
}
237247
return relative;
238248
}
239249

@@ -244,11 +254,11 @@ function readPublicFile(
244254
maxBytes: number,
245255
): { relative: string; text: string } {
246256
const resolved = fs.realpathSync(input);
247-
publicRelativePath(root, resolved, label);
248257
const descriptor = fs.openSync(resolved, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
249258
try {
250-
const opened = fs.realpathSync(`/proc/self/fd/${descriptor}`);
251-
const relative = publicRelativePath(root, opened, label);
259+
// Containment is checked after the open so the descriptor being read is the file the
260+
// check accepted, not one a concurrent swap redirected it to.
261+
const relative = publicRelativePath(root, resolved, label);
252262
const stat = fs.fstatSync(descriptor);
253263
if (!stat.isFile() || stat.size > maxBytes) {
254264
throw new Error(`${label} must be a regular file no larger than ${maxBytes} bytes.`);
@@ -297,6 +307,16 @@ function saveActive(sessionRoot: string, state: ActiveSession): void {
297307
writeJsonAtomic(activeFile(sessionRoot, state.lane), state);
298308
}
299309

310+
function processIsAlive(pid: number): boolean {
311+
try {
312+
process.kill(pid, 0);
313+
return true;
314+
} catch (error) {
315+
// EPERM means the pid exists under another user; only ESRCH proves the lock owner is gone.
316+
return (error as NodeJS.ErrnoException).code === "EPERM";
317+
}
318+
}
319+
300320
function acquireHarnessLock(sessionRoot: string): () => void {
301321
const lock = path.join(sessionRoot, "harness.lock");
302322
for (let attempt = 0; attempt < 2; attempt += 1) {
@@ -314,7 +334,7 @@ function acquireHarnessLock(sessionRoot: string): () => void {
314334
throw error;
315335
}
316336
const owner = Number(fs.readFileSync(lock, "utf8").trim());
317-
if (Number.isInteger(owner) && owner > 0 && fs.existsSync(`/proc/${owner}`)) {
337+
if (Number.isInteger(owner) && owner > 0 && processIsAlive(owner)) {
318338
throw new Error("The shared Telegram harness already has a command in progress.", {
319339
cause: error,
320340
});

‎scripts/e2e/telegram-user-driver.py‎

Lines changed: 40 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,22 @@ def read_json(path):
3434
return {}
3535

3636

37+
def open_contained_file(root, relative):
38+
"""Opens a file under root, descending one component at a time from an open directory
39+
descriptor so no symlink can be traversed and no directory can be swapped mid-walk.
40+
Anchoring on descriptors is what keeps containment true without Linux-only /proc paths."""
41+
parent = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
42+
try:
43+
*directories, name = relative.parts
44+
for directory in directories:
45+
child = os.open(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent)
46+
os.close(parent)
47+
parent = child
48+
return os.open(name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=parent)
49+
finally:
50+
os.close(parent)
51+
52+
3753
def write_json_private(path, data):
3854
path.parent.mkdir(parents=True, exist_ok=True)
3955
path.parent.chmod(stat.S_IRWXU)
@@ -764,24 +780,18 @@ def resolve_message_id(self, value):
764780

765781
def resolve_media(self, value):
766782
relative = Path(value)
767-
if relative.is_absolute() or ".." in relative.parts:
783+
if relative.is_absolute() or not relative.parts or ".." in relative.parts:
768784
raise DriverError("Media must be inside the Mantis output directory.")
769-
media = self.media_root / relative
770785
try:
771-
descriptor = os.open(media, os.O_RDONLY | os.O_NOFOLLOW)
786+
descriptor = open_contained_file(self.media_root, relative)
772787
except OSError as error:
773788
raise DriverError("Media must be a regular file inside the Mantis output directory.") from error
774789
try:
775-
opened = Path(os.path.realpath(f"/proc/self/fd/{descriptor}"))
776-
try:
777-
opened.relative_to(self.media_root)
778-
except ValueError as error:
779-
raise DriverError("Media must be inside the Mantis output directory.") from error
780790
if not stat.S_ISREG(os.fstat(descriptor).st_mode):
781791
raise DriverError("Media must be a regular file no larger than 20 MiB.")
782792
staging_dir = self.media_staging / f"upload-{secrets.token_hex(8)}"
783793
staging_dir.mkdir(mode=0o700)
784-
target = staging_dir / opened.name
794+
target = staging_dir / relative.name
785795
target_descriptor = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
786796
try:
787797
copied = 0
@@ -972,6 +982,22 @@ def command_serve(args):
972982
pid_path.unlink(missing_ok=True)
973983

974984

985+
def running_process_command_line(pid):
986+
"""Returns the argv pid is running under, or None once it is gone, so pid reuse cannot
987+
redirect cleanup at an unrelated process group. Zombies hold their table entry until
988+
they are reaped, so their pid cannot be reused and they count as already gone."""
989+
result = subprocess.run(
990+
["ps", "-p", str(pid), "-o", "state=", "-o", "args="],
991+
capture_output=True,
992+
check=False,
993+
text=True,
994+
)
995+
state, _, command_line = result.stdout.strip().partition(" ")
996+
if result.returncode != 0 or not state or state.startswith("Z"):
997+
return None
998+
return command_line.strip()
999+
1000+
9751001
def command_terminate_observer(args):
9761002
pid_path = Path(args.pid_file)
9771003
try:
@@ -990,32 +1016,20 @@ def command_terminate_observer(args):
9901016
pgid = int(value.get("pgid") or 0)
9911017
if value.get("socket") != args.socket or pid <= 0 or pgid <= 0 or pgid == os.getpgrp():
9921018
raise DriverError("Telegram observer pid file is invalid.")
993-
process_stat = Path(f"/proc/{pid}/stat")
994-
995-
def running():
996-
try:
997-
return process_stat.read_text().rsplit(")", 1)[1].split()[0] not in {"X", "Z"}
998-
except FileNotFoundError:
999-
return False
1000-
1001-
try:
1002-
command_line = Path(f"/proc/{pid}/cmdline").read_bytes()
1003-
except FileNotFoundError:
1004-
command_line = b""
1005-
# Zombies retain their proc entry with an empty command line; they are not reused PIDs.
1006-
if not running():
1019+
command_line = running_process_command_line(pid)
1020+
if command_line is None:
10071021
pid_path.unlink(missing_ok=True)
10081022
return
1009-
if b"telegram-user-driver" not in command_line or args.socket.encode() not in command_line or b"serve" not in command_line:
1023+
if "telegram-user-driver" not in command_line or args.socket not in command_line or "serve" not in command_line:
10101024
raise DriverError("Telegram observer process identity changed before cleanup.")
10111025
try:
10121026
os.killpg(pgid, signal.SIGTERM)
10131027
except ProcessLookupError:
10141028
pass
10151029
deadline = time.monotonic() + 2
1016-
while running() and time.monotonic() < deadline:
1030+
while running_process_command_line(pid) is not None and time.monotonic() < deadline:
10171031
time.sleep(0.05)
1018-
if running():
1032+
if running_process_command_line(pid) is not None:
10191033
try:
10201034
os.killpg(pgid, signal.SIGKILL)
10211035
except ProcessLookupError:

‎src/infra/system-run-approval-binding.test.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,9 @@ describe("missingSystemRunApprovalBinding", () => {
335335

336336
describe("mutable file operand binding", () => {
337337
it("binds every script in a compound command and detects drift", async () => {
338-
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-system-run-binding-"));
338+
const cwd = fs.realpathSync(
339+
fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-system-run-binding-")),
340+
);
339341
const first = path.join(cwd, "first.sh");
340342
const second = path.join(cwd, "second.py");
341343
try {
@@ -344,7 +346,14 @@ describe("mutable file operand binding", () => {
344346
const command = { kind: "shell" as const, text: "sh first.sh && python3 second.py" };
345347
const prepared = expectOk(await prepareSystemRunMutableFileBinding({ command, cwd }));
346348

347-
expect(prepared.binding.operands).toHaveLength(2);
349+
// Assert the script operands by path: a host whose interpreters live in a writable
350+
// prefix (Homebrew, asdf, nix profiles) also binds those executables, so an operand
351+
// count would only describe the host that ran the test.
352+
expect(
353+
prepared.binding.operands
354+
.filter((operand) => !operand.executable)
355+
.map((operand) => operand.snapshot.path),
356+
).toEqual([first, second]);
348357
await expect(
349358
revalidateSystemRunMutableFileBinding({ binding: prepared.binding, cwd }),
350359
).resolves.toEqual({ ok: true });

‎test/scripts/mantis-telegram-desktop-proof-workflow.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1001,7 +1001,7 @@ describe("Mantis Telegram Desktop proof workflow", () => {
10011001
expect(sutScript).not.toContain("...process.env,\n MOCK_PORT");
10021002
expect(laneScript).toContain("function commandEnv()");
10031003
expect(laneScript).toContain("fs.constants.O_NOFOLLOW");
1004-
expect(laneScript).toContain("/proc/self/fd/${descriptor}");
1004+
expect(laneScript).toContain("isSymbolicLink()");
10051005
expect(laneScript).not.toContain("readRecorderSession");
10061006
expect(laneScript).toContain('"artifacts"');
10071007
expect(laneScript).toContain(

‎test/scripts/telegram-mantis-lane.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,37 @@ describe("Telegram Mantis free-form lane", () => {
340340
}
341341
});
342342

343+
it("reads nested public files but refuses symlinked directory components", async () => {
344+
const harness = await setupHarness();
345+
const outside = path.join(path.dirname(harness.outputRoot), "outside.txt");
346+
fs.writeFileSync(outside, "not allowed");
347+
fs.mkdirSync(path.join(harness.outputRoot, "nested"));
348+
fs.writeFileSync(path.join(harness.outputRoot, "nested", "body.txt"), "nested body");
349+
fs.symlinkSync(path.dirname(harness.outputRoot), path.join(harness.outputRoot, "escape"));
350+
try {
351+
await runLane(harness.env, [
352+
"send",
353+
"--lane",
354+
"candidate",
355+
"--text-file",
356+
path.join(harness.outputRoot, "nested", "body.txt"),
357+
]);
358+
expect(harness.requests).toEqual([{ command: "send", text: "nested body" }]);
359+
await expect(
360+
runLane(harness.env, [
361+
"send",
362+
"--lane",
363+
"candidate",
364+
"--text-file",
365+
path.join(harness.outputRoot, "escape", "outside.txt"),
366+
]),
367+
).rejects.toThrow("--text-file must be inside the Mantis output directory");
368+
expect(harness.requests).toEqual([{ command: "send", text: "nested body" }]);
369+
} finally {
370+
await harness.close();
371+
}
372+
});
373+
343374
it("runs scenario-authored actions inside the ephemeral desktop", async () => {
344375
const harness = await setupHarness();
345376
const actions = path.join(harness.outputRoot, "click-picker.json");

‎test/scripts/telegram-user-observer.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,12 @@ with tempfile.TemporaryDirectory() as root:
6666
media_error = ""
6767
except module.DriverError as error:
6868
media_error = str(error)
69+
(public / "escape").symlink_to(private)
70+
try:
71+
observer.resolve_media("escape/credential.txt")
72+
directory_escape_error = ""
73+
except module.DriverError as error:
74+
directory_escape_error = str(error)
6975
observer.ingest({
7076
"@type": "updateNewMessage",
7177
"message": {
@@ -216,6 +222,7 @@ with tempfile.TemporaryDirectory() as root:
216222
print(json.dumps({
217223
"bystanderError": bystander_error,
218224
"deleted": deleted,
225+
"directoryEscapeError": directory_escape_error,
219226
"documentContent": module.UserDriver.document_content(None, "/tmp/proof.txt", "proof"),
220227
"events": observer.events,
221228
"foreignAlive": foreign_alive,
@@ -274,6 +281,9 @@ describe("Telegram user observer", () => {
274281
expect(value.mediaError).toBe(
275282
"Media must be a regular file inside the Mantis output directory.",
276283
);
284+
expect(value.directoryEscapeError).toBe(
285+
"Media must be a regular file inside the Mantis output directory.",
286+
);
277287
expect(value.documentContent).toEqual({
278288
"@type": "inputMessageDocument",
279289
caption: { "@type": "formattedText", entities: [], text: "proof" },

0 commit comments

Comments
 (0)