Skip to content

Commit 16865d5

Browse files
vincentkocsteipete
andauthored
fix(gateway): keep local CLI shared auth off device scopes (#96002)
* fix(gateway): keep local CLI shared auth off device scopes * fix(gateway): preserve auth-none CLI device identity --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 8a69810 commit 16865d5

8 files changed

Lines changed: 201 additions & 24 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Docs: https://docs.openclaw.ai
99
### Fixes
1010

1111
- **WhatsApp restart recovery:** stop automatic restart loops after logged-out or connection-replaced disconnects until the account reconnects. (#78511) Thanks @openperf.
12+
- **Local Gateway CLI auth:** keep loopback CLI token/password calls off durable device scopes so read probes cannot block later write/admin commands behind a stale pairing baseline. (#95997) Thanks @vincentkoc.
1213
- **iMessage group warnings:** suppress the false drop-all startup warning when an effective group sender allowlist can admit groups, and point true empty-allowlist configurations at the correct remedy. (#100046)
1314
- **Control UI mobile login:** keep Gateway recovery guidance visible after connection failures, make the disconnected gate scroll safely on constrained screens, and improve mobile keyboard and tap-target behavior. (#100208)
1415

‎src/gateway/call.test.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -552,7 +552,7 @@ describe("callGateway url resolution", () => {
552552
expect(lastClientOptions?.password).toBeUndefined();
553553
});
554554

555-
it("keeps device identity enabled for explicit CLI loopback shared-token auth", async () => {
555+
it("omits device identity for explicit CLI loopback shared-token auth", async () => {
556556
setLocalLoopbackGatewayConfig();
557557

558558
await callGateway({
@@ -564,6 +564,19 @@ describe("callGateway url resolution", () => {
564564

565565
expect(lastClientOptions?.url).toBe("ws://127.0.0.1:18789");
566566
expect(lastClientOptions?.token).toBe("explicit-token");
567+
expect(lastClientOptions?.deviceIdentity).toBeNull();
568+
});
569+
570+
it("keeps CLI device identity when an ambient token is inactive under auth mode none", async () => {
571+
getRuntimeConfig.mockReturnValue({
572+
gateway: { mode: "local", bind: "loopback", auth: { mode: "none" } },
573+
});
574+
setGatewayNetworkDefaults();
575+
process.env.OPENCLAW_GATEWAY_TOKEN = "inactive-env-token";
576+
577+
await callGatewayCli({ method: "health" });
578+
579+
expect(lastClientOptions?.token).toBe("inactive-env-token");
567580
expect(lastClientOptions?.deviceIdentity).toEqual(deviceIdentityState.value);
568581
});
569582

‎src/gateway/call.ts‎

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -484,31 +484,33 @@ function isLoopbackGatewayUrl(rawUrl: string): boolean {
484484
function shouldOmitDeviceIdentityForGatewayCall(params: {
485485
opts: CallGatewayBaseOptions;
486486
url: string;
487+
authMode: ReturnType<typeof resolveGatewayAuth>["mode"];
487488
token?: string;
488489
password?: string;
489490
allowAuthNone?: boolean;
490491
}): boolean {
491492
const mode = params.opts.mode ?? GATEWAY_CLIENT_MODES.CLI;
492493
const clientName = params.opts.clientName ?? GATEWAY_CLIENT_NAMES.CLI;
493-
const hasDirectLocalBackendAuth =
494-
Boolean(params.token || params.password) || params.allowAuthNone === true;
495-
return (
494+
// Inactive ambient credentials must not turn an auth-none CLI call device-less.
495+
// Omit identity only when the Gateway will actually authenticate the supplied secret.
496+
const hasSharedSecretAuth =
497+
(params.authMode === "token" && Boolean(params.token)) ||
498+
(params.authMode === "password" && Boolean(params.password));
499+
const isLoopback = isLoopbackGatewayUrl(params.url);
500+
const isLocalBackendSharedAuth =
496501
mode === GATEWAY_CLIENT_MODES.BACKEND &&
497502
clientName === GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT &&
498-
hasDirectLocalBackendAuth &&
499-
isLoopbackGatewayUrl(params.url)
500-
);
503+
(hasSharedSecretAuth || params.allowAuthNone === true) &&
504+
isLoopback;
505+
const isLocalCliSharedAuth =
506+
mode === GATEWAY_CLIENT_MODES.CLI &&
507+
clientName === GATEWAY_CLIENT_NAMES.CLI &&
508+
hasSharedSecretAuth &&
509+
isLoopback;
510+
return isLocalBackendSharedAuth || isLocalCliSharedAuth;
501511
}
502512

503-
function resolveDeviceIdentityForGatewayCall(params: {
504-
opts: CallGatewayBaseOptions;
505-
url: string;
506-
token?: string;
507-
password?: string;
508-
}): ReturnType<typeof loadOrCreateDeviceIdentity> | null {
509-
if (shouldOmitDeviceIdentityForGatewayCall(params)) {
510-
return null;
511-
}
513+
function resolveDeviceIdentityForGatewayCall(): DeviceIdentity | null {
512514
try {
513515
return gatewayCallDeps.loadOrCreateDeviceIdentity();
514516
} catch {
@@ -1163,12 +1165,12 @@ async function callGatewayWithScopes<T = Record<string, unknown>>(
11631165
const tlsFingerprint = await resolveGatewayTlsFingerprint({ opts, context, url });
11641166
const token = useStoredDeviceAuth ? undefined : resolvedCredentials.token;
11651167
const password = useStoredDeviceAuth ? undefined : resolvedCredentials.password;
1166-
const allowAuthNone =
1167-
opts.requireLocalBackendSharedAuth === true &&
1168-
resolveGatewayCallAuth(context.config).mode === "none";
1168+
const authMode = resolveGatewayCallAuth(context.config).mode;
1169+
const allowAuthNone = opts.requireLocalBackendSharedAuth === true && authMode === "none";
11691170
const omitDeviceIdentity = shouldOmitDeviceIdentityForGatewayCall({
11701171
opts,
11711172
url,
1173+
authMode,
11721174
token,
11731175
password,
11741176
allowAuthNone,
@@ -1182,7 +1184,7 @@ async function callGatewayWithScopes<T = Record<string, unknown>>(
11821184
opts.deviceIdentity === undefined
11831185
? omitDeviceIdentity
11841186
? null
1185-
: resolveDeviceIdentityForGatewayCall({ opts, url, token, password })
1187+
: resolveDeviceIdentityForGatewayCall()
11861188
: opts.deviceIdentity;
11871189
if (useStoredDeviceAuth) {
11881190
const storedAuth = loadStoredOperatorDeviceAuthToken(deviceIdentity);

‎src/gateway/server.auth.compat-baseline.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import {
1111
ConnectErrorDetailCodes,
1212
createSignedDevice,
1313
getFreePort,
14+
GATEWAY_CLIENT_MODES,
15+
GATEWAY_CLIENT_NAMES,
1416
readConnectChallengeNonce,
1517
openWs,
1618
originForPort,
@@ -23,6 +25,13 @@ import {
2325

2426
installGatewayTestHooks({ scope: "suite" });
2527

28+
const CLI_CLIENT = {
29+
id: GATEWAY_CLIENT_NAMES.CLI,
30+
version: "1.0.0",
31+
platform: "test",
32+
mode: GATEWAY_CLIENT_MODES.CLI,
33+
};
34+
2635
function expectAuthErrorDetails(params: {
2736
details: unknown;
2837
expectedCode: string;
@@ -96,6 +105,36 @@ async function expectLocalBackendGatewayClientScopesPreserved(
96105
}
97106
}
98107

108+
async function expectLocalCliSharedAuthScopesPreserved(
109+
port: number,
110+
auth: { token?: string; password?: string },
111+
) {
112+
const ws = await openWs(port);
113+
try {
114+
const res = await connectReq(ws, {
115+
...auth,
116+
client: { ...CLI_CLIENT },
117+
scopes: ["operator.admin"],
118+
device: null,
119+
});
120+
expect(res.ok, JSON.stringify(res)).toBe(true);
121+
122+
const helloOk = res.payload as
123+
| {
124+
auth?: {
125+
scopes?: unknown;
126+
};
127+
}
128+
| undefined;
129+
expect(helloOk?.auth?.scopes).toEqual(["operator.admin"]);
130+
131+
const adminRes = await rpcReq(ws, "set-heartbeats", { enabled: false });
132+
expect(adminRes.ok).toBe(true);
133+
} finally {
134+
ws.close();
135+
}
136+
}
137+
99138
describe("gateway auth compatibility baseline", () => {
100139
describe("token mode", () => {
101140
let server: Awaited<ReturnType<typeof startGatewayServer>>;
@@ -133,6 +172,10 @@ describe("gateway auth compatibility baseline", () => {
133172
await expectLocalBackendGatewayClientScopesPreserved(port, { token: "secret" });
134173
});
135174

175+
test("preserves scopes for direct-local CLI shared-token connects without device identity", async () => {
176+
await expectLocalCliSharedAuthScopesPreserved(port, { token: "secret" });
177+
});
178+
136179
test("returns stable token-missing details for control ui without token", async () => {
137180
const ws = await openWs(port, { origin: originForPort(port) });
138181
try {
@@ -306,6 +349,10 @@ describe("gateway auth compatibility baseline", () => {
306349
test("preserves scopes for direct-local backend shared-password connects without device identity", async () => {
307350
await expectLocalBackendGatewayClientScopesPreserved(port, { password: "secret" });
308351
});
352+
353+
test("preserves scopes for direct-local CLI shared-password connects without device identity", async () => {
354+
await expectLocalCliSharedAuthScopesPreserved(port, { password: "secret" });
355+
});
309356
});
310357

311358
describe("none mode", () => {

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,44 @@ describe("gateway silent scope-upgrade reconnect", () => {
271271
}
272272
});
273273

274+
test("keeps direct-local CLI shared-token calls off stale paired CLI baseline", async () => {
275+
const started = await startServerWithClient("secret");
276+
const identity = await approveReadScopedDevice({
277+
clientId: GATEWAY_CLIENT_NAMES.CLI,
278+
clientMode: GATEWAY_CLIENT_MODES.CLI,
279+
});
280+
281+
try {
282+
const health = await callGateway({
283+
url: `ws://127.0.0.1:${started.port}`,
284+
token: "secret",
285+
method: "health",
286+
clientName: GATEWAY_CLIENT_NAMES.CLI,
287+
mode: GATEWAY_CLIENT_MODES.CLI,
288+
timeoutMs: 2_000,
289+
});
290+
expect(health.ok).toBe(true);
291+
292+
const admin = await callGateway({
293+
url: `ws://127.0.0.1:${started.port}`,
294+
token: "secret",
295+
method: "set-heartbeats",
296+
params: { enabled: false },
297+
scopes: ["operator.admin"],
298+
clientName: GATEWAY_CLIENT_NAMES.CLI,
299+
mode: GATEWAY_CLIENT_MODES.CLI,
300+
timeoutMs: 2_000,
301+
});
302+
expect(admin.ok).toBe(true);
303+
304+
const pending = await devicePairingModule.listDevicePairing();
305+
expect(pending.pending).toHaveLength(0);
306+
await expectReadScopedPairing(identity.deviceId);
307+
} finally {
308+
await closeStartedGateway(started);
309+
}
310+
});
311+
274312
test("keeps local native approval clients off stale paired gateway-client baseline", async () => {
275313
const started = await startServerWithClient("secret");
276314
const identity = await approveReadScopedDevice({

‎src/gateway/server/ws-connection/handshake-auth-helpers.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
resolvePairingLocality,
1414
resolveUnauthorizedHandshakeContext,
1515
shouldAllowSilentLocalPairing,
16+
shouldPreserveLocalCliSharedAuthScopes,
1617
shouldSkipLocalBackendSelfPairing,
1718
} from "./handshake-auth-helpers.js";
1819

@@ -30,6 +31,7 @@ type PairingLocalityOverrides = {
3031
};
3132
type SilentLocalPairingParams = Parameters<typeof shouldAllowSilentLocalPairing>[0];
3233
type BackendSelfPairingParams = Parameters<typeof shouldSkipLocalBackendSelfPairing>[0];
34+
type LocalCliSharedAuthScopeParams = Parameters<typeof shouldPreserveLocalCliSharedAuthScopes>[0];
3335

3436
const CONTROL_UI_WEBCHAT_CONNECT_PARAMS = {
3537
client: {
@@ -132,6 +134,17 @@ function skipBackendSelfPairing(overrides: Partial<BackendSelfPairingParams> = {
132134
});
133135
}
134136

137+
function preserveLocalCliSharedAuthScopes(overrides: Partial<LocalCliSharedAuthScopeParams> = {}) {
138+
return shouldPreserveLocalCliSharedAuthScopes({
139+
connectParams: CLI_CONNECT_PARAMS,
140+
locality: "direct_local",
141+
hasBrowserOriginHeader: false,
142+
sharedAuthOk: true,
143+
authMethod: "token",
144+
...overrides,
145+
});
146+
}
147+
135148
describe("handshake auth helpers", () => {
136149
it("pins browser-origin loopback clients to the synthetic rate-limit ip", () => {
137150
const rateLimiter = createRateLimiter();
@@ -422,6 +435,36 @@ describe("handshake auth helpers", () => {
422435
).toBe(false);
423436
});
424437

438+
it("preserves local CLI shared-auth scopes only for token/password loopback auth", () => {
439+
expect(preserveLocalCliSharedAuthScopes()).toBe(true);
440+
expect(
441+
preserveLocalCliSharedAuthScopes({
442+
locality: "cli_container_local",
443+
authMethod: "password",
444+
}),
445+
).toBe(true);
446+
expect(
447+
preserveLocalCliSharedAuthScopes({
448+
locality: "remote",
449+
}),
450+
).toBe(false);
451+
expect(
452+
preserveLocalCliSharedAuthScopes({
453+
authMethod: "device-token",
454+
}),
455+
).toBe(false);
456+
expect(
457+
preserveLocalCliSharedAuthScopes({
458+
hasBrowserOriginHeader: true,
459+
}),
460+
).toBe(false);
461+
expect(
462+
preserveLocalCliSharedAuthScopes({
463+
connectParams: GATEWAY_BACKEND_CONNECT_PARAMS,
464+
}),
465+
).toBe(false);
466+
});
467+
425468
it("rejects pairing bypass when browser origin header is present", () => {
426469
expect(
427470
skipBackendSelfPairing({

‎src/gateway/server/ws-connection/handshake-auth-helpers.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,24 @@ export function shouldSkipLocalBackendSelfPairing(params: {
283283
return (params.sharedAuthOk && usesSharedSecretAuth) || usesDeviceTokenAuth;
284284
}
285285

286+
export function shouldPreserveLocalCliSharedAuthScopes(params: {
287+
connectParams: ConnectParams;
288+
locality: PairingLocalityKind;
289+
hasBrowserOriginHeader: boolean;
290+
sharedAuthOk: boolean;
291+
authMethod: GatewayAuthResult["method"];
292+
}): boolean {
293+
const isCliClient =
294+
params.connectParams.client.id === GATEWAY_CLIENT_IDS.CLI &&
295+
params.connectParams.client.mode === GATEWAY_CLIENT_MODES.CLI;
296+
if (!isCliClient) {
297+
return false;
298+
}
299+
const isLocal = params.locality === "direct_local" || params.locality === "cli_container_local";
300+
const usesSharedSecretAuth = params.authMethod === "token" || params.authMethod === "password";
301+
return isLocal && !params.hasBrowserOriginHeader && params.sharedAuthOk && usesSharedSecretAuth;
302+
}
303+
286304
function resolveSignatureToken(connectParams: ConnectParams): string | null {
287305
return (
288306
connectParams.auth?.token ??

‎src/gateway/server/ws-connection/message-handler.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,7 @@ import {
169169
resolvePairingLocality,
170170
resolveUnauthorizedHandshakeContext,
171171
shouldAllowSilentLocalPairing,
172+
shouldPreserveLocalCliSharedAuthScopes,
172173
shouldSkipLocalBackendSelfPairing,
173174
} from "./handshake-auth-helpers.js";
174175
import {
@@ -1026,6 +1027,13 @@ export function attachGatewayWsMessageHandler(params: GatewayWsMessageHandlerPar
10261027
sharedAuthOk,
10271028
authMethod,
10281029
});
1030+
let preserveLocalCliSharedAuthScopes = shouldPreserveLocalCliSharedAuthScopes({
1031+
connectParams,
1032+
locality: pairingLocality,
1033+
hasBrowserOriginHeader,
1034+
sharedAuthOk,
1035+
authMethod,
1036+
});
10291037
const handleMissingDeviceIdentity = (): boolean => {
10301038
const trustedProxyAuthOk = isTrustedProxyControlUiOperatorAuth({
10311039
isControlUi,
@@ -1051,13 +1059,13 @@ export function attachGatewayWsMessageHandler(params: GatewayWsMessageHandlerPar
10511059
hasSharedAuth,
10521060
isLocalClient,
10531061
});
1054-
// Shared token/password auth can bypass pairing for trusted operators.
1055-
// Device-less clients still clear self-declared scopes by default, with
1056-
// one narrow exception: the direct-local backend gateway-client shared-
1057-
// auth handoff used for in-process control-plane coordination.
1062+
// Device-less shared auth clears self-declared scopes by default.
1063+
// Only first-party local control paths preserve scopes: backend self-
1064+
// calls and CLI shared-secret calls that already proved loopback auth.
10581065
if (
10591066
!device &&
10601067
!skipLocalBackendSelfPairing &&
1068+
!preserveLocalCliSharedAuthScopes &&
10611069
shouldClearUnboundScopesForMissingDeviceIdentity({
10621070
decision,
10631071
controlUiAuthPolicy,
@@ -1237,6 +1245,13 @@ export function attachGatewayWsMessageHandler(params: GatewayWsMessageHandlerPar
12371245
sharedAuthOk,
12381246
authMethod,
12391247
});
1248+
preserveLocalCliSharedAuthScopes = shouldPreserveLocalCliSharedAuthScopes({
1249+
connectParams,
1250+
locality: pairingLocality,
1251+
hasBrowserOriginHeader,
1252+
sharedAuthOk,
1253+
authMethod,
1254+
});
12401255
if (!authOk) {
12411256
rejectUnauthorized(authResult);
12421257
return;

0 commit comments

Comments
 (0)