Skip to content

Commit e640c0a

Browse files
committed
fix(gateway): decouple backend RPC from CLI pairing
1 parent 91adb69 commit e640c0a

7 files changed

Lines changed: 175 additions & 12 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,11 @@ Docs: https://docs.openclaw.ai
6161

6262
### Fixes
6363

64+
- Gateway/subagents: keep direct-loopback backend RPCs authenticated with the
65+
shared gateway token/password off stale CLI paired-device scope baselines, so
66+
internal calls no longer hit `scope-upgrade` pairing prompts while remote,
67+
browser, node, device-token, and explicit-device paths still require normal
68+
pairing approval. Fixes #63548.
6469
- CLI/gateway: keep diagnostic probes from creating first-time read-only device
6570
pairings, while still reusing cached device tokens for detailed read probes.
6671
Fixes #71766. Thanks @SunboZ.

‎docs/gateway/protocol.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,14 @@ permissions:
110110
}
111111
```
112112

113+
Trusted same-process backend clients (`client.id: "gateway-client"`,
114+
`client.mode: "backend"`) may omit `device` on direct loopback connections when
115+
they authenticate with the shared gateway token/password. This path is reserved
116+
for internal control-plane RPCs and keeps stale CLI/device pairing baselines from
117+
blocking local backend work such as subagent session updates. Remote clients,
118+
browser-origin clients, node clients, and explicit device-token/device-identity
119+
clients still use the normal pairing and scope-upgrade checks.
120+
113121
When a device token is issued, `hello-ok` also includes:
114122

115123
```json

‎docs/gateway/security/index.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,11 @@ Treat Gateway and node as one operator trust domain, with different roles:
9292
- **Gateway** is the control plane and policy surface (`gateway.auth`, tool policy, routing).
9393
- **Node** is remote execution surface paired to that Gateway (commands, device actions, host-local capabilities).
9494
- A caller authenticated to the Gateway is trusted at Gateway scope. After pairing, node actions are trusted operator actions on that node.
95+
- Direct loopback backend clients authenticated with the shared gateway
96+
token/password can make internal control-plane RPCs without presenting a user
97+
device identity. This is not a remote or browser pairing bypass: network
98+
clients, node clients, device-token clients, and explicit device identities
99+
still go through pairing and scope-upgrade enforcement.
95100
- `sessionKey` is routing/context selection, not per-user auth.
96101
- Exec approvals (allowlist + ask) are guardrails for operator intent, not hostile multi-tenant isolation.
97102
- OpenClaw's product default for trusted single-operator setups is that host exec on `gateway`/`node` is allowed without approval prompts (`security="full"`, `ask="off"` unless you tighten it). That default is intentional UX, not a vulnerability by itself.

‎docs/gateway/troubleshooting.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,12 @@ Use `error.details.code` from the failed `connect` response to pick the next act
200200
| `AUTH_DEVICE_TOKEN_MISMATCH` | Cached per-device token is stale or revoked. | Rotate/re-approve device token using [devices CLI](/cli/devices), then reconnect. |
201201
| `PAIRING_REQUIRED` | Device identity needs approval. Check `error.details.reason` for `not-paired`, `scope-upgrade`, `role-upgrade`, or `metadata-upgrade`, and use `requestId` / `remediationHint` when present. | Approve pending request: `openclaw devices list` then `openclaw devices approve <requestId>`. Scope/role upgrades use the same flow after you review the requested access. |
202202

203+
Direct loopback backend RPCs authenticated with the shared gateway
204+
token/password should not depend on the CLI's paired-device scope baseline. If
205+
subagents or other internal calls still fail with `scope-upgrade`, verify the
206+
caller is using `client.id: "gateway-client"` and `client.mode: "backend"` and
207+
is not forcing an explicit `deviceIdentity` or device token.
208+
203209
Device auth v2 migration check:
204210

