Skip to content

Commit ea46bf5

Browse files
committed
fix(configure): align readiness and loopback consent with runtime
Keep remote TLS pins and edge-auth inputs through health readiness polling by reusing the existing probe parameters. Keep remote config out of local health probes and cover polling through a real TLS socket. Check loopback consent against runtime proxy matching for both parsed bases and containing ranges, preserving mapped IPv4 and exact IPv6 zone semantics. Extend consent and URL-binding coverage without changing runtime authorization or config schemas.
1 parent 214e8a1 commit ea46bf5

9 files changed

Lines changed: 109 additions & 33 deletions

‎docs/cli/configure.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,9 @@ Selecting `gateway`, `daemon`, or `health` (or running the full wizard with no `
3838

3939
For **Trusted Proxy** auth, enter comma-separated IPv4 or IPv6 addresses or CIDR ranges, such as `10.0.0.1, ::1, 10.0.0.0/24`. The wizard rejects malformed addresses and empty entries before saving; surrounding whitespace is ignored.
4040

41-
For **Trusted Proxy** auth, entering a loopback proxy address shows a security warning and asks for explicit consent before setting `gateway.auth.trustedProxy.allowLoopback`. Declining leaves it unset and warns that loopback proxy requests will be rejected at runtime. See [Trusted proxy auth](/gateway/trusted-proxy-auth#configure-with-the-wizard) for the trust requirements.
41+
For **Trusted Proxy** auth, entering an address or CIDR that matches a loopback source shows a security warning and asks for explicit consent before setting `gateway.auth.trustedProxy.allowLoopback`. Declining leaves it unset and warns that loopback proxy requests will be rejected at runtime. See [Trusted proxy auth](/gateway/trusted-proxy-auth#configure-with-the-wizard) for the trust requirements.
4242

43-
Reconfiguring trusted-proxy mode defaults the loopback prompt to the existing opt-in and preserves `deviceAutoApprove` unchanged. An explicit refusal revokes loopback consent; without a loopback address, the existing setting is retained.
43+
Reconfiguring trusted-proxy mode defaults the loopback prompt to the existing opt-in and preserves `deviceAutoApprove` unchanged. An explicit refusal revokes loopback consent; without a matching loopback source, the existing setting is retained.
4444

4545
## Model section
4646

‎docs/gateway/trusted-proxy-auth.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,9 +144,9 @@ Any local process that can connect to the Gateway can impersonate a loopback rev
144144

145145
### Configure with the wizard
146146

147-
Run `openclaw configure --section gateway` and select **Trusted Proxy**. Entering a loopback proxy address (including a CIDR with a loopback base address) shows the security warning above and asks whether to allow loopback authentication. The default is **No** for a new configuration. **Yes** saves `gateway.auth.trustedProxy.allowLoopback: true`; **No** leaves it unset and warns that loopback proxy requests will fail with `trusted_proxy_loopback_source`, with a link back to this page.
147+
Run `openclaw configure --section gateway` and select **Trusted Proxy**. Entering an address or CIDR that matches a loopback source under the Gateway's runtime rules shows the security warning above and asks whether to allow loopback authentication. This includes ranges containing loopback, even when their base address is not loopback. The default is **No** for a new configuration. **Yes** saves `gateway.auth.trustedProxy.allowLoopback: true`; **No** leaves it unset and warns that loopback proxy requests will fail with `trusted_proxy_loopback_source`, with a link back to this page.
148148

149-
When reconfiguring an existing trusted-proxy setup, the prompt defaults to the existing `allowLoopback` opt-in. Choosing **No** revokes it. If no entered proxy address is loopback, the wizard leaves the existing value unchanged. Same-mode reconfiguration also preserves `deviceAutoApprove` verbatim; device enrollment policy is not changed by this prompt. Switching from another auth mode does not restore dormant trusted-proxy opt-ins.
149+
When reconfiguring an existing trusted-proxy setup, the prompt defaults to the existing `allowLoopback` opt-in. Choosing **No** revokes it. If no entered address or range matches a loopback source, the wizard leaves the existing value unchanged. Same-mode reconfiguration also preserves `deviceAutoApprove` verbatim; device enrollment policy is not changed by this prompt. Switching from another auth mode does not restore dormant trusted-proxy opt-ins.
150150

151151
## Per-identity scope grants
152152

‎src/commands/configure.gateway.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { Socket } from "node:net";
44
import { afterEach, describe, expect, it, vi } from "vitest";
55
import type { OpenClawConfig } from "../config/config.js";
66
import { authorizeHttpGatewayConnect, resolveGatewayAuth } from "../gateway/auth.js";
7+
import { isTrustedProxyAddress } from "../gateway/net.js";
78
import type { RuntimeEnv } from "../runtime.js";
89

910
const mocks = vi.hoisted(() => ({
@@ -252,6 +253,11 @@ describe("promptGatewayConfig", () => {
252253
["127.0.0.0/8", "127.0.0.1"],
253254
["::1/128", "::1"],
254255
["127.1/8", "127.0.0.1"],
256+
["127.42.0.0/16", "127.42.0.1"],
257+
["126.0.0.0/7", "127.0.0.1"],
258+
["::/127", "::1"],
259+
["::/0", "::1"],
260+
["::ffff:127.0.0.2/128", "127.0.0.2"],
255261
[" 127.0.0.1 , \t::1/128 ", "::1"],
256262
])("accepts runtime auth after consent for loopback proxy %s", async (proxies, remoteAddress) => {
257263
vi.stubEnv("OPENCLAW_LOCALE", "en");
@@ -276,6 +282,21 @@ describe("promptGatewayConfig", () => {
276282
});
277283
});
278284

285+
it.each(["126.0.0.0/8", "::/128", "::2/127", "::ffff:0:0/96", "::1%LO0"])(
286+
"does not ask for loopback consent when runtime cannot match loopback through %s",
287+
async (proxies) => {
288+
const result = await runTrustedProxyPrompt({
289+
textQueue: ["18789", "x-forwarded-user", "", "", proxies],
290+
});
291+
expect(mocks.confirm).not.toHaveBeenCalled();
292+
expect(result.config.gateway?.auth?.trustedProxy?.allowLoopback).toBeUndefined();
293+
for (const peer of ["127.0.0.1", "::1", "::1%LO0"]) {
294+
expect(isTrustedProxyAddress(peer, result.config.gateway?.trustedProxies)).toBe(false);
295+
expect(await authorizeConfiguredProxy(result.config, peer)).toMatchObject({ ok: false });
296+
}
297+
},
298+
);
299+
279300
it.each([
280301
["en", "Any local process", "Allow loopback", "will be rejected"],
281302
["zh-CN", "任何本地进程", "允许回环", "将被拒绝"],

‎src/commands/configure.gateway.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import {
1919
TAILSCALE_EXPOSURE_OPTIONS,
2020
TAILSCALE_MISSING_BIN_NOTE_LINES,
2121
} from "../gateway/gateway-config-prompts.shared.js";
22-
import { isLoopbackAddress } from "../gateway/net.js";
22+
import { isLoopbackAddress, isTrustedProxyAddress } from "../gateway/net.js";
2323
import { findTailscaleBinary } from "../infra/tailscale.js";
2424
import type { RuntimeEnv } from "../runtime.js";
2525
import { resolveDefaultSecretProviderAlias } from "../secrets/ref-contract.js";
@@ -319,11 +319,15 @@ export async function promptGatewayConfig(
319319
const existingProxy =
320320
cfg.gateway?.auth?.mode === "trusted-proxy" ? cfg.gateway.auth.trustedProxy : undefined;
321321
let allowLoopback = existingProxy?.allowLoopback;
322-
// Parse CIDR bases before classification so runtime-accepted aliases still require consent.
322+
// The base covers subnets within loopback; representative peers cover ranges containing it.
323+
// Use runtime matching too, including its mapped IPv4 and exact IPv6 zone semantics.
323324
if (
324-
trustedProxies.some((address) =>
325-
isLoopbackAddress(parseIpAddressOrCidr(address)?.[0].toString()),
326-
)
325+
trustedProxies.some((address) => {
326+
const base = parseIpAddressOrCidr(address)?.[0].toString();
327+
return [base, "127.0.0.1", "::1"].some(
328+
(peer) => isLoopbackAddress(peer) && isTrustedProxyAddress(peer, [address]),
329+
);
330+
})
327331
) {
328332
const title = t("wizard.gateway.trustedProxyLoopbackTitle");
329333
note(t("wizard.gateway.trustedProxyLoopbackWarning"), title);

‎src/commands/configure.wizard.gateway.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ describe("runConfigureWizard", () => {
233233
url: "wss://gateway.example.test",
234234
token: { source: "env", provider: "default", id: "MISSING_REMOTE_TOKEN" },
235235
password: remotePassword,
236+
tlsFingerprint: "ab".repeat(32),
236237
},
237238
},
238239
secrets: { providers: { default: { source: "env" } } },
@@ -243,6 +244,9 @@ describe("runConfigureWizard", () => {
243244

244245
await runConfigureWizard({ command: "configure", sections: ["health"] }, createRuntime());
245246

247+
expect(mocks.waitForGatewayReachable).toHaveBeenCalledWith(
248+
expect.objectContaining({ url: remoteConfig.gateway?.remote?.url, config: remoteConfig }),
249+
);
246250
expect(mocks.healthCommand).toHaveBeenCalledWith(
247251
expect.objectContaining({
248252
config: remoteConfig,

‎src/commands/configure.wizard.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,7 @@ async function runGatewayHealthCheck(params: {
161161
try {
162162
const gatewayProbe = await waitForGatewayReachable({
163163
url: wsUrl,
164+
...(probeMode === "remote" ? { config: params.cfg } : {}),
164165
token,
165166
password,
166167
...(params.daemonSetupOutcome === "succeeded"

‎src/commands/onboard-helpers.remote-probe.test.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22
import { afterEach, describe, expect, it, vi } from "vitest";
33
import { ConnectErrorDetailCodes } from "../../packages/gateway-protocol/src/connect-error-details.js";
44
import type { OpenClawConfig } from "../config/types.openclaw.js";
5-
import { probeGatewayConfiguredModel, probeGatewayReachable } from "./onboard-helpers.js";
5+
import {
6+
probeGatewayConfiguredModel,
7+
probeGatewayReachable,
8+
waitForGatewayReachable,
9+
} from "./onboard-helpers.js";
610

711
const mocks = vi.hoisted(() => ({ probeGateway: vi.fn() }));
812

@@ -44,19 +48,23 @@ describe("probeGatewayReachable", () => {
4448
});
4549
});
4650

47-
it("forwards configured remote edge auth to the gateway probe", async () => {
51+
it.each([
52+
["single probe", probeGatewayReachable],
53+
["polling", waitForGatewayReachable],
54+
] as const)("forwards remote trust through %s", async (_name, probe) => {
4855
mocks.probeGateway.mockResolvedValueOnce({ ok: true, configSnapshot: null });
4956
const config: OpenClawConfig = {
5057
gateway: {
5158
mode: "remote",
5259
remote: {
5360
url: "wss://gateway.example",
5461
edgeAuth: { "X-Edge-Auth": "test-secret" },
62+
tlsFingerprint: "ab".repeat(32),
5563
},
5664
},
5765
};
5866

59-
await expect(probeGatewayReachable({ url: "wss://gateway.example", config })).resolves.toEqual({
67+
await expect(probe({ url: "wss://gateway.example", config })).resolves.toEqual({
6068
ok: true,
6169
});
6270
expect(mocks.probeGateway).toHaveBeenCalledWith(

‎src/commands/onboard-helpers.ts‎

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -421,28 +421,24 @@ export async function probeGatewayConfiguredModel(
421421
}
422422

423423
/** Polls gateway reachability until success or deadline. */
424-
export async function waitForGatewayReachable(params: {
425-
url: string;
426-
token?: string;
427-
password?: string;
428-
/** Total time to wait before giving up. */
429-
deadlineMs?: number;
430-
/** Per-probe timeout (each probe makes a full gateway health request). */
431-
probeTimeoutMs?: number;
432-
/** Delay between probes. */
433-
pollMs?: number;
434-
}): Promise<{ ok: boolean; detail?: string }> {
435-
const deadlineMs = params.deadlineMs ?? 15_000;
436-
const pollMs = resolveTimerTimeoutMs(params.pollMs ?? 400, 400, 0);
437-
const probeTimeoutMs = params.probeTimeoutMs ?? 1500;
424+
export async function waitForGatewayReachable(
425+
params: Omit<OnboardingGatewayProbeParams, "timeoutMs"> & {
426+
/** Total time to wait before giving up. */
427+
deadlineMs?: number;
428+
/** Per-probe timeout for the hello-only readiness check. */
429+
probeTimeoutMs?: number;
430+
/** Delay between probes. */
431+
pollMs?: number;
432+
},
433+
): Promise<{ ok: boolean; detail?: string }> {
434+
const { deadlineMs = 15_000, pollMs = 400, probeTimeoutMs = 1500, ...probeParams } = params;
435+
const pollDelayMs = resolveTimerTimeoutMs(pollMs, 400, 0);
438436
const startedAt = Date.now();
439437
let lastDetail: string | undefined;
440438

441439
while (Date.now() - startedAt < deadlineMs) {
442440
const probe = await probeGatewayReachable({
443-
url: params.url,
444-
token: params.token,
445-
password: params.password,
441+
...probeParams,
446442
timeoutMs: probeTimeoutMs,
447443
});
448444
if (probe.ok) {
@@ -453,7 +449,7 @@ export async function waitForGatewayReachable(params: {
453449
if (remainingMs <= 0) {
454450
break;
455451
}
456-
await sleep(Math.min(pollMs, remainingMs));
452+
await sleep(Math.min(pollDelayMs, remainingMs));
457453
}
458454

459455
return { ok: false, detail: lastDetail };

‎src/gateway/probe.tls.test.ts‎

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@ import type { AddressInfo, Socket } from "node:net";
44
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
55
import { WebSocketServer } from "ws";
66
import { TEST_TLS_CERT_PEM, TEST_TLS_KEY_PEM } from "../../test/helpers/tls-fixture.js";
7+
import { waitForGatewayReachable } from "../commands/onboard-helpers.js";
78
import type { OpenClawConfig } from "../config/types.openclaw.js";
89
import { resetSecretRedactionRegistryForTest } from "../logging/secret-redaction-registry.test-support.js";
910
import { createSuiteTempRootTracker, withTestDir } from "../test-helpers/temp-dir.js";
11+
import { withEnvAsync } from "../test-utils/env.js";
1012
import { resolveGatewayClientBootstrap } from "./client-bootstrap.js";
1113
import {
1214
buildMinimalGatewayHelloOkPayload,
@@ -169,6 +171,20 @@ describe("Gateway probe TLS trust", () => {
169171

170172
it.each([
171173
{ name: "saved pin", savedPin: fingerprint, ok: true },
174+
{ name: "probe URL whitespace", savedPin: fingerprint, urlVariant: "whitespace", ok: true },
175+
{
176+
name: "identical uppercase scheme",
177+
savedPin: fingerprint,
178+
urlVariant: "same-case",
179+
ok: true,
180+
},
181+
{
182+
name: "case-changed endpoint",
183+
savedPin: fingerprint,
184+
urlVariant: "different-case",
185+
ok: false,
186+
error: "certificate",
187+
},
172188
{ name: "saved pin in local mode", savedPin: fingerprint, local: true, ok: true },
173189
{ name: "saved pin with whitespace", savedPin: ` sha256:${fingerprint} `, ok: true },
174190
{
@@ -201,19 +217,27 @@ describe("Gateway probe TLS trust", () => {
201217
},
202218
])(
203219
"enforces $name before sending Gateway credentials",
204-
async ({ savedPin, explicitPin, local, changed, ok, error }) => {
220+
async ({ savedPin, explicitPin, local, changed, urlVariant, ok, error }) => {
205221
const before = {
206222
receivedBytes: gateway.observed.receivedBytes,
207223
edgeAuthHeaders: gateway.observed.edgeAuthHeaders.length,
208224
connectFrames: gateway.observed.connectFrames,
209225
};
226+
const probeUrl =
227+
urlVariant === "whitespace"
228+
? ` ${url} `
229+
: urlVariant?.endsWith("case")
230+
? url.replace("wss:", "WSS:")
231+
: url;
232+
const savedUrl =
233+
urlVariant === "same-case" ? probeUrl : changed ? `${url}/other` : ` ${url} `;
210234
const result = await probeGateway({
211-
url,
235+
url: probeUrl,
212236
config: {
213237
gateway: {
214238
mode: local ? "local" : "remote",
215239
remote: {
216-
url: changed ? `${url}/other` : ` ${url} `,
240+
url: savedUrl,
217241
tlsFingerprint: savedPin,
218242
edgeAuth: { "X-Test-Edge-Auth": edgeAuthValue },
219243
},
@@ -244,4 +268,22 @@ describe("Gateway probe TLS trust", () => {
244268
}
245269
},
246270
);
271+
272+
it("retains saved TLS trust through the health readiness polling path", async () => {
273+
const before = gateway.observed.connectFrames;
274+
const result = await withEnvAsync(
275+
{ OPENCLAW_STATE_DIR: await tempDirs.make("polling-state") },
276+
() =>
277+
waitForGatewayReachable({
278+
url,
279+
config: { gateway: { mode: "remote", remote: { url, tlsFingerprint: fingerprint } } },
280+
token: "test-probe-token",
281+
deadlineMs: 2_000,
282+
probeTimeoutMs: 2_000,
283+
}),
284+
);
285+
expect(result).toEqual({ ok: true });
286+
await gateway.drain();
287+
expect(gateway.observed.connectFrames - before).toBe(1);
288+
});
247289
});

0 commit comments

Comments
 (0)