Skip to content

Commit 8d6cbee

Browse files
authored
fix(gateway): avoid Tailscale crash loops after upgrades (#126069)
* fix(gateway): migrate legacy Tailscale routes on upgrade * fix(gateway): preserve unattributable Tailscale routes
1 parent fe816d6 commit 8d6cbee

7 files changed

Lines changed: 157 additions & 0 deletions

File tree

‎docs/gateway/tailscale.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ This compatibility path does not grant managed Tailscale semantics: `gateway.aut
117117
- Tailscale Serve/Funnel requires the `tailscale` CLI installed and logged in.
118118
- `tailscale.mode: "funnel"` refuses to start unless auth mode is `password`, to avoid public exposure.
119119
- OpenClaw holds Serve/Funnel as a foreground Tailscale claim. Gateway startup succeeds only after the claim is active, and stopping or losing the Gateway releases it automatically.
120+
- When upgrading from an older OpenClaw release, a persistent HTTPS root route may still own port 443. Because that route is indistinguishable from an operator-managed route, OpenClaw does not change it: startup explains the conflict and exits with status 78 instead of entering a systemd restart loop. Inspect `tailscale serve status`. If you confirm it is the stale route created by older managed Serve/Funnel, remove only its root handler with `tailscale serve --yes --https=443 --set-path=/ off` or `tailscale funnel --yes --https=443 --set-path=/ off`, then restart the Gateway. If the route is intentionally external, disable managed Tailscale ingress and use the `trustedProxies` path above.
120121
- Named Tailscale Services are not supported by managed ingress because Tailscale requires them to run as persistent background routes. Existing `gateway.tailscale.serviceName` installs must run `openclaw doctor --fix`; Doctor disables managed ingress and removes the key. Inspect the retained Service route, clear it with `tailscale serve clear <service-name>`, then enable device Serve with `gateway.tailscale.mode: "serve"` if desired.
121122
- Older releases could advertise an externally configured default HTTPS Serve route that targeted a `gateway.bind: "lan"` listener. That route does not automatically gain trusted ingress provenance. Prefer migrating to managed ingress: run `openclaw doctor` to preview an atomic change to `gateway.bind: "loopback"` plus `gateway.tailscale.mode: "serve"`; apply it with `openclaw doctor --fix`, then restart the Gateway. Doctor does not reset Tailscale state or guess how to rewrite custom Serve ports and Tailscale Services. If another service must retain ownership, use the explicit `trustedProxies` compatibility path above.
122123
- `gateway.tailscale.preserveFunnel: true` is a deprecated migration guard. It detects an externally configured `tailscale funnel` route before reapplying Serve. If that route still targets the ordinary Gateway listener, OpenClaw leaves it unchanged and warns because the route is not managed ingress. Gateway-authenticated routes work only through the explicit `trustedProxies` compatibility path above and continue to require the configured auth; plugin-authenticated webhook routes such as Google Chat and SMS keep using their own signature/auth checks. To migrate, first configure a durable `gateway.auth.password` (prefer a SecretRef) or `OPENCLAW_GATEWAY_PASSWORD`, set `gateway.auth.mode` to `password`, run `openclaw config set gateway.tailscale.mode funnel`, then `openclaw config unset gateway.tailscale.preserveFunnel`.

‎src/cli/gateway-cli/run.supervised-lock.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { createServer } from "node:http";
33
import { describe, expect, it, vi } from "vitest";
44
import { GatewayLockError } from "../../infra/gateway-lock.js";
5+
import { TailscaleRouteOwnershipConflictError } from "../../infra/tailscale-route-ownership-error.js";
56
import { OpenClawAgentDatabaseMediaMigrationRequiredError } from "../../state/openclaw-agent-db-migration-required.js";
67
import { testing } from "./run.test-support.js";
78

@@ -21,6 +22,12 @@ function createLogger() {
2122
}
2223

2324
describe("supervised gateway lock recovery", () => {
25+
it("uses exit 78 for an ambiguous persistent Tailscale route", () => {
26+
expect(
27+
testing.resolveGatewayStartupFailureExitCode(new TailscaleRouteOwnershipConflictError()),
28+
).toBe(78);
29+
});
30+
2431
it("uses exit 78 for offline agent database migration requirements", () => {
2532
expect(
2633
testing.resolveGatewayStartupFailureExitCode(

‎src/cli/gateway-cli/run.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ import {
5555
formatGatewayPidList,
5656
} from "../../infra/gateway-processes.js";
5757
import type { RespawnSupervisor } from "../../infra/supervisor-markers.js";
58+
import { isTailscaleRouteOwnershipConflictError } from "../../infra/tailscale-route-ownership-error.js";
5859
import { setConsoleSubsystemFilter, setConsoleTimestampPrefix } from "../../logging/console.js";
5960
import { withDiagnosticPhase } from "../../logging/diagnostic-phase.js";
6061
import { createSubsystemLogger } from "../../logging/subsystem.js";
@@ -478,6 +479,7 @@ function resolveGatewayLockErrorExitCode(err: unknown): number {
478479

479480
function resolveGatewayStartupFailureExitCode(err: unknown): number {
480481
return isInvalidConfigError(err) ||
482+
isTailscaleRouteOwnershipConflictError(err) ||
481483
findOpenClawAgentDatabaseMediaMigrationRequiredError(err) ||
482484
findOpenClawStateDatabaseSchemaMigrationRequiredError(err)
483485
? EXIT_CONFIG_ERROR
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import { readFile, writeFile } from "node:fs/promises";
2+
import path from "node:path";
3+
import { fileURLToPath } from "node:url";
4+
import { afterEach, describe, expect, it } from "vitest";
5+
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
6+
import { captureEnv } from "../test-utils/env.js";
7+
import { startGatewayTailscaleExposure } from "./server-tailscale.js";
8+
9+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
10+
11+
describe("managed Tailscale upgrade", () => {
12+
const legacyRoute = (funnel = false, proxyPort = 18789) => {
13+
const host = "fixture.tailnet.ts.net:443";
14+
return {
15+
TCP: { "443": { HTTPS: true } },
16+
Web: { [host]: { Handlers: { "/": { Proxy: `http://127.0.0.1:${proxyPort}/` } } } },
17+
...(funnel ? { AllowFunnel: { [host]: true } } : {}),
18+
};
19+
};
20+
21+
const installFixture = async (config: object, mode: "serve" | "funnel") => {
22+
const fixture = fileURLToPath(
23+
new URL("../../test/fixtures/tailscale-legacy-route-fixture.mjs", import.meta.url),
24+
);
25+
const marker = path.join(tempDirs.make("openclaw-tailscale-upgrade-"), "state");
26+
await writeFile(marker, JSON.stringify(config));
27+
process.env.OPENCLAW_TEST_TAILSCALE_BINARY = fixture;
28+
process.env.OPENCLAW_TEST_TAILSCALE_FIXTURE_MARKER = marker;
29+
process.env.OPENCLAW_TEST_TAILSCALE_FIXTURE_MODE = mode;
30+
process.env.VITEST ??= "true";
31+
return marker;
32+
};
33+
34+
it.each(["serve", "funnel"] as const)(
35+
"does not infer ownership from a matching persistent %s route",
36+
async (mode) => {
37+
const env = captureEnv([
38+
"OPENCLAW_TEST_TAILSCALE_BINARY",
39+
"OPENCLAW_TEST_TAILSCALE_FIXTURE_MARKER",
40+
"OPENCLAW_TEST_TAILSCALE_FIXTURE_MODE",
41+
"VITEST",
42+
]);
43+
const marker = await installFixture(legacyRoute(mode === "funnel"), mode);
44+
const before = await readFile(marker, "utf8");
45+
46+
try {
47+
await expect(
48+
startGatewayTailscaleExposure({
49+
tailscaleMode: mode,
50+
port: 18789,
51+
backend: { host: "127.0.0.1", port: 19000 },
52+
logTailscale: { info: () => undefined, warn: () => undefined },
53+
}),
54+
).rejects.toThrow("ownership OpenClaw cannot prove; it was not modified");
55+
expect(await readFile(marker, "utf8")).toBe(before);
56+
} finally {
57+
env.restore();
58+
}
59+
},
60+
);
61+
62+
it("does not mutate an independent Tailscale Service", async () => {
63+
const env = captureEnv([
64+
"OPENCLAW_TEST_TAILSCALE_BINARY",
65+
"OPENCLAW_TEST_TAILSCALE_FIXTURE_MARKER",
66+
"OPENCLAW_TEST_TAILSCALE_FIXTURE_MODE",
67+
"VITEST",
68+
]);
69+
const marker = await installFixture({ Services: { "svc:other": legacyRoute() } }, "serve");
70+
const before = await readFile(marker, "utf8");
71+
72+
try {
73+
const cleanup = await startGatewayTailscaleExposure({
74+
tailscaleMode: "serve",
75+
port: 18789,
76+
backend: { host: "127.0.0.1", port: 19000 },
77+
logTailscale: { info: () => undefined, warn: () => undefined },
78+
});
79+
80+
expect(await readFile(marker, "utf8")).toBe(before);
81+
await cleanup?.();
82+
} finally {
83+
env.restore();
84+
}
85+
});
86+
});
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { asNullableObjectRecord as readRecord } from "@openclaw/normalization-core/record-coerce";
2+
3+
const TAILSCALE_ROUTE_OWNERSHIP_CONFLICT_CODE = "TAILSCALE_ROUTE_OWNERSHIP_CONFLICT";
4+
5+
export class TailscaleRouteOwnershipConflictError extends Error {
6+
readonly code = TAILSCALE_ROUTE_OWNERSHIP_CONFLICT_CODE;
7+
8+
constructor() {
9+
super(
10+
"Tailscale HTTPS port 443 is already owned by a route whose ownership OpenClaw cannot prove; it was not modified. " +
11+
"Inspect `tailscale serve status`. If it is a stale route from an older OpenClaw release, remove its root handler with " +
12+
"`tailscale serve --yes --https=443 --set-path=/ off` or `tailscale funnel --yes --https=443 --set-path=/ off`, then restart the Gateway. " +
13+
"Otherwise disable managed Tailscale ingress or reconfigure the route before restarting.",
14+
);
15+
this.name = "TailscaleRouteOwnershipConflictError";
16+
}
17+
}
18+
19+
export function isTailscaleRouteOwnershipConflictError(error: unknown): boolean {
20+
return (
21+
error instanceof TailscaleRouteOwnershipConflictError ||
22+
readRecord(error)?.code === TAILSCALE_ROUTE_OWNERSHIP_CONFLICT_CODE
23+
);
24+
}

‎src/infra/tailscale.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
TAILSCALE_ROUTE_OWNER_ARG,
2222
type TailscaleRouteOwnerMessage,
2323
} from "./tailscale-route-owner-protocol.js";
24+
import { TailscaleRouteOwnershipConflictError } from "./tailscale-route-ownership-error.js";
2425

2526
const TAILSCALE_STATUS_ATTEMPTS = 3;
2627
const TAILSCALE_STATUS_RETRY_DELAY_MS = 500;
@@ -237,7 +238,14 @@ type TailscaleRouteOwnerFailure = Pick<
237238
"code" | "stdout" | "stderr"
238239
>;
239240

241+
function isPort443RouteConflict(message: TailscaleRouteOwnerFailure): boolean {
242+
return /listener already exists for port 443/i.test(`${message.stderr}\n${message.stdout}`);
243+
}
244+
240245
function routeClaimError(message: TailscaleRouteOwnerFailure): Error {
246+
if (isPort443RouteConflict(message)) {
247+
return new TailscaleRouteOwnershipConflictError();
248+
}
241249
const detail = [message.stderr.trim(), message.stdout.trim()].find(Boolean);
242250
return Object.assign(new Error(detail || "Tailscale route owner exited before claiming route"), {
243251
code: message.code,
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#!/usr/bin/env node
2+
import { readFile } from "node:fs/promises";
3+
4+
const args = process.argv.slice(2);
5+
const marker = process.env.OPENCLAW_TEST_TAILSCALE_FIXTURE_MARKER;
6+
const mode = process.env.OPENCLAW_TEST_TAILSCALE_FIXTURE_MODE;
7+
if (!marker || (mode !== "serve" && mode !== "funnel")) {
8+
process.stderr.write("missing fixture state\n");
9+
process.exit(2);
10+
}
11+
12+
if (JSON.stringify(args) === JSON.stringify(["status", "--json"])) {
13+
process.stdout.write(JSON.stringify({ Self: { DNSName: "fixture.tailnet.ts.net." } }));
14+
process.exit(0);
15+
}
16+
17+
if (JSON.stringify(args) === JSON.stringify([mode, "--yes", "--bg=false", "19000"])) {
18+
const state = await readFile(marker, "utf8");
19+
const status = JSON.parse(state);
20+
if (status.TCP?.["443"]) {
21+
process.stderr.write("listener already exists for port 443\n");
22+
process.exit(1);
23+
}
24+
process.stdout.write("Press Ctrl+C to exit.\n");
25+
setInterval(() => {}, 1000);
26+
} else {
27+
process.stderr.write(`unexpected arguments: ${JSON.stringify(args)}\n`);
28+
process.exit(2);
29+
}

0 commit comments

Comments
 (0)