205211
```bash

‎src/gateway/call.test.ts‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,9 @@ let lastClientOptions: {
2727
token?: string;
2828
password?: string;
2929
tlsFingerprint?: string;
30+
clientName?: string;
3031
clientDisplayName?: string;
32+
mode?: string;
3133
scopes?: string[];
3234
deviceIdentity?: unknown;
3335
onHelloOk?: (hello: { features?: { methods?: string[] } }) => void | Promise<void>;
@@ -59,7 +61,9 @@ vi.mock("./client.js", () => ({
5961
url?: string;
6062
token?: string;
6163
password?: string;
64+
clientName?: string;
6265
clientDisplayName?: string;
66+
mode?: string;
6367
scopes?: string[];
6468
onHelloOk?: (hello: { features?: { methods?: string[] } }) => void | Promise<void>;
6569
onClose?: (code: number, reason: string) => void;
@@ -97,7 +101,9 @@ class StubGatewayClient {
97101
url?: string;
98102
token?: string;
99103
password?: string;
104+
clientName?: string;
100105
clientDisplayName?: string;
106+
mode?: string;
101107
scopes?: string[];
102108
onHelloOk?: (hello: { features?: { methods?: string[] } }) => void | Promise<void>;
103109
onClose?: (code: number, reason: string) => void;
@@ -303,14 +309,31 @@ describe("callGateway url resolution", () => {
303309
expect(lastClientOptions?.token).toBe("test-token");
304310
});
305311

306-
it("keeps device identity enabled for local loopback shared-token auth", async () => {
312+
it("keeps direct-local backend shared-token auth independent of paired device state", async () => {
307313
setLocalLoopbackGatewayConfig();
308314

309315
await callGateway({
310316
method: "health",
311317
token: "explicit-token",
312318
});
313319

320+
expect(lastClientOptions?.url).toBe("ws://127.0.0.1:18789");
321+
expect(lastClientOptions?.token).toBe("explicit-token");
322+
expect(lastClientOptions?.clientName).toBe(GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT);
323+
expect(lastClientOptions?.mode).toBe(GATEWAY_CLIENT_MODES.BACKEND);
324+
expect(lastClientOptions?.deviceIdentity).toBeNull();
325+
});
326+
327+
it("keeps device identity enabled for explicit CLI loopback shared-token auth", async () => {
328+
setLocalLoopbackGatewayConfig();
329+
330+
await callGateway({
331+
method: "health",
332+
token: "explicit-token",
333+
clientName: GATEWAY_CLIENT_NAMES.CLI,
334+
mode: GATEWAY_CLIENT_MODES.CLI,
335+
});
336+
314337
expect(lastClientOptions?.url).toBe("ws://127.0.0.1:18789");
315338
expect(lastClientOptions?.token).toBe("explicit-token");
316339
expect(lastClientOptions?.deviceIdentity).toEqual(deviceIdentityState.value);
@@ -331,6 +354,22 @@ describe("callGateway url resolution", () => {
331354
expect(lastRequestOptions?.method).toBe("health");
332355
});
333356

357+
it("keeps backend device identity enabled for remote shared-token auth", async () => {
358+
loadConfig.mockReturnValue(makeRemotePasswordGatewayConfig("remote-password"));
359+
setGatewayNetworkDefaults();
360+
361+
await callGateway({
362+
method: "health",
363+
token: "explicit-token",
364+
});
365+
366+
expect(lastClientOptions?.url).toBe("wss://remote.example:18789");
367+
expect(lastClientOptions?.token).toBe("explicit-token");
368+
expect(lastClientOptions?.clientName).toBe(GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT);
369+
expect(lastClientOptions?.mode).toBe(GATEWAY_CLIENT_MODES.BACKEND);
370+
expect(lastClientOptions?.deviceIdentity).toEqual(deviceIdentityState.value);
371+
});
372+
334373
it("honors an explicit null device identity override", async () => {
335374
setLocalLoopbackGatewayConfig();
336375

@@ -470,6 +509,22 @@ describe("callGateway url resolution", () => {
470509
expect(lastClientOptions?.scopes).toEqual([]);
471510
});
472511

512+
it("uses backend client metadata for explicit scoped default calls", async () => {
513+
setLocalLoopbackGatewayConfig();
514+
515+
await callGateway({
516+
method: "sessions.delete",
517+
scopes: ["operator.admin"],
518+
token: "explicit-token",
519+
});
520+
521+
expect(lastClientOptions?.clientName).toBe(GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT);
522+
expect(lastClientOptions?.mode).toBe(GATEWAY_CLIENT_MODES.BACKEND);
523+
expect(lastClientOptions?.clientDisplayName).toBe("gateway:sessions.delete");
524+
expect(lastClientOptions?.scopes).toEqual(["operator.admin"]);
525+
expect(lastClientOptions?.deviceIdentity).toBeNull();
526+
});
527+
473528
it("labels default backend calls with the requested method", async () => {
474529
setLocalLoopbackGatewayConfig();
475530

‎src/gateway/call.ts‎

Lines changed: 49 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
import type { OpenClawConfig } from "../config/types.openclaw.js";
99
import { loadOrCreateDeviceIdentity, type DeviceIdentity } from "../infra/device-identity.js";
1010
import { loadGatewayTlsRuntime } from "../infra/tls/gateway.js";
11+
import { isLoopbackIpAddress } from "../shared/net/ip.js";
1112
import { normalizeOptionalString } from "../shared/string-coerce.js";
1213
import {
1314
GATEWAY_CLIENT_MODES,
@@ -194,12 +195,43 @@ export const __testing = {
194195
},
195196
};
196197

197-
function resolveDeviceIdentityForGatewayCall(): ReturnType<
198-
typeof loadOrCreateDeviceIdentity
199-
> | null {
200-
// Shared-auth local calls should still stay device-bound so operator scopes
201-
// remain available for detail RPCs such as status / system-presence /
202-
// last-heartbeat.
198+
function isLoopbackGatewayUrl(rawUrl: string): boolean {
199+
try {
200+
const hostname = new URL(rawUrl).hostname.toLowerCase();
201+
const unbracketed =
202+
hostname.startsWith("[") && hostname.endsWith("]") ? hostname.slice(1, -1) : hostname;
203+
return unbracketed === "localhost" || isLoopbackIpAddress(unbracketed);
204+
} catch {
205+
return false;
206+
}
207+
}
208+
209+
function shouldOmitDeviceIdentityForGatewayCall(params: {
210+
opts: CallGatewayBaseOptions;
211+
url: string;
212+
token?: string;
213+
password?: string;
214+
}): boolean {
215+
const mode = params.opts.mode ?? GATEWAY_CLIENT_MODES.CLI;
216+
const clientName = params.opts.clientName ?? GATEWAY_CLIENT_NAMES.CLI;
217+
const hasSharedAuth = Boolean(params.token || params.password);
218+
return (
219+
mode === GATEWAY_CLIENT_MODES.BACKEND &&
220+
clientName === GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT &&
221+
hasSharedAuth &&
222+
isLoopbackGatewayUrl(params.url)
223+
);
224+
}
225+
226+
function resolveDeviceIdentityForGatewayCall(params: {
227+
opts: CallGatewayBaseOptions;
228+
url: string;
229+
token?: string;
230+
password?: string;
231+
}): ReturnType<typeof loadOrCreateDeviceIdentity> | null {
232+
if (shouldOmitDeviceIdentityForGatewayCall(params)) {
233+
return null;
234+
}
203235
try {
204236
return gatewayCallDeps.loadOrCreateDeviceIdentity();
205237
} catch {
@@ -515,7 +547,7 @@ async function executeGatewayRequestWithScopes<T>(params: {
515547
scopes,
516548
deviceIdentity:
517549
opts.deviceIdentity === undefined
518-
? resolveDeviceIdentityForGatewayCall()
550+
? resolveDeviceIdentityForGatewayCall({ opts, url, token, password })
519551
: opts.deviceIdentity,
520552
minProtocol: opts.minProtocol ?? PROTOCOL_VERSION,
521553
maxProtocol: opts.maxProtocol ?? PROTOCOL_VERSION,
@@ -616,14 +648,21 @@ export async function callGatewayLeastPrivilege<T = Record<string, unknown>>(
616648
export async function callGateway<T = Record<string, unknown>>(
617649
opts: CallGatewayOptions,
618650
): Promise<T> {
619-
if (Array.isArray(opts.scopes)) {
620-
return await callGatewayWithScopes(opts, opts.scopes);
621-
}
622651
const callerMode = opts.mode ?? GATEWAY_CLIENT_MODES.BACKEND;
623652
const callerName = opts.clientName ?? GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT;
624653
if (callerMode === GATEWAY_CLIENT_MODES.CLI || callerName === GATEWAY_CLIENT_NAMES.CLI) {
625654
return await callGatewayCli(opts);
626655
}
656+
if (Array.isArray(opts.scopes)) {
657+
return await callGatewayWithScopes(
658+
{
659+
...opts,
660+
mode: callerMode,
661+
clientName: callerName,
662+
},
663+
opts.scopes,
664+
);
665+
}
627666
return await callGatewayLeastPrivilege({
628667
...opts,
629668
mode: callerMode,

‎src/gateway/server.silent-scope-upgrade-reconnect.poc.test.ts‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,17 @@
11
import { describe, expect, test, vi } from "vitest";
22
import { WebSocket } from "ws";
3+
import {
4+
loadOrCreateDeviceIdentity,
5+
publicKeyRawBase64UrlFromPem,
6+
} from "../infra/device-identity.js";
37
import * as devicePairingModule from "../infra/device-pairing.js";
4-
import { getPairedDevice } from "../infra/device-pairing.js";
8+
import {
9+
approveDevicePairing,
10+
getPairedDevice,
11+
requestDevicePairing,
12+
} from "../infra/device-pairing.js";
513
import { GATEWAY_CLIENT_MODES, GATEWAY_CLIENT_NAMES } from "../utils/message-channel.js";
14+
import { callGateway } from "./call.js";
615
import {
716
issueOperatorToken,
817
loadDeviceIdentity,
@@ -223,6 +232,42 @@ describe("gateway silent scope-upgrade reconnect", () => {
223232
}
224233
});
225234

235+
test("keeps direct-local backend callGateway scoped calls off stale paired CLI baseline", async () => {
236+
const started = await startServerWithClient("secret");
237+
const identity = loadOrCreateDeviceIdentity();
238+
const publicKey = publicKeyRawBase64UrlFromPem(identity.publicKeyPem);
239+
const request = await requestDevicePairing({
240+
deviceId: identity.deviceId,
241+
publicKey,
242+
role: "operator",
243+
scopes: ["operator.read"],
244+
clientId: GATEWAY_CLIENT_NAMES.CLI,
245+
clientMode: GATEWAY_CLIENT_MODES.CLI,
246+
});
247+
await approveDevicePairing(request.request.requestId, {
248+
callerScopes: ["operator.read"],
249+
});
250+
251+
try {
252+
await expect(
253+
callGateway({
254+
url: `ws://127.0.0.1:${started.port}`,
255+
token: "secret",
256+
method: "health",
257+
scopes: ["operator.admin"],
258+
timeoutMs: 2_000,
259+
}),
260+
).resolves.toMatchObject({ ok: true });
261+
262+
const paired = await getPairedDevice(identity.deviceId);
263+
expect(paired?.approvedScopes).toEqual(["operator.read"]);
264+
} finally {
265+
started.ws.close();
266+
await started.server.close();
267+
started.envSnapshot.restore();
268+
}
269+
});
270+
226271
test("accepts local silent reconnect when pairing was concurrently approved", async () => {
227272
const started = await startServerWithClient("secret");
228273
const loaded = loadDeviceIdentity("silent-reconnect-race");

0 commit comments

Comments
 (0)