Skip to content

Commit 05b0b82

Browse files
committed
fix: guard tailscale sudo fallback (#1551) (thanks @sweepies)
1 parent 908d933 commit 05b0b82

3 files changed

Lines changed: 114 additions & 59 deletions

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ Docs: https://docs.clawd.bot
1111

1212
### Fixes
1313
- Voice wake: auto-save wake words on blur/submit across iOS/Android and align limits with macOS.
14+
- Tailscale: retry serve/funnel with sudo only for permission errors and keep original failure details. (#1551) Thanks @sweepies.
1415
- Discord: limit autoThread mention bypass to bot-owned threads; keep ack reactions mention-gated. (#1511) Thanks @pvoo.
1516
- Gateway: accept null optional fields in exec approval requests. (#1511) Thanks @pvoo.
1617
- TUI: forward unknown slash commands (for example, `/context`) to the Gateway.

src/infra/tailscale.test.ts

Lines changed: 53 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,21 @@
1-
import { describe, expect, it, vi } from "vitest";
1+
import { afterEach, describe, expect, it, vi } from "vitest";
22

3-
import {
3+
import * as tailscale from "./tailscale.js";
4+
5+
const {
46
ensureGoInstalled,
57
ensureTailscaledInstalled,
68
getTailnetHostname,
79
enableTailscaleServe,
810
disableTailscaleServe,
9-
enableTailscaleFunnel,
10-
disableTailscaleFunnel,
11-
ensureFunnel
12-
} from "./tailscale.js";
11+
ensureFunnel,
12+
} = tailscale;
1313

1414
describe("tailscale helpers", () => {
15+
afterEach(() => {
16+
vi.restoreAllMocks();
17+
});
18+
1519
it("parses DNS name from tailscale status", async () => {
1620
const exec = vi.fn().mockResolvedValue({
1721
stdout: JSON.stringify({
@@ -61,7 +65,9 @@ describe("tailscale helpers", () => {
6165
it("enableTailscaleServe attempts normal first, then sudo", async () => {
6266
// 1. First attempt fails
6367
// 2. Second attempt (sudo) succeeds
64-
const exec = vi.fn()
68+
vi.spyOn(tailscale, "getTailscaleBinary").mockResolvedValue("tailscale");
69+
const exec = vi
70+
.fn()
6571
.mockRejectedValueOnce(new Error("permission denied"))
6672
.mockResolvedValueOnce({ stdout: "" });
6773

@@ -71,18 +77,19 @@ describe("tailscale helpers", () => {
7177
1,
7278
"tailscale",
7379
expect.arrayContaining(["serve", "--bg", "--yes", "3000"]),
74-
expect.any(Object)
80+
expect.any(Object),
7581
);
7682

7783
expect(exec).toHaveBeenNthCalledWith(
7884
2,
7985
"sudo",
8086
expect.arrayContaining(["-n", "tailscale", "serve", "--bg", "--yes", "3000"]),
81-
expect.any(Object)
87+
expect.any(Object),
8288
);
8389
});
8490

8591
it("enableTailscaleServe does NOT use sudo if first attempt succeeds", async () => {
92+
vi.spyOn(tailscale, "getTailscaleBinary").mockResolvedValue("tailscale");
8693
const exec = vi.fn().mockResolvedValue({ stdout: "" });
8794

8895
await enableTailscaleServe(3000, exec as never);
@@ -91,13 +98,15 @@ describe("tailscale helpers", () => {
9198
expect(exec).toHaveBeenCalledWith(
9299
"tailscale",
93100
expect.arrayContaining(["serve", "--bg", "--yes", "3000"]),
94-
expect.any(Object)
101+
expect.any(Object),
95102
);
96103
});
97104

98105
it("disableTailscaleServe uses fallback", async () => {
99-
const exec = vi.fn()
100-
.mockRejectedValueOnce(new Error("failed"))
106+
vi.spyOn(tailscale, "getTailscaleBinary").mockResolvedValue("tailscale");
107+
const exec = vi
108+
.fn()
109+
.mockRejectedValueOnce(new Error("permission denied"))
101110
.mockResolvedValueOnce({ stdout: "" });
102111

103112
await disableTailscaleServe(exec as never);
@@ -107,7 +116,7 @@ describe("tailscale helpers", () => {
107116
2,
108117
"sudo",
109118
expect.arrayContaining(["-n", "tailscale", "serve", "reset"]),
110-
expect.any(Object)
119+
expect.any(Object),
111120
);
112121
});
113122

@@ -116,9 +125,11 @@ describe("tailscale helpers", () => {
116125
// 1. status (success)
117126
// 2. enable (fails)
118127
// 3. enable sudo (success)
119-
const exec = vi.fn()
128+
vi.spyOn(tailscale, "getTailscaleBinary").mockResolvedValue("tailscale");
129+
const exec = vi
130+
.fn()
120131
.mockResolvedValueOnce({ stdout: JSON.stringify({ BackendState: "Running" }) }) // status
121-
.mockRejectedValueOnce(new Error("failed")) // enable normal
132+
.mockRejectedValueOnce(new Error("permission denied")) // enable normal
122133
.mockResolvedValueOnce({ stdout: "" }); // enable sudo
123134

124135
const runtime = {
@@ -134,23 +145,47 @@ describe("tailscale helpers", () => {
134145
expect(exec).toHaveBeenNthCalledWith(
135146
1,
136147
"tailscale",
137-
expect.arrayContaining(["funnel", "status", "--json"])
148+
expect.arrayContaining(["funnel", "status", "--json"]),
138149
);
139150

140151
// 2. enable normal
141152
expect(exec).toHaveBeenNthCalledWith(
142153
2,
143154
"tailscale",
144155
expect.arrayContaining(["funnel", "--yes", "--bg", "8080"]),
145-
expect.any(Object)
156+
expect.any(Object),
146157
);
147158

148159
// 3. enable sudo
149160
expect(exec).toHaveBeenNthCalledWith(
150161
3,
151162
"sudo",
152163
expect.arrayContaining(["-n", "tailscale", "funnel", "--yes", "--bg", "8080"]),
153-
expect.any(Object)
164+
expect.any(Object),
154165
);
155166
});
167+
168+
it("enableTailscaleServe skips sudo on non-permission errors", async () => {
169+
vi.spyOn(tailscale, "getTailscaleBinary").mockResolvedValue("tailscale");
170+
const exec = vi.fn().mockRejectedValueOnce(new Error("boom"));
171+
172+
await expect(enableTailscaleServe(3000, exec as never)).rejects.toThrow("boom");
173+
174+
expect(exec).toHaveBeenCalledTimes(1);
175+
});
176+
177+
it("enableTailscaleServe rethrows original error if sudo fails", async () => {
178+
vi.spyOn(tailscale, "getTailscaleBinary").mockResolvedValue("tailscale");
179+
const originalError = Object.assign(new Error("permission denied"), {
180+
stderr: "permission denied",
181+
});
182+
const exec = vi
183+
.fn()
184+
.mockRejectedValueOnce(originalError)
185+
.mockRejectedValueOnce(new Error("sudo: a password is required"));
186+
187+
await expect(enableTailscaleServe(3000, exec as never)).rejects.toBe(originalError);
188+
189+
expect(exec).toHaveBeenCalledTimes(2);
190+
});
156191
});

src/infra/tailscale.ts

Lines changed: 60 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,39 @@ export async function ensureTailscaledInstalled(
206206
await exec("brew", ["install", "tailscale"]);
207207
}
208208

209+
type ExecErrorDetails = {
210+
stdout?: unknown;
211+
stderr?: unknown;
212+
message?: unknown;
213+
code?: unknown;
214+
};
215+
216+
function extractExecErrorText(err: unknown) {
217+
const errOutput = err as ExecErrorDetails;
218+
const stdout = typeof errOutput.stdout === "string" ? errOutput.stdout : "";
219+
const stderr = typeof errOutput.stderr === "string" ? errOutput.stderr : "";
220+
const message = typeof errOutput.message === "string" ? errOutput.message : "";
221+
const code = typeof errOutput.code === "string" ? errOutput.code : "";
222+
return { stdout, stderr, message, code };
223+
}
224+
225+
function isPermissionDeniedError(err: unknown): boolean {
226+
const { stdout, stderr, message, code } = extractExecErrorText(err);
227+
if (code.toUpperCase() === "EACCES") return true;
228+
const combined = `${stdout}\n${stderr}\n${message}`.toLowerCase();
229+
return (
230+
combined.includes("permission denied") ||
231+
combined.includes("access denied") ||
232+
combined.includes("operation not permitted") ||
233+
combined.includes("not permitted") ||
234+
combined.includes("requires root") ||
235+
combined.includes("must be run as root") ||
236+
combined.includes("must be run with sudo") ||
237+
combined.includes("requires sudo") ||
238+
combined.includes("need sudo")
239+
);
240+
}
241+
209242
// Helper to attempt a command, and retry with sudo if it fails.
210243
async function execWithSudoFallback(
211244
exec: typeof runExec,
@@ -216,12 +249,18 @@ async function execWithSudoFallback(
216249
try {
217250
return await exec(bin, args, opts);
218251
} catch (err) {
219-
// If the error suggests permission denied or access denied, try with sudo.
220-
// Or honestly, for any error in these specific ops, trying sudo is a reasonable fallback
221-
// given the context of what we're doing (system-level network config).
222-
// We'll log a verbose message that we're falling back.
252+
if (!isPermissionDeniedError(err)) {
253+
throw err;
254+
}
223255
logVerbose(`Command failed, retrying with sudo: ${bin} ${args.join(" ")}`);
224-
return await exec("sudo", ["-n", bin, ...args], opts);
256+
try {
257+
return await exec("sudo", ["-n", bin, ...args], opts);
258+
} catch (sudoErr) {
259+
const { stderr, message } = extractExecErrorText(sudoErr);
260+
const detail = (stderr || message).trim();
261+
if (detail) logVerbose(`Sudo retry failed: ${detail}`);
262+
throw err;
263+
}
225264
}
226265
}
227266

@@ -313,52 +352,32 @@ export async function ensureFunnel(
313352

314353
export async function enableTailscaleServe(port: number, exec: typeof runExec = runExec) {
315354
const tailscaleBin = await getTailscaleBinary();
316-
await execWithSudoFallback(
317-
exec,
318-
tailscaleBin,
319-
["serve", "--bg", "--yes", `${port}`],
320-
{
321-
maxBuffer: 200_000,
322-
timeoutMs: 15_000,
323-
},
324-
);
355+
await execWithSudoFallback(exec, tailscaleBin, ["serve", "--bg", "--yes", `${port}`], {
356+
maxBuffer: 200_000,
357+
timeoutMs: 15_000,
358+
});
325359
}
326360

327361
export async function disableTailscaleServe(exec: typeof runExec = runExec) {
328362
const tailscaleBin = await getTailscaleBinary();
329-
await execWithSudoFallback(
330-
exec,
331-
tailscaleBin,
332-
["serve", "reset"],
333-
{
334-
maxBuffer: 200_000,
335-
timeoutMs: 15_000,
336-
},
337-
);
363+
await execWithSudoFallback(exec, tailscaleBin, ["serve", "reset"], {
364+
maxBuffer: 200_000,
365+
timeoutMs: 15_000,
366+
});
338367
}
339368

340369
export async function enableTailscaleFunnel(port: number, exec: typeof runExec = runExec) {
341370
const tailscaleBin = await getTailscaleBinary();
342-
await execWithSudoFallback(
343-
exec,
344-
tailscaleBin,
345-
["funnel", "--bg", "--yes", `${port}`],
346-
{
347-
maxBuffer: 200_000,
348-
timeoutMs: 15_000,
349-
},
350-
);
371+
await execWithSudoFallback(exec, tailscaleBin, ["funnel", "--bg", "--yes", `${port}`], {
372+
maxBuffer: 200_000,
373+
timeoutMs: 15_000,
374+
});
351375
}
352376

353377
export async function disableTailscaleFunnel(exec: typeof runExec = runExec) {
354378
const tailscaleBin = await getTailscaleBinary();
355-
await execWithSudoFallback(
356-
exec,
357-
tailscaleBin,
358-
["funnel", "reset"],
359-
{
360-
maxBuffer: 200_000,
361-
timeoutMs: 15_000,
362-
},
363-
);
379+
await execWithSudoFallback(exec, tailscaleBin, ["funnel", "reset"], {
380+
maxBuffer: 200_000,
381+
timeoutMs: 15_000,
382+
});
364383
}

0 commit comments

Comments
 (0)