Skip to content

Commit 72fd25d

Browse files
jetd1vincentkocXiaoshuai Zhang
authored
fix(gateway): connect bootstrap clients to self-signed WSS (#80204)
* fix(gateway): propagate TLS pins to bootstrap clients Co-authored-by: Xiaoshuai Zhang <[email protected]> Punchcard-Session: cobalt-brook-meadow-m9 * fix(gateway): keep TLS loader type private Punchcard-Session: cobalt-brook-meadow-m9 * fix(gateway): preserve TLS pin transport policy Punchcard-Session: cobalt-brook-meadow-m9 --------- Co-authored-by: Vincent Koc <[email protected]> Co-authored-by: Xiaoshuai Zhang <[email protected]>
1 parent ae41dce commit 72fd25d

14 files changed

Lines changed: 373 additions & 27 deletions

‎packages/gateway-client/src/client.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import type {
1919
import { resolveGatewayStartupRetryAfterMs } from "@openclaw/gateway-protocol/startup-unavailable";
2020
import { MIN_CLIENT_PROTOCOL_VERSION, PROTOCOL_VERSION } from "@openclaw/gateway-protocol/version";
2121
import { isLoopbackIpAddress, type ParsedIpAddress } from "@openclaw/net-policy/ip";
22+
import { isWssUrl } from "@openclaw/net-policy/url-protocol";
2223
import { WebSocket, type ClientOptions, type CertMeta } from "ws";
2324
import {
2425
isSensitiveUrlQueryParamName,
@@ -518,7 +519,8 @@ export class GatewayClient {
518519

519520
private createSocket(handlers: GatewayProtocolSocketHandlers): GatewayProtocolSocket {
520521
const url = this.opts.url ?? DEFAULT_GATEWAY_CLIENT_URL;
521-
if (this.opts.tlsFingerprint && !url.startsWith("wss://")) {
522+
const usesTls = isWssUrl(url);
523+
if (this.opts.tlsFingerprint && !usesTls) {
522524
throw new GatewayClientSocketFactoryConfigurationError(
523525
"gateway tls fingerprint requires wss:// gateway url",
524526
);
@@ -560,7 +562,7 @@ export class GatewayClient {
560562
handshakeTimeout: handshakeTimeoutMs,
561563
...(this.opts.origin ? { origin: this.opts.origin } : {}),
562564
};
563-
if (url.startsWith("wss://") && this.opts.tlsFingerprint) {
565+
if (usesTls && this.opts.tlsFingerprint) {
564566
wsOptions.rejectUnauthorized = false;
565567
wsOptions.checkServerIdentity = (_hostValue: string, cert: CertMeta) => {
566568
const fingerprintValue =
@@ -606,7 +608,7 @@ export class GatewayClient {
606608
this.transportValidated = false;
607609
ws.on("open", () => {
608610
handlers.open();
609-
if (url.startsWith("wss://") && this.opts.tlsFingerprint) {
611+
if (usesTls && this.opts.tlsFingerprint) {
610612
const tlsError = this.validateTlsFingerprint();
611613
if (tlsError) {
612614
handlers.error(tlsError);

‎packages/gateway-client/src/protocol-client.socket-factory.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,27 @@ describe("GatewayProtocolClient socket factory recovery", () => {
212212
});
213213

214214
describe("GatewayClient socket factory recovery", () => {
215+
it("accepts uppercase WSS URLs with a TLS fingerprint", () => {
216+
const onConnectError = vi.fn<(error: Error) => void>();
217+
const beforeConnect = vi.fn(() => {
218+
throw new Error("stop after transport policy");
219+
});
220+
const client = new GatewayClient({
221+
url: "WSS://gateway.example:18789",
222+
tlsFingerprint: "deadbeef",
223+
onConnectError,
224+
hostDeps: { beforeConnect },
225+
});
226+
227+
client.start();
228+
229+
expect(beforeConnect).toHaveBeenCalledOnce();
230+
expect(onConnectError).toHaveBeenCalledExactlyOnceWith(
231+
expect.objectContaining({ message: "stop after transport policy" }),
232+
);
233+
client.stop();
234+
});
235+
215236
it("retries transient node-host setup failures without requiring another start", async () => {
216237
vi.useFakeTimers();
217238
const onConnectError = vi.fn<(error: Error) => void>();

‎packages/net-policy/src/url-protocol.test.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
import { describe, expect, it } from "vitest";
2-
import { hasHttpUrlPrefix, isHttpsUrl, isHttpUrl, isWebSocketUrl } from "./url-protocol.js";
2+
import {
3+
hasHttpUrlPrefix,
4+
isHttpsUrl,
5+
isHttpUrl,
6+
isWebSocketUrl,
7+
isWssUrl,
8+
} from "./url-protocol.js";
39

410
describe("hasHttpUrlPrefix", () => {
511
it.each([
@@ -27,17 +33,20 @@ describe("parsed URL protocol predicates", () => {
2733
expect(isHttpUrl(url)).toBe(http);
2834
expect(isHttpsUrl(url)).toBe(https);
2935
expect(isWebSocketUrl(url)).toBe(websocket);
36+
expect(isWssUrl(url)).toBe(url.protocol === "wss:");
3037
});
3138

3239
it("returns false for malformed and relative strings", () => {
3340
expect(isHttpUrl("https://")).toBe(false);
3441
expect(isHttpsUrl("/relative")).toBe(false);
3542
expect(isWebSocketUrl("not a URL")).toBe(false);
43+
expect(isWssUrl("not a URL")).toBe(false);
3644
});
3745

3846
it("parses string inputs without changing URL constructor behavior", () => {
3947
expect(isHttpUrl(" HTTP://user:[email protected]:8080/path ")).toBe(true);
4048
expect(isHttpsUrl(" HTTPS://example.com ")).toBe(true);
4149
expect(isWebSocketUrl(" WSS://example.com:9443/socket ")).toBe(true);
50+
expect(isWssUrl(" WSS://example.com:9443/socket ")).toBe(true);
4251
});
4352
});

‎packages/net-policy/src/url-protocol.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,7 @@ export function isWebSocketUrl(value: string | URL): boolean {
2828
const url = parseUrl(value);
2929
return url?.protocol === "ws:" || url?.protocol === "wss:";
3030
}
31+
32+
export function isWssUrl(value: string | URL): boolean {
33+
return parseUrl(value)?.protocol === "wss:";
34+
}

‎src/acp/server.startup.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,14 @@ type GatewayClientAuth = {
1616
type ResolveGatewayClientBootstrap = (params: unknown) => Promise<{
1717
url: string;
1818
urlSource: string;
19+
preauthHandshakeTimeoutMs?: number;
20+
tlsFingerprint?: string;
1921
auth: GatewayClientAuth;
2022
}>;
2123
type GatewayClientOptions = GatewayClientCallbacks &
2224
GatewayClientAuth & {
2325
caps?: string[];
26+
tlsFingerprint?: string;
2427
url?: string;
2528
};
2629
type MockAcpStream = {
@@ -426,6 +429,30 @@ describe("serveAcpGateway startup", () => {
426429
}
427430
});
428431

432+
it("passes the resolved TLS fingerprint into the ACP gateway client", async () => {
433+
mockState.resolveGatewayClientBootstrap.mockResolvedValue({
434+
url: "wss://127.0.0.1:18789",
435+
urlSource: "local loopback",
436+
tlsFingerprint: "sha256:local",
437+
auth: {
438+
token: undefined,
439+
password: undefined,
440+
},
441+
});
442+
const { signalHandlers, onceSpy } = captureProcessSignalHandlers();
443+
444+
try {
445+
const servePromise = serveAcpGateway({});
446+
await emitHelloAndWaitForAgentSideConnection();
447+
448+
expect(mockState.gatewayOptions[0]?.tlsFingerprint).toBe("sha256:local");
449+
450+
await stopServeWithSigint(signalHandlers, servePromise);
451+
} finally {
452+
onceSpy.mockRestore();
453+
}
454+
});
455+
429456
it.each([
430457
{
431458
name: "default logging",

‎src/acp/server.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ export async function serveAcpGateway(opts: AcpServerOptions = {}): Promise<void
145145
token: bootstrap.auth.token,
146146
password: bootstrap.auth.password,
147147
preauthHandshakeTimeoutMs: bootstrap.preauthHandshakeTimeoutMs,
148+
tlsFingerprint: bootstrap.tlsFingerprint,
148149
clientName: GATEWAY_CLIENT_NAMES.CLI,
149150
clientDisplayName: "ACP",
150151
clientVersion: "acp",

‎src/gateway/call.ts‎

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ import {
6565
resolveLeastPrivilegeOperatorScopesForMethod,
6666
type OperatorScope,
6767
} from "./method-scopes.js";
68+
import { resolveGatewayConnectionTlsFingerprint } from "./tls-fingerprint.js";
6869
export type { GatewayConnectionDetails };
6970

7071
export type GatewayRequestFunction = <T = Record<string, unknown>>(
@@ -806,29 +807,15 @@ async function resolveGatewayTlsFingerprint(params: {
806807
opts: CallGatewayBaseOptions;
807808
context: ResolvedGatewayCallContext;
808809
url: string;
810+
urlSource: string;
809811
}): Promise<string | undefined> {
810-
const { opts, context, url } = params;
811-
const useLocalTls =
812-
context.config.gateway?.tls?.enabled === true &&
813-
!context.urlOverrideSource &&
814-
!context.remoteUrl &&
815-
url.startsWith("wss://");
816-
const tlsRuntime = useLocalTls
817-
? await gatewayCallDeps.loadGatewayTlsRuntime(context.config.gateway?.tls)
818-
: undefined;
819-
const overrideTlsFingerprint = trimToUndefined(opts.tlsFingerprint);
820-
const remoteTlsFingerprint =
821-
// Env overrides may still inherit configured remote TLS pinning for private cert deployments.
822-
// CLI overrides remain explicit-only and intentionally skip config remote TLS to avoid
823-
// accidentally pinning against caller-supplied target URLs.
824-
context.isRemoteMode && context.urlOverrideSource !== "cli"
825-
? trimToUndefined(context.remote?.tlsFingerprint)
826-
: undefined;
827-
return (
828-
overrideTlsFingerprint ||
829-
remoteTlsFingerprint ||
830-
(tlsRuntime?.enabled ? tlsRuntime.fingerprintSha256 : undefined)
831-
);
812+
return await resolveGatewayConnectionTlsFingerprint({
813+
config: params.context.config,
814+
url: params.url,
815+
urlSource: params.urlSource,
816+
explicitTlsFingerprint: params.opts.tlsFingerprint,
817+
loadGatewayTlsRuntime: gatewayCallDeps.loadGatewayTlsRuntime,
818+
});
832819
}
833820

834821
function formatGatewayCloseError(
@@ -1196,7 +1183,12 @@ async function callGatewayWithScopes<T = Record<string, unknown>>(
11961183
...(opts.configPath ? { configPath: opts.configPath } : {}),
11971184
});
11981185
const url = connectionDetails.url;
1199-
const tlsFingerprint = await resolveGatewayTlsFingerprint({ opts, context, url });
1186+
const tlsFingerprint = await resolveGatewayTlsFingerprint({
1187+
opts,
1188+
context,
1189+
url,
1190+
urlSource: connectionDetails.urlSource,
1191+
});
12001192
const token = useStoredDeviceAuth ? undefined : resolvedCredentials.token;
12011193
const password = useStoredDeviceAuth ? undefined : resolvedCredentials.password;
12021194
const authMode = resolveGatewayCallAuth(context.config).mode;
@@ -1299,6 +1291,7 @@ export async function buildGatewayProbeConnectionDetails(
12991291
opts: callOpts,
13001292
context,
13011293
url: connectionDetails.url,
1294+
urlSource: connectionDetails.urlSource,
13021295
});
13031296
return {
13041297
...connectionDetails,

‎src/gateway/client-bootstrap.test.ts‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,14 @@ type AuthResolutionParams = Parameters<typeof resolveGatewayCredentialsWithSecre
77

88
const mockState = vi.hoisted(() => ({
99
buildGatewayConnectionDetails: vi.fn(),
10+
loadGatewayTlsRuntime: vi.fn(),
1011
resolveGatewayCredentialsWithSecretInputs: vi.fn(),
1112
}));
1213

14+
vi.mock("../infra/tls/gateway.js", () => ({
15+
loadGatewayTlsRuntime: (...args: unknown[]) => mockState.loadGatewayTlsRuntime(...args),
16+
}));
17+
1318
vi.mock("./connection-details.js", () => ({
1419
buildGatewayConnectionDetailsWithResolvers: (...args: unknown[]) =>
1520
mockState.buildGatewayConnectionDetails(...args),
@@ -38,6 +43,11 @@ function expectLastAuthResolutionParams(expected: {
3843
describe("resolveGatewayClientBootstrap", () => {
3944
beforeEach(() => {
4045
mockState.buildGatewayConnectionDetails.mockReset();
46+
mockState.loadGatewayTlsRuntime.mockReset();
47+
mockState.loadGatewayTlsRuntime.mockResolvedValue({
48+
enabled: false,
49+
required: false,
50+
});
4151
mockState.resolveGatewayCredentialsWithSecretInputs.mockReset();
4252
mockState.resolveGatewayCredentialsWithSecretInputs.mockResolvedValue({
4353
token: undefined,
@@ -88,4 +98,130 @@ describe("resolveGatewayClientBootstrap", () => {
8898
urlOverrideSource: undefined,
8999
});
90100
});
101+
102+
it("returns the local TLS fingerprint for config-derived WSS clients", async () => {
103+
const tlsConfig = { enabled: true };
104+
mockState.buildGatewayConnectionDetails.mockReturnValue({
105+
url: "wss://127.0.0.1:18789",
106+
urlSource: "local loopback",
107+
});
108+
mockState.loadGatewayTlsRuntime.mockResolvedValue({
109+
enabled: true,
110+
required: true,
111+
fingerprintSha256: "sha256:local",
112+
});
113+
114+
const result = await resolveGatewayClientBootstrap({
115+
config: { gateway: { tls: tlsConfig } } as never,
116+
env: process.env,
117+
});
118+
119+
expect(result.tlsFingerprint).toBe("sha256:local");
120+
expect(mockState.loadGatewayTlsRuntime).toHaveBeenCalledWith(tlsConfig);
121+
});
122+
123+
it.each([
124+
{
125+
url: "wss://gateway.example/ws",
126+
urlSource: "config gateway.remote.url",
127+
},
128+
{
129+
url: "wss://override.example/ws",
130+
urlSource: "env OPENCLAW_GATEWAY_URL",
131+
},
132+
])("returns the configured remote pin for $urlSource", async ({ url, urlSource }) => {
133+
mockState.buildGatewayConnectionDetails.mockReturnValue({ url, urlSource });
134+
135+
const result = await resolveGatewayClientBootstrap({
136+
config: {
137+
gateway: {
138+
mode: "remote",
139+
remote: {
140+
url: "wss://gateway.example/ws",
141+
tlsFingerprint: "sha256:remote",
142+
},
143+
},
144+
} as never,
145+
env: process.env,
146+
});
147+
148+
expect(result.tlsFingerprint).toBe("sha256:remote");
149+
expect(mockState.loadGatewayTlsRuntime).not.toHaveBeenCalled();
150+
});
151+
152+
it("does not inherit the configured remote pin for CLI URL overrides", async () => {
153+
const url = "wss://override.example/ws";
154+
mockState.buildGatewayConnectionDetails.mockReturnValue({
155+
url,
156+
urlSource: "cli --url",
157+
});
158+
159+
const result = await resolveGatewayClientBootstrap({
160+
config: {
161+
gateway: {
162+
mode: "remote",
163+
remote: {
164+
url: "wss://gateway.example/ws",
165+
tlsFingerprint: "sha256:remote",
166+
},
167+
},
168+
} as never,
169+
gatewayUrl: url,
170+
env: process.env,
171+
});
172+
173+
expect(result.tlsFingerprint).toBeUndefined();
174+
expect(mockState.loadGatewayTlsRuntime).not.toHaveBeenCalled();
175+
});
176+
177+
it("preserves the configured remote pin so plaintext targets fail closed", async () => {
178+
const url = "ws://127.0.0.1:18789";
179+
mockState.buildGatewayConnectionDetails.mockReturnValue({
180+
url,
181+
urlSource: "config gateway.remote.url",
182+
});
183+
184+
const result = await resolveGatewayClientBootstrap({
185+
config: {
186+
gateway: {
187+
mode: "remote",
188+
remote: {
189+
url,
190+
tlsFingerprint: "sha256:remote",
191+
},
192+
},
193+
} as never,
194+
env: process.env,
195+
});
196+
197+
expect(result.tlsFingerprint).toBe("sha256:remote");
198+
expect(mockState.loadGatewayTlsRuntime).not.toHaveBeenCalled();
199+
});
200+
201+
it("uses the local pin when remote mode falls back to the configured local gateway", async () => {
202+
const tlsConfig = { enabled: true };
203+
mockState.buildGatewayConnectionDetails.mockReturnValue({
204+
url: "wss://127.0.0.1:18789",
205+
urlSource: "missing gateway.remote.url (fallback local)",
206+
});
207+
mockState.loadGatewayTlsRuntime.mockResolvedValue({
208+
enabled: true,
209+
required: true,
210+
fingerprintSha256: "sha256:local",
211+
});
212+
213+
const result = await resolveGatewayClientBootstrap({
214+
config: {
215+
gateway: {
216+
mode: "remote",
217+
tls: tlsConfig,
218+
remote: { tlsFingerprint: "sha256:remote" },
219+
},
220+
} as never,
221+
env: process.env,
222+
});
223+
224+
expect(result.tlsFingerprint).toBe("sha256:local");
225+
expect(mockState.loadGatewayTlsRuntime).toHaveBeenCalledWith(tlsConfig);
226+
});
91227
});

0 commit comments

Comments
 (0)