Skip to content

Commit c0930de

Browse files
authored
fix(secrets): scope egress sentinels to Gateway and survive client tunnel resets (#123527)
* fix(secrets): scope exec egress proxy to gateway * fix(secrets): keep a client reset from crashing the egress proxy host
1 parent 8a3964f commit c0930de

5 files changed

Lines changed: 211 additions & 94 deletions

File tree

‎docs/gateway/secrets.md‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,21 @@ openclaw config set secrets.egressProxy.enabled true --strict-json
325325
openclaw gateway restart
326326
```
327327

328+
For example, bind an OpenAI key to its API host and enable the proxy:
329+
330+
```bash
331+
openclaw secrets store set OPENAI_API_KEY --allow-host api.openai.com
332+
openclaw config set secrets.egressProxy.enabled true --strict-json
333+
```
334+
335+
After restarting the Gateway, a Gateway-hosted agent can run:
336+
337+
```bash
338+
curl -sS https://api.openai.com/v1/models -H "Authorization: Bearer $OPENAI_API_KEY"
339+
```
340+
341+
In the agent environment, `$OPENAI_API_KEY` is an `oc-sent-v2...end` sentinel. The proxy replaces it with the stored value only for `api.openai.com`. A request to an unbound host is refused with `Secret "OPENAI_API_KEY" is not allowed for host "<host>". Run: openclaw secrets store set OPENAI_API_KEY --allow-host <host>`.
342+
328343
Equivalent config:
329344

330345
```json5
@@ -338,7 +353,7 @@ Equivalent config:
338353
}
339354
```
340355

341-
When enabled, OpenClaw adds these values to Gateway and sandbox exec environments:
356+
When enabled, OpenClaw adds these values to Gateway-hosted exec environments:
342357

343358
- `HTTPS_PROXY` and `HTTP_PROXY`, with per-run credentials embedded in the loopback proxy URL
344359
- `NODE_EXTRA_CA_CERTS`, `SSL_CERT_FILE`, `CURL_CA_BUNDLE`, and `REQUESTS_CA_BUNDLE`, pointing at the ephemeral CA certificate
@@ -364,8 +379,7 @@ Current limits:
364379
- Identity-scoped secrets are not supported; only the team store participates.
365380
- Allowed-host policy is exact-hostname authorization only. It does not validate the resolved IP or prevent an allowed origin from reflecting credentials.
366381
- Plain HTTP is refused; it is not upgraded or substituted.
367-
- Sandbox/container reachability is not implemented. Local container sandboxes default to `network: "none"`, and their loopback address is not the Gateway host. The variables are present, but the proxy is normally unreachable.
368-
- Remote `node` exec and provider-native harness subprocesses do not use this proxy.
382+
- Secret egress applies only to Gateway-hosted exec. Sandbox and remote `node` exec receive neither proxy variables nor sentinels, so shared-store `secret` entries are unavailable there. Provider-native harness subprocesses also do not use this proxy.
369383
- Background subprocesses lose proxy authorization when their owning agent run ends, even if the process itself is still alive.
370384

371385
## File-backed API keys

‎src/agents/bash-tools.exec-run.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -404,9 +404,11 @@ export function createExecTool(
404404

405405
const resolvedExecEnvState = requestPreparation.getResolvedExecEnvPreparedState(params);
406406
const storeEnv = await resolveStoreEnv();
407-
const canReachGatewayProxy = host === "gateway" || host === "sandbox";
407+
// The proxy is loopback-owned by the Gateway. Sandbox and node hosts
408+
// cannot use its sentinels, so both sides of the contract stay absent.
409+
const useSecretEgress = secretEgressEnabled && host === "gateway";
408410
let secretEgressEnv: Record<string, string> | undefined;
409-
if (secretEgressEnabled && canReachGatewayProxy) {
411+
if (useSecretEgress) {
410412
if (!defaults?.operationalRunInstance) {
411413
throw new Error("Secret egress proxy requires an admitted agent run instance");
412414
}
@@ -424,7 +426,7 @@ export function createExecTool(
424426
defaultPathPrepend,
425427
pluginEnv: resolvedExecEnvState?.pluginEnv,
426428
storeEnv: storeEnv.env,
427-
storeSecretEnv: secretEgressEnv ? storeEnv.secretSentinels : undefined,
429+
storeSecretEnv: useSecretEgress ? storeEnv.secretSentinels : undefined,
428430
secretEgressEnv,
429431
warnings,
430432
});

‎src/agents/bash-tools.exec.store-env.test.ts‎

Lines changed: 153 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { looksLikeSecretSentinel, resolveSecretSentinel } from "../secrets/senti
55
import { writeSecretStoreEntry } from "../secrets/store/secret-store.js";
66
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
77
import { captureEnv } from "../test-utils/env.js";
8+
import type { ExecuteNodeHostCommandParams } from "./bash-tools.exec-host-node.types.js";
89
import type { BashSandboxConfig } from "./bash-tools.shared.js";
910

1011
const mocks = vi.hoisted(() => ({
@@ -14,6 +15,10 @@ const mocks = vi.hoisted(() => ({
1415
env: Record<string, string>;
1516
requestedEnv?: Record<string, string>;
1617
}>,
18+
nodeHostParams: [] as Array<{
19+
env: Record<string, string>;
20+
requestedEnv?: Record<string, string>;
21+
}>,
1722
spawnInputs: [] as Array<{ env?: Record<string, string> }>,
1823
proxyBindings: [] as Array<unknown>,
1924
}));
@@ -58,6 +63,26 @@ vi.mock("./bash-tools.exec-host-gateway.js", () => ({
5863
),
5964
}));
6065

66+
vi.mock("./bash-tools.exec-host-node.js", () => ({
67+
executeNodeHostCommand: vi.fn(
68+
async (params: Pick<ExecuteNodeHostCommandParams, "env" | "requestedEnv">) => {
69+
mocks.nodeHostParams.push({
70+
env: { ...params.env },
71+
requestedEnv: params.requestedEnv ? { ...params.requestedEnv } : undefined,
72+
});
73+
return {
74+
content: [{ type: "text", text: "node ok" }],
75+
details: {
76+
status: "completed",
77+
exitCode: 0,
78+
durationMs: 0,
79+
aggregated: "node ok",
80+
},
81+
};
82+
},
83+
),
84+
}));
85+
6186
vi.mock("../process/supervisor/index.js", () => ({
6287
getProcessSupervisor: () => ({
6388
spawn: async (input: { env?: Record<string, string>; onStdout?: (chunk: string) => void }) => {
@@ -96,6 +121,17 @@ type StoreEntry = {
96121
allowedHosts?: string[];
97122
};
98123

124+
type StoreEnvHost = "gateway" | "sandbox" | "node";
125+
126+
const EGRESS_ENV = {
127+
HTTPS_PROXY: mocks.proxyUrl,
128+
HTTP_PROXY: mocks.proxyUrl,
129+
NODE_EXTRA_CA_CERTS: "/state/secret-egress/root-ca.pem",
130+
SSL_CERT_FILE: "/state/secret-egress/root-ca.pem",
131+
CURL_CA_BUNDLE: "/state/secret-egress/root-ca.pem",
132+
REQUESTS_CA_BUNDLE: "/state/secret-egress/root-ca.pem",
133+
} as const;
134+
99135
async function withTeamStoreEntries(
100136
entries: StoreEntry[],
101137
run: () => Promise<void>,
@@ -116,6 +152,47 @@ async function withTeamStoreEntries(
116152
}
117153
}
118154

155+
async function captureStoreExecEnvironment(params: {
156+
host: StoreEnvHost;
157+
callId: string;
158+
config?: { secrets: { egressProxy: { enabled: boolean } } };
159+
}): Promise<Record<string, string>> {
160+
let sandboxEnv: Record<string, string> | undefined;
161+
const sandbox: BashSandboxConfig | undefined =
162+
params.host === "sandbox"
163+
? {
164+
containerName: "store-env-sandbox",
165+
workspaceDir: process.cwd(),
166+
containerWorkdir: "/workspace",
167+
buildExecSpec: async (input) => {
168+
sandboxEnv = { ...input.env };
169+
return {
170+
argv: ["remote-shell", input.command],
171+
env: {},
172+
stdinMode: "pipe-open" as const,
173+
};
174+
},
175+
}
176+
: undefined;
177+
const tool = createExecTool({
178+
host: params.host,
179+
security: "full",
180+
ask: "off",
181+
cwd: process.cwd(),
182+
sandbox,
183+
operationalRunInstance: { instanceId: "instance-1", runId: "run-1" },
184+
config: params.config,
185+
});
186+
await tool.execute(params.callId, { command: "echo ok", yieldMs: 120_000 });
187+
if (params.host === "gateway") {
188+
return mocks.gatewayParams.at(-1)?.env ?? {};
189+
}
190+
if (params.host === "node") {
191+
return mocks.nodeHostParams.at(-1)?.env ?? {};
192+
}
193+
return sandboxEnv ?? {};
194+
}
195+
119196
describe("exec store environment", () => {
120197
beforeAll(async () => {
121198
({ createExecTool } = await import("./bash-tools.exec-run.js"));
@@ -125,6 +202,7 @@ describe("exec store environment", () => {
125202
beforeEach(() => {
126203
mocks.egressActive = false;
127204
mocks.gatewayParams.length = 0;
205+
mocks.nodeHostParams.length = 0;
128206
mocks.spawnInputs.length = 0;
129207
mocks.proxyBindings.length = 0;
130208
});
@@ -295,95 +373,82 @@ describe("exec store environment", () => {
295373
});
296374
});
297375

298-
it("keeps disabled secret egress byte-identical with a secret-kind store entry", async () => {
299-
await withTeamStoreEntries(
300-
[
301-
{
302-
name: "SERVICE_API_KEY",
303-
value: "disabled-secret",
304-
kind: "secret",
305-
allowedHosts: ["api.example.com"],
306-
},
307-
],
308-
async () => {
309-
const absentConfig = createExecTool({ host: "gateway", security: "full", ask: "off" });
310-
await absentConfig.execute("call-egress-absent", {
311-
command: "echo ok",
312-
yieldMs: 120_000,
313-
});
314-
const baseline = JSON.stringify({
315-
gateway: mocks.gatewayParams[0],
316-
spawn: mocks.spawnInputs[0],
317-
});
318-
mocks.gatewayParams.length = 0;
319-
mocks.spawnInputs.length = 0;
320-
321-
const explicitFalse = createExecTool({
322-
host: "gateway",
323-
security: "full",
324-
ask: "off",
325-
config: { secrets: { egressProxy: { enabled: false } } },
326-
});
327-
await explicitFalse.execute("call-egress-disabled", {
328-
command: "echo ok",
329-
yieldMs: 120_000,
330-
});
331-
332-
expect(
333-
JSON.stringify({ gateway: mocks.gatewayParams[0], spawn: mocks.spawnInputs[0] }),
334-
).toBe(baseline);
335-
},
336-
);
337-
});
376+
it.each(["gateway", "sandbox", "node"] as const)(
377+
"keeps disabled secret egress byte-identical for %s exec",
378+
async (host) => {
379+
await withTeamStoreEntries(
380+
[
381+
{ name: "AWS_REGION", value: "us-west-2", kind: "env" },
382+
{
383+
name: "SERVICE_API_KEY",
384+
value: "disabled-secret",
385+
kind: "secret",
386+
allowedHosts: ["api.example.com"],
387+
},
388+
],
389+
async () => {
390+
const baseline = await captureStoreExecEnvironment({
391+
host,
392+
callId: `call-egress-absent-${host}`,
393+
});
394+
const explicitFalse = await captureStoreExecEnvironment({
395+
host,
396+
callId: `call-egress-disabled-${host}`,
397+
config: { secrets: { egressProxy: { enabled: false } } },
398+
});
338399

339-
it("injects proxy trust and secret-kind sentinels without changing env-kind entries", async () => {
340-
await withTeamStoreEntries(
341-
[
342-
{ name: "AWS_REGION", value: "us-west-2", kind: "env" },
343-
{
344-
name: "SERVICE_API_KEY",
345-
value: "enabled-secret",
346-
kind: "secret",
347-
allowedHosts: ["API.EXAMPLE.COM"],
400+
expect(JSON.stringify(explicitFalse)).toBe(JSON.stringify(baseline));
348401
},
349-
],
350-
async () => {
351-
mocks.egressActive = true;
352-
const tool = createExecTool({
353-
host: "gateway",
354-
security: "full",
355-
ask: "off",
356-
operationalRunInstance: { instanceId: "instance-1", runId: "run-1" },
357-
config: { secrets: { egressProxy: { enabled: true } } },
358-
});
359-
await tool.execute("call-egress-enabled", {
360-
command: "echo ok",
361-
yieldMs: 120_000,
362-
});
402+
);
403+
},
404+
);
363405

364-
const env = mocks.gatewayParams[0]?.env ?? {};
365-
expect(env.AWS_REGION).toBe("us-west-2");
366-
expect(looksLikeSecretSentinel(env.SERVICE_API_KEY ?? "")).toBe(true);
367-
expect(resolveSecretSentinel(env.SERVICE_API_KEY ?? "")).toBe("enabled-secret");
368-
expect(env).toMatchObject({
369-
HTTPS_PROXY: mocks.proxyUrl,
370-
HTTP_PROXY: mocks.proxyUrl,
371-
NODE_EXTRA_CA_CERTS: "/state/secret-egress/root-ca.pem",
372-
SSL_CERT_FILE: "/state/secret-egress/root-ca.pem",
373-
CURL_CA_BUNDLE: "/state/secret-egress/root-ca.pem",
374-
REQUESTS_CA_BUNDLE: "/state/secret-egress/root-ca.pem",
375-
});
376-
expect(JSON.stringify(env)).not.toContain("enabled-secret");
377-
expect(mocks.proxyBindings).toEqual([
378-
[
379-
expect.objectContaining({
380-
name: "SERVICE_API_KEY",
381-
allowedHosts: ["api.example.com"],
382-
sentinel: env.SERVICE_API_KEY,
383-
}),
384-
],
385-
]);
386-
},
387-
);
388-
});
406+
it.each(["gateway", "sandbox", "node"] as const)(
407+
"applies enabled secret egress correctly for %s exec",
408+
async (host) => {
409+
await withTeamStoreEntries(
410+
[
411+
{ name: "AWS_REGION", value: "us-west-2", kind: "env" },
412+
{
413+
name: "SERVICE_API_KEY",
414+
value: "enabled-secret",
415+
kind: "secret",
416+
allowedHosts: ["API.EXAMPLE.COM"],
417+
},
418+
],
419+
async () => {
420+
mocks.egressActive = true;
421+
const env = await captureStoreExecEnvironment({
422+
host,
423+
callId: `call-egress-enabled-${host}`,
424+
config: { secrets: { egressProxy: { enabled: true } } },
425+
});
426+
expect(env.AWS_REGION).toBe("us-west-2");
427+
if (host === "gateway") {
428+
expect(looksLikeSecretSentinel(env.SERVICE_API_KEY ?? "")).toBe(true);
429+
expect(resolveSecretSentinel(env.SERVICE_API_KEY ?? "")).toBe("enabled-secret");
430+
expect(env).toMatchObject(EGRESS_ENV);
431+
expect(JSON.stringify(env)).not.toContain("enabled-secret");
432+
expect(mocks.proxyBindings).toEqual([
433+
[
434+
expect.objectContaining({
435+
name: "SERVICE_API_KEY",
436+
allowedHosts: ["api.example.com"],
437+
sentinel: env.SERVICE_API_KEY,
438+
}),
439+
],
440+
]);
441+
return;
442+
}
443+
444+
expect(env).not.toHaveProperty("SERVICE_API_KEY");
445+
expect(JSON.stringify(env)).not.toContain("oc-sent-v2.");
446+
for (const [key, value] of Object.entries(EGRESS_ENV)) {
447+
expect(env[key]).not.toBe(value);
448+
}
449+
expect(mocks.proxyBindings).toEqual([]);
450+
},
451+
);
452+
},
453+
);
389454
});

‎src/secrets/egress-proxy/proxy-server.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,36 @@ afterEach(async () => {
256256
});
257257

258258
describe("secret egress proxy", () => {
259+
it("survives a client that resets a refused tunnel instead of crashing the Gateway", async () => {
260+
// The proxy runs inside the Gateway process, so an unhandled socket 'error' would take
261+
// the whole Gateway down. curl resets the connection after a 407, which is exactly this.
262+
const proxyPort = Number(new URL(proxyEnv.HTTPS_PROXY as string).port);
263+
const uncaught: Error[] = [];
264+
const onUncaught = (error: Error) => uncaught.push(error);
265+
process.on("uncaughtException", onUncaught);
266+
try {
267+
await new Promise<void>((resolve) => {
268+
const socket = net.connect(proxyPort, "127.0.0.1", () => {
269+
// No Proxy-Authorization: the proxy answers 407, then the peer resets abruptly.
270+
socket.write("CONNECT example.test:443 HTTP/1.1\r\nHost: example.test:443\r\n\r\n");
271+
setTimeout(() => {
272+
socket.resetAndDestroy();
273+
setTimeout(resolve, 150);
274+
}, 50);
275+
});
276+
socket.on("error", () => {});
277+
});
278+
} finally {
279+
process.off("uncaughtException", onUncaught);
280+
}
281+
282+
expect(uncaught).toEqual([]);
283+
// The listener must still serve traffic after the reset.
284+
const stillAlive = await rawConnect({ auth: basicProxyAuth(registeredPassword(proxyEnv)) });
285+
expect(stillAlive.response).toContain("200 Connection Established");
286+
stillAlive.socket.destroy();
287+
});
288+
259289
it.each([
260290
{ label: "missing", auth: undefined, expectedReason: "missing-proxy-auth" },
261291
{

0 commit comments

Comments
 (0)