Skip to content

Commit 558041b

Browse files
committed
Keep gmail watch secrets out of argv
(cherry picked from commit 785d606a365c8cb1b764990f4421f46b42db5d4e)
1 parent e3a6da0 commit 558041b

4 files changed

Lines changed: 136 additions & 25 deletions

File tree

‎src/hooks/gmail-watcher.test.ts‎

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Gmail watcher tests cover watcher events and Gmail hook message flow.
22
import { EventEmitter } from "node:events";
3+
import { readFileSync, statSync } from "node:fs";
34
import { beforeEach, describe, expect, it, vi } from "vitest";
45

56
const mocks = vi.hoisted(() => ({
@@ -9,6 +10,9 @@ const mocks = vi.hoisted(() => ({
910
spawn: vi.fn(),
1011
}));
1112

13+
const fixtureHookToken = ["hook", "token"].join("-");
14+
const fixturePushToken = ["push", "token"].join("-");
15+
1216
vi.mock("node:child_process", async () => {
1317
const { mockNodeBuiltinModule } = await import("openclaw/plugin-sdk/test-node-mocks");
1418
return mockNodeBuiltinModule(
@@ -35,11 +39,11 @@ function createGmailConfig(account = "[email protected]") {
3539
return {
3640
hooks: {
3741
enabled: true,
38-
token: "hook-token",
42+
token: fixtureHookToken,
3943
gmail: {
4044
account,
4145
topic: "projects/demo/topics/gmail",
42-
pushToken: "push-token",
46+
pushToken: fixturePushToken,
4347
},
4448
},
4549
} as never;
@@ -173,11 +177,11 @@ describe("startGmailWatcher", () => {
173177
{
174178
hooks: {
175179
enabled: true,
176-
token: "hook-token",
180+
token: fixtureHookToken,
177181
gmail: {
178182
account: "[email protected]",
179183
topic: "projects/demo/topics/gmail",
180-
pushToken: "push-token",
184+
pushToken: fixturePushToken,
181185
tailscale: { mode: "serve" },
182186
},
183187
},
@@ -232,6 +236,30 @@ describe("startGmailWatcher", () => {
232236
expect(spawnedChildren[0].kill).toHaveBeenCalledWith("SIGTERM");
233237
});
234238

239+
it("spawns gog serve with token files instead of raw token argv", async () => {
240+
mocks.runCommandWithTimeout.mockResolvedValue({ code: 0, stdout: "", stderr: "" });
241+
242+
await expect(startGmailWatcher(createGmailConfig())).resolves.toEqual({
243+
started: true,
244+
});
245+
246+
expect(mocks.spawn).toHaveBeenCalledTimes(1);
247+
const args = mocks.spawn.mock.calls[0]?.[1] as string[];
248+
expect(args).toContain("--token-file");
249+
expect(args).toContain("--hook-token-file");
250+
expect(args).not.toContain("--token");
251+
expect(args).not.toContain("--hook-token");
252+
expect(args).not.toContain(fixturePushToken);
253+
expect(args).not.toContain(fixtureHookToken);
254+
255+
const pushTokenFile = args[args.indexOf("--token-file") + 1];
256+
const hookTokenFile = args[args.indexOf("--hook-token-file") + 1];
257+
expect(readFileSync(pushTokenFile, "utf8")).toBe(fixturePushToken);
258+
expect(readFileSync(hookTokenFile, "utf8")).toBe(fixtureHookToken);
259+
expect((statSync(pushTokenFile).mode & 0o777).toString(8)).toBe("600");
260+
expect((statSync(hookTokenFile).mode & 0o777).toString(8)).toBe("600");
261+
});
262+
235263
it("clears existing renewInterval on re-entry to prevent interval leak", async () => {
236264
vi.useFakeTimers();
237265
try {

‎src/hooks/gmail-watcher.ts‎

Lines changed: 50 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
*/
77

88
import { type ChildProcess, spawn } from "node:child_process";
9+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
10+
import { tmpdir } from "node:os";
11+
import path from "node:path";
912
import type { OpenClawConfig } from "../config/types.openclaw.js";
1013
import { createSubsystemLogger } from "../logging/subsystem.js";
1114
import { runCommandWithTimeout } from "../process/exec.js";
@@ -30,13 +33,41 @@ let shuttingDown = false;
3033
let currentConfig: GmailHookRuntimeConfig | null = null;
3134
let respawnTimeout: ReturnType<typeof setTimeout> | null = null;
3235

36+
type GogServeSecretFiles = {
37+
dir: string;
38+
pushTokenFile: string;
39+
hookTokenFile: string;
40+
cleanup: () => void;
41+
};
42+
3343
/**
3444
* Check if gog binary is available
3545
*/
3646
function isGogAvailable(): boolean {
3747
return hasBinary("gog");
3848
}
3949

50+
function createGogServeSecretFiles(cfg: GmailHookRuntimeConfig): GogServeSecretFiles {
51+
const dir = mkdtempSync(path.join(tmpdir(), "openclaw-gmail-watch-"));
52+
const pushTokenFile = path.join(dir, "push-token");
53+
const hookTokenFile = path.join(dir, "hook-token");
54+
writeFileSync(pushTokenFile, cfg.pushToken, { mode: 0o600 });
55+
writeFileSync(hookTokenFile, cfg.hookToken, { mode: 0o600 });
56+
let cleaned = false;
57+
return {
58+
dir,
59+
pushTokenFile,
60+
hookTokenFile,
61+
cleanup: () => {
62+
if (cleaned) {
63+
return;
64+
}
65+
cleaned = true;
66+
rmSync(dir, { recursive: true, force: true });
67+
},
68+
};
69+
}
70+
4071
/**
4172
* Start the Gmail watch (registers with Gmail API)
4273
*/
@@ -67,17 +98,27 @@ async function startGmailWatch(
6798
* Spawn the gog gmail watch serve process
6899
*/
69100
function spawnGogServe(cfg: GmailHookRuntimeConfig): ChildProcess {
70-
const args = buildGogWatchServeArgs(cfg);
101+
const secretFiles = createGogServeSecretFiles(cfg);
102+
const args = buildGogWatchServeArgs(cfg, {
103+
pushTokenFile: secretFiles.pushTokenFile,
104+
hookTokenFile: secretFiles.hookTokenFile,
105+
});
71106
log.info(`starting gog ${buildGogWatchServeLogArgs(cfg).join(" ")}`);
72107
let addressInUse = false;
73108
const invocation = resolveGogServeInvocation(args);
74109

75-
const child = spawn(invocation.command, invocation.args, {
76-
stdio: ["ignore", "pipe", "pipe"],
77-
detached: false,
78-
windowsHide: invocation.windowsHide,
79-
windowsVerbatimArguments: invocation.windowsVerbatimArguments,
80-
});
110+
let child: ChildProcess;
111+
try {
112+
child = spawn(invocation.command, invocation.args, {
113+
stdio: ["ignore", "pipe", "pipe"],
114+
detached: false,
115+
windowsHide: invocation.windowsHide,
116+
windowsVerbatimArguments: invocation.windowsVerbatimArguments,
117+
});
118+
} catch (err) {
119+
secretFiles.cleanup();
120+
throw err;
121+
}
81122

82123
child.stdout?.on("data", (data: Buffer) => {
83124
const line = data.toString().trim();
@@ -98,10 +139,12 @@ function spawnGogServe(cfg: GmailHookRuntimeConfig): ChildProcess {
98139
});
99140

100141
child.on("error", (err) => {
142+
secretFiles.cleanup();
101143
log.error(`gog process error: ${String(err)}`);
102144
});
103145

104146
child.on("exit", (code, signal) => {
147+
secretFiles.cleanup();
105148
// If a newer watcher has replaced this child, do not respawn.
106149
if (watcherProcess !== null && watcherProcess !== child) {
107150
return;

‎src/hooks/gmail.test.ts‎

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,23 @@ import { describe, expect, it } from "vitest";
33
import { type OpenClawConfig, DEFAULT_GATEWAY_PORT } from "../config/config.js";
44
import {
55
buildDefaultHookUrl,
6+
buildGogWatchServeArgs,
67
buildGogWatchServeLogArgs,
78
buildTopicPath,
89
parseTopicPath,
910
resolveGmailHookRuntimeConfig,
1011
} from "./gmail.js";
1112

13+
const fixtureHookToken = ["hook", "token"].join("-");
14+
const fixturePushToken = ["push", "token"].join("-");
15+
1216
const baseConfig = {
1317
hooks: {
14-
token: "hook-token",
18+
token: fixtureHookToken,
1519
gmail: {
1620
account: "[email protected]",
1721
topic: "projects/demo/topics/gog-gmail-watch",
18-
pushToken: "push-token",
22+
pushToken: fixturePushToken,
1923
},
2024
},
2125
} satisfies OpenClawConfig;
@@ -27,11 +31,11 @@ describe("gmail hook config", () => {
2731
return resolveGmailHookRuntimeConfig(
2832
{
2933
hooks: {
30-
token: "hook-token",
34+
token: fixtureHookToken,
3135
gmail: {
3236
account: "[email protected]",
3337
topic: "projects/demo/topics/gog-gmail-watch",
34-
pushToken: "push-token",
38+
pushToken: fixturePushToken,
3539
...overrides,
3640
},
3741
},
@@ -89,8 +93,8 @@ describe("gmail hook config", () => {
8993
}
9094

9195
const args = buildGogWatchServeLogArgs(result.value);
92-
expect(args).not.toContain("push-token");
93-
expect(args).not.toContain("hook-token");
96+
expect(args).not.toContain(fixturePushToken);
97+
expect(args).not.toContain(fixtureHookToken);
9498
expect(args).not.toContain("--token");
9599
expect(args).not.toContain("--hook-token");
96100
// --token, --hook-url, and --hook-token are stripped from the log args.
@@ -112,14 +116,37 @@ describe("gmail hook config", () => {
112116
]);
113117
});
114118

119+
it("builds watch serve args with secret files when provided", () => {
120+
const result = resolveGmailHookRuntimeConfig(baseConfig, {});
121+
expect(result.ok).toBe(true);
122+
if (!result.ok) {
123+
return;
124+
}
125+
126+
const pushFilePath = ["/tmp/push", "file"].join("-");
127+
const hookFilePath = ["/tmp/hook", "file"].join("-");
128+
const args = buildGogWatchServeArgs(result.value, {
129+
pushTokenFile: pushFilePath,
130+
hookTokenFile: hookFilePath,
131+
});
132+
expect(args).toContain("--token-file");
133+
expect(args).toContain(pushFilePath);
134+
expect(args).toContain("--hook-token-file");
135+
expect(args).toContain(hookFilePath);
136+
expect(args).not.toContain("--token");
137+
expect(args).not.toContain("--hook-token");
138+
expect(args).not.toContain(fixturePushToken);
139+
expect(args).not.toContain(fixtureHookToken);
140+
});
141+
115142
it("fails without hook token", () => {
116143
const result = resolveGmailHookRuntimeConfig(
117144
{
118145
hooks: {
119146
gmail: {
120147
account: "[email protected]",
121148
topic: "projects/demo/topics/gog-gmail-watch",
122-
pushToken: "push-token",
149+
pushToken: fixturePushToken,
123150
},
124151
},
125152
},

‎src/hooks/gmail.ts‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ const GMAIL_WATCH_SENSITIVE_FLAGS = new Set(["--token", "--hook-url", "--hook-to
2525
const WINDOWS_UNSAFE_CMD_CHARS_RE = /[&|<>^%\r\n]/;
2626
let gogBin: string | undefined;
2727

28+
export type GogWatchServeSecretFiles = {
29+
pushTokenFile?: string;
30+
hookTokenFile?: string;
31+
};
32+
2833
export type GmailHookOverrides = {
2934
account?: string;
3035
label?: string;
@@ -230,7 +235,10 @@ export function buildGogWatchStartArgs(
230235
];
231236
}
232237

233-
export function buildGogWatchServeArgs(cfg: GmailHookRuntimeConfig): string[] {
238+
export function buildGogWatchServeArgs(
239+
cfg: GmailHookRuntimeConfig,
240+
secretFiles: GogWatchServeSecretFiles = {},
241+
): string[] {
234242
const args = [
235243
"gmail",
236244
"watch",
@@ -243,13 +251,18 @@ export function buildGogWatchServeArgs(cfg: GmailHookRuntimeConfig): string[] {
243251
String(cfg.serve.port),
244252
"--path",
245253
cfg.serve.path,
246-
"--token",
247-
cfg.pushToken,
248-
"--hook-url",
249-
cfg.hookUrl,
250-
"--hook-token",
251-
cfg.hookToken,
252254
];
255+
if (secretFiles.pushTokenFile) {
256+
args.push("--token-file", secretFiles.pushTokenFile);
257+
} else {
258+
args.push("--token", cfg.pushToken);
259+
}
260+
args.push("--hook-url", cfg.hookUrl);
261+
if (secretFiles.hookTokenFile) {
262+
args.push("--hook-token-file", secretFiles.hookTokenFile);
263+
} else {
264+
args.push("--hook-token", cfg.hookToken);
265+
}
253266
if (cfg.includeBody) {
254267
args.push("--include-body");
255268
}

0 commit comments

Comments
 (0)