Skip to content

Commit adf5c67

Browse files
authored
test(exec): cover companion response loss without local replay (#131961)
* test(exec): characterize companion response loss without local replay Exercise signed Unix socket requests, real native execution, and enforced routing after a lost response. Clarify that HOST=app already requires the companion; FALLBACK does not change current routing. This records the nullable transport ambiguity without changing production behavior. * test(exec): stabilize transport proof fixtures Use socket-owner readiness and awaited shutdown for the real native proof. Freeze the JSONL deadline instead of asserting wall-clock latency, and align fixture types with the existing test helpers. * test(macos): observe native cancellation fixture readiness Wait for registered PID-marker observation or a real native terminal response before injecting cancellation. Gate the sentinel delay on readiness and drain failure cleanup before removing fixture state. Cover slow admission, early native failures, and incomplete PID publication without changing production behavior. * test(exec): register and validate native proof client
1 parent 39df7ec commit adf5c67

8 files changed

Lines changed: 1028 additions & 176 deletions

File tree

‎apps/macos/Tests/OpenClawIPCTests/ExecHostSocketCancellationTests.swift‎

Lines changed: 249 additions & 51 deletions
Large diffs are not rendered by default.
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import Foundation
2+
import OpenClawKit
3+
import Testing
4+
@testable import OpenClaw
5+
6+
/// Opt-in, process-isolated proof of real native execution after caller response loss.
7+
@Suite(.serialized)
8+
@MainActor
9+
struct ExecHostTransportProofTests {
10+
@Test(.enabled(if: ProcessInfo.processInfo.environment["OPENCLAW_EXEC_HOST_NATIVE_PROOF"] == "1"))
11+
func `native execution completes after caller response loss`() async throws {
12+
let environment = ProcessInfo.processInfo.environment
13+
let statePath = try #require(environment["OPENCLAW_STATE_DIR"])
14+
let state = URL(fileURLWithPath: statePath).resolvingSymlinksInPath()
15+
let root = state.deletingLastPathComponent()
16+
try #require(root.deletingLastPathComponent().path == URL(fileURLWithPath: "/tmp").resolvingSymlinksInPath()
17+
.path)
18+
try #require(root.lastPathComponent.hasPrefix("oc-exec-native-"))
19+
for key in ["HOME", "CFFIXED_USER_HOME", "OPENCLAW_HOME"] {
20+
let value = try #require(environment[key])
21+
try #require(URL(fileURLWithPath: value).resolvingSymlinksInPath().path == root
22+
.appendingPathComponent("home").path)
23+
}
24+
try #require(ExecApprovalsStore.databaseURL().resolvingSymlinksInPath().path ==
25+
ExecApprovalsSQLiteStore.databaseURL(stateDirectoryURL: state).resolvingSymlinksInPath().path)
26+
let socketPath = root.appendingPathComponent("native.sock").path
27+
let token = "exec-host-native-proof-token"
28+
try ExecApprovalsSQLiteStore.write(
29+
ExecApprovalsFile(
30+
version: 1,
31+
socket: ExecApprovalsSocketConfig(path: socketPath, token: token),
32+
defaults: ExecApprovalsDefaults(security: .full, ask: .off, autoAllowSkills: false),
33+
agents: ["denied": ExecApprovalsAgent(security: .deny, ask: .off)]),
34+
stateDirectoryURL: state)
35+
36+
let server = ExecApprovalsSocketServer(
37+
socketPath: socketPath,
38+
token: token,
39+
onPrompt: { _ in
40+
Issue.record("This proof must not request interactive approval")
41+
return .deny
42+
},
43+
onExec: { request in
44+
await ExecApprovalsStore.withStateDirectory(state) {
45+
await ExecHostExecutor.handle(request)
46+
}
47+
},
48+
onUnexpectedStop: { _ in Issue.record("Native proof socket stopped unexpectedly") })
49+
do {
50+
try #require(await server.start())
51+
var repo = URL(fileURLWithPath: #filePath)
52+
for _ in 0..<5 {
53+
repo.deleteLastPathComponent()
54+
}
55+
let child = Process()
56+
child.executableURL = URL(fileURLWithPath: "/usr/bin/env")
57+
child.arguments = [
58+
"node", "--import", "tsx",
59+
repo.appendingPathComponent("src/infra/exec-host.native.test-support.ts").path,
60+
root.path, socketPath,
61+
]
62+
child.currentDirectoryURL = repo
63+
child.environment = environment
64+
let outputURL = root.appendingPathComponent("native-client.log")
65+
FileManager.default.createFile(atPath: outputURL.path, contents: nil)
66+
let output = try FileHandle(forWritingTo: outputURL)
67+
defer { try? output.close() }
68+
child.standardOutput = output
69+
child.standardError = output
70+
let exited = Task { @MainActor in
71+
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Int32, any Error>) in
72+
child.terminationHandler = { process in continuation.resume(returning: process.terminationStatus) }
73+
do { try child.run() } catch { continuation.resume(throwing: error) }
74+
}
75+
}
76+
let exitCode = try await exited.value
77+
try output.close()
78+
let log = try String(contentsOf: outputURL, encoding: .utf8)
79+
#expect(exitCode == 0, "TypeScript boundary proof failed: \(log)")
80+
#expect(log.contains("native START -> response dropped -> client null -> native COMPLETE"))
81+
#expect(log.contains("native success and policy denial verified"))
82+
} catch {
83+
await server.stop().value
84+
throw error
85+
}
86+
await server.stop().value
87+
#expect(!FileManager.default.fileExists(atPath: socketPath))
88+
}
89+
}

‎config/knip.all-exports.config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ const ROOT_TEST_ENTRY_GLOBS = [
3939
"src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts}!",
4040
"scripts/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts}!",
4141
"test/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts}!",
42+
// ExecHostTransportProofTests.swift launches this isolated native client by path.
43+
"src/infra/exec-host.native.test-support.ts!",
4244
// Vitest loads these by configuration or module alias rather than imports.
4345
"test/setup*.ts!",
4446
"test/non-isolated-runner.ts!",

‎docs/nodes/index.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1007,7 +1007,7 @@ Notes:
10071007
- Client instance metadata, signed device identity, and pairing auth use separate state records; see [Headless identity state](#headless-identity-state).
10081008
- Exec approvals are enforced locally via
10091009
`~/.openclaw/state/openclaw.sqlite#exec_approvals_config` (see [Exec approvals](/tools/exec-approvals)).
1010-
- On macOS, the headless node host executes `system.run` locally by default. Set `OPENCLAW_NODE_EXEC_HOST=app` to route `system.run` through the companion app exec host; add `OPENCLAW_NODE_EXEC_FALLBACK=0` to require the app host and fail closed if it is unavailable.
1010+
- On macOS, the headless node host executes `system.run` locally by default. Set `OPENCLAW_NODE_EXEC_HOST=app` to require the companion app exec host, with no local fallback. `OPENCLAW_NODE_EXEC_FALLBACK` does not change current routing.
10111011
- Add `--tls` / `--tls-fingerprint` when the Gateway WS uses TLS.
10121012

10131013
## Mac node mode
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
// Launched only by ExecHostTransportProofTests in a fresh, process-isolated state root.
2+
import assert from "node:assert/strict";
3+
import { once } from "node:events";
4+
import fs from "node:fs/promises";
5+
import net from "node:net";
6+
import path from "node:path";
7+
import { setTimeout as delay } from "node:timers/promises";
8+
import { createDeferred } from "../../test/helpers/promise.js";
9+
import { requestExecHostViaSocket, type ExecHostRequest } from "./exec-host.js";
10+
11+
const [rootArgument, nativeSocket] = process.argv.slice(2);
12+
assert.equal(process.env.OPENCLAW_EXEC_HOST_NATIVE_PROOF, "1");
13+
assert.ok(rootArgument, "Native proof requires an isolated root argument");
14+
assert.ok(nativeSocket, "Native proof requires a socket path argument");
15+
const root = await fs.realpath(rootArgument);
16+
assert.equal(path.dirname(root), await fs.realpath("/tmp"));
17+
assert.ok(path.basename(root).startsWith("oc-exec-native-"));
18+
assert.equal(await fs.realpath(process.env.OPENCLAW_STATE_DIR!), path.join(root, "state"));
19+
const token = "exec-host-native-proof-token";
20+
const marker = path.join(root, "native-markers");
21+
const release = path.join(root, "release-child");
22+
await fs.rm(marker, { force: true });
23+
await fs.rm(release, { force: true });
24+
const request: ExecHostRequest = {
25+
command: [
26+
"/bin/sh",
27+
"-c",
28+
'printf "START\\n" >> "$1"; while [ ! -f "$2" ]; do /bin/sleep 0.01; done; printf "COMPLETE\\n" >> "$1"',
29+
"exec-host-native-proof",
30+
marker,
31+
release,
32+
],
33+
cwd: root,
34+
timeoutMs: 5_000,
35+
needsScreenRecording: false,
36+
};
37+
38+
async function waitForStart() {
39+
const deadline = Date.now() + 3_000;
40+
while (Date.now() < deadline) {
41+
try {
42+
if ((await fs.readFile(marker, "utf8")) === "START\n") {
43+
return;
44+
}
45+
} catch (error) {
46+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
47+
throw error;
48+
}
49+
}
50+
await delay(10);
51+
}
52+
throw new Error("Native child did not write START before the response fault");
53+
}
54+
55+
async function withDeadline<T>(promise: Promise<T>, ms: number): Promise<T> {
56+
let timer: NodeJS.Timeout | undefined;
57+
try {
58+
return await Promise.race([
59+
promise,
60+
new Promise<never>((_, reject) => {
61+
timer = setTimeout(() => reject(new Error("Native proof deadline exceeded")), ms);
62+
}),
63+
]);
64+
} finally {
65+
clearTimeout(timer);
66+
}
67+
}
68+
69+
const success = await requestExecHostViaSocket({
70+
socketPath: nativeSocket,
71+
token,
72+
request: { command: ["/bin/echo", "native-success"], cwd: root, timeoutMs: 5_000 },
73+
timeoutMs: 10_000,
74+
});
75+
assert.equal(success?.ok, true);
76+
if (success?.ok) {
77+
assert.equal(success.payload.success, true);
78+
assert.equal(success.payload.exitCode, 0);
79+
assert.equal(success.payload.stdout, "native-success\n");
80+
}
81+
const denied = await requestExecHostViaSocket({
82+
socketPath: nativeSocket,
83+
token,
84+
request: { ...request, agentId: "denied" },
85+
timeoutMs: 10_000,
86+
});
87+
assert.equal(denied?.ok, false);
88+
if (denied && !denied.ok) {
89+
assert.equal(denied.error.reason, "security=deny");
90+
}
91+
await assert.rejects(fs.stat(marker), { code: "ENOENT" });
92+
console.log("native success and policy denial verified");
93+
94+
const proxySocket = path.join(root, "proxy.sock");
95+
const sockets: net.Socket[] = [];
96+
const closes: Promise<void>[] = [];
97+
const forwarded = createDeferred<net.Socket>();
98+
const nativeResponse = createDeferred<string>();
99+
const errors: Error[] = [];
100+
const order: string[] = [];
101+
function track(socket: net.Socket) {
102+
sockets.push(socket);
103+
closes.push(
104+
new Promise<void>((resolve) => {
105+
socket.once("close", resolve);
106+
}),
107+
);
108+
socket.on("error", (error) => errors.push(error));
109+
}
110+
const proxy = net.createServer({ allowHalfOpen: true }, (client) => {
111+
track(client);
112+
const upstream = net.createConnection({ path: nativeSocket, allowHalfOpen: true });
113+
track(upstream);
114+
// pipe forwards the signed bytes unchanged and forwards the request's write EOF.
115+
client.pipe(upstream);
116+
client.once("end", () => {
117+
order.push("request-half-closed");
118+
forwarded.resolve(client);
119+
});
120+
let response = "";
121+
upstream.setEncoding("utf8");
122+
upstream.on("data", (chunk: string) => {
123+
response += chunk;
124+
});
125+
upstream.once("end", () => nativeResponse.resolve(response));
126+
});
127+
try {
128+
const listening = once(proxy, "listening");
129+
proxy.listen(proxySocket);
130+
await listening;
131+
const outcome = requestExecHostViaSocket({
132+
socketPath: proxySocket,
133+
token,
134+
request,
135+
timeoutMs: 10_000,
136+
});
137+
const caller = await withDeadline(forwarded.promise, 3_000);
138+
await waitForStart();
139+
order.push("native-started");
140+
caller.end();
141+
order.push("response-dropped");
142+
assert.equal(await outcome, null);
143+
order.push("client-null");
144+
assert.equal(await fs.readFile(marker, "utf8"), "START\n");
145+
await fs.writeFile(release, "finish\n");
146+
// Keep draining the native connection: its terminal reply proves the executor
147+
// awaited ShellExecutor and reaped the child, even though the caller lost it.
148+
const response = JSON.parse(await withDeadline(nativeResponse.promise, 8_000)) as {
149+
ok: boolean;
150+
payload: { success: boolean; exitCode: number };
151+
};
152+
assert.equal(response.ok, true);
153+
assert.equal(response.payload.success, true);
154+
assert.equal(response.payload.exitCode, 0);
155+
assert.equal(await fs.readFile(marker, "utf8"), "START\nCOMPLETE\n");
156+
order.push("native-completed");
157+
assert.deepEqual(order, [
158+
"request-half-closed",
159+
"native-started",
160+
"response-dropped",
161+
"client-null",
162+
"native-completed",
163+
]);
164+
assert.deepEqual(errors, []);
165+
console.log("native START -> response dropped -> client null -> native COMPLETE");
166+
} finally {
167+
await fs.writeFile(release, "finish\n");
168+
try {
169+
// Drain even after an assertion fails so the real native child is reaped.
170+
if (sockets.length > 0) {
171+
await withDeadline(nativeResponse.promise, 8_000);
172+
}
173+
} finally {
174+
for (const socket of sockets) {
175+
socket.destroy();
176+
}
177+
await Promise.all(closes);
178+
await new Promise<void>((resolve, reject) => {
179+
proxy.close((error) => (error ? reject(error) : resolve()));
180+
});
181+
}
182+
}

0 commit comments

Comments
 (0)