Skip to content

Commit 3a98716

Browse files
committed
fix(gateway): evict revoked CLI grant tools
1 parent 0833b88 commit 3a98716

7 files changed

Lines changed: 215 additions & 17 deletions

File tree

‎src/gateway/mcp-grant-store.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
deactivateMcpLoopbackClientGrantCapture,
55
mintAttachGrant,
66
mintMcpLoopbackClientGrant,
7+
registerMcpLoopbackClientGrantRevocationListener,
78
resolveAttachGrant,
89
resolveMcpLoopbackClientGrant,
910
revokeAttachGrant,
@@ -205,6 +206,40 @@ describe("mcp-grant-store", () => {
205206
expect(revokeMcpLoopbackClientGrant(successor.token)).toBe(false);
206207
});
207208

209+
it("notifies revocation listeners for single and runtime-wide cleanup", () => {
210+
const events: Array<{ token: string; runtimeOwnerToken: string }> = [];
211+
const unregister = registerMcpLoopbackClientGrantRevocationListener((event) => {
212+
events.push(event);
213+
});
214+
try {
215+
const first = mintMcpLoopbackClientGrant({
216+
context: { sessionKey: "agent:main:first", senderIsOwner: false },
217+
runtimeOwnerToken: "runtime-one",
218+
});
219+
const second = mintMcpLoopbackClientGrant({
220+
context: { sessionKey: "agent:main:second", senderIsOwner: false },
221+
runtimeOwnerToken: "runtime-one",
222+
});
223+
224+
expect(revokeMcpLoopbackClientGrant(first.token)).toBe(true);
225+
expect(revokeMcpLoopbackClientGrant(first.token)).toBe(false);
226+
expect(revokeMcpLoopbackClientGrantsForRuntime("runtime-one")).toBe(1);
227+
expect(events).toEqual([
228+
{ token: first.token, runtimeOwnerToken: "runtime-one" },
229+
{ token: second.token, runtimeOwnerToken: "runtime-one" },
230+
]);
231+
} finally {
232+
unregister();
233+
}
234+
235+
const afterUnregister = mintMcpLoopbackClientGrant({
236+
context: { sessionKey: "agent:main:later", senderIsOwner: false },
237+
runtimeOwnerToken: "runtime-one",
238+
});
239+
expect(revokeMcpLoopbackClientGrant(afterUnregister.token)).toBe(true);
240+
expect(events).toHaveLength(2);
241+
});
242+
208243
it("requires a session key for loopback client grants", () => {
209244
expect(() =>
210245
mintMcpLoopbackClientGrant({

‎src/gateway/mcp-grant-store.ts‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ interface McpLoopbackClientGrant {
8080
readonly context: McpLoopbackRequestContext;
8181
}
8282

83-
export type McpLoopbackToolAuth = {
83+
type McpLoopbackToolAuth = {
8484
agentDir?: string;
8585
store: AuthProfileStore;
8686
};
@@ -91,6 +91,13 @@ type StoredMcpLoopbackClientGrant = McpLoopbackClientGrant & {
9191
toolAuth?: McpLoopbackToolAuth;
9292
};
9393

94+
type McpLoopbackClientGrantRevocation = {
95+
token: string;
96+
runtimeOwnerToken: string;
97+
};
98+
99+
const clientGrantRevocationListeners = new Set<(event: McpLoopbackClientGrantRevocation) => void>();
100+
94101
const DEFAULT_TTL_MS = 60 * 60 * 1000; // 1h
95102
const MAX_TTL_MS = 12 * 60 * 60 * 1000;
96103

@@ -267,16 +274,32 @@ export function resolveMcpLoopbackClientGrant(params: {
267274
};
268275
}
269276

277+
/** Registers cleanup tied to the exact lifetime of loopback client grants. */
278+
export function registerMcpLoopbackClientGrantRevocationListener(
279+
listener: (event: McpLoopbackClientGrantRevocation) => void,
280+
): () => void {
281+
clientGrantRevocationListeners.add(listener);
282+
return () => clientGrantRevocationListeners.delete(listener);
283+
}
284+
270285
export function revokeMcpLoopbackClientGrant(token: string): boolean {
271-
return clientGrantsByToken.delete(token);
286+
const grant = clientGrantsByToken.get(token);
287+
if (!grant || !clientGrantsByToken.delete(token)) {
288+
return false;
289+
}
290+
// Revocation must also release server-owned projections whose closures retain
291+
// this grant's prepared credentials.
292+
for (const listener of clientGrantRevocationListeners) {
293+
listener({ token, runtimeOwnerToken: grant.runtimeOwnerToken });
294+
}
295+
return true;
272296
}
273297

274298
export function revokeMcpLoopbackClientGrantsForRuntime(runtimeOwnerToken: string): number {
275299
let removed = 0;
276300
for (const [token, grant] of clientGrantsByToken) {
277301
if (grant.runtimeOwnerToken === runtimeOwnerToken) {
278-
clientGrantsByToken.delete(token);
279-
removed += 1;
302+
removed += revokeMcpLoopbackClientGrant(token) ? 1 : 0;
280303
}
281304
}
282305
return removed;

‎src/gateway/mcp-http.request.ts‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ import {
1818
resolveAttachGrant,
1919
resolveMcpLoopbackClientGrant,
2020
type McpLoopbackRequestContext,
21-
type McpLoopbackToolAuth,
2221
} from "./mcp-grant-store.js";
2322
import { isLoopbackAddress } from "./net.js";
2423
import { checkBrowserOrigin } from "./origin-check.js";
@@ -66,7 +65,6 @@ type McpLoopbackRequestAuth = {
6665
boundContext?: McpLoopbackRequestContext;
6766
boundCaptureKey?: string;
6867
boundGrantToken?: string;
69-
boundToolAuth?: McpLoopbackToolAuth;
7068
};
7169

7270
function resolveScopedSessionKey(cfg: OpenClawConfig, rawSessionKey: string | undefined): string {
@@ -147,7 +145,6 @@ function resolveMcpSender(params: {
147145
boundContext: clientGrant.context,
148146
boundCaptureKey: clientGrant.captureKey,
149147
boundGrantToken: grantToken,
150-
boundToolAuth: clientGrant.toolAuth,
151148
};
152149
}
153150
const grant = grantToken ? resolveAttachGrant(grantToken) : undefined;
@@ -285,7 +282,6 @@ export function validateMcpLoopbackRequest(params: {
285282
boundContext: sender.boundContext,
286283
boundCaptureKey: sender.boundCaptureKey,
287284
boundGrantToken: sender.boundGrantToken,
288-
boundToolAuth: sender.boundToolAuth,
289285
};
290286
}
291287

‎src/gateway/mcp-http.runtime.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,42 @@ describe("McpLoopbackToolCache", () => {
201201
expect(resolveGatewayScopedTools).toHaveBeenCalledTimes(3);
202202
});
203203

204+
it("evicts only the revoked grant's cached tool closures", () => {
205+
const cache = new McpLoopbackToolCache();
206+
const cfg = {} as OpenClawConfig;
207+
208+
cache.resolve(scopeParams({ cfg, grantToken: "grant-a" }));
209+
cache.resolve(scopeParams({ cfg, grantToken: "grant-b" }));
210+
cache.resolve(scopeParams({ cfg, grantToken: "grant-a" }));
211+
cache.resolve(scopeParams({ cfg, grantToken: "grant-b" }));
212+
expect(resolveGatewayScopedTools).toHaveBeenCalledTimes(2);
213+
214+
expect(cache.evictGrant("grant-a")).toBe(true);
215+
cache.resolve(scopeParams({ cfg, grantToken: "grant-a" }));
216+
cache.resolve(scopeParams({ cfg, grantToken: "grant-b" }));
217+
218+
expect(resolveGatewayScopedTools).toHaveBeenCalledTimes(3);
219+
});
220+
221+
it("preserves the global 256-entry cache cap across grants", () => {
222+
const cache = new McpLoopbackToolCache();
223+
const cfg = {} as OpenClawConfig;
224+
225+
for (let index = 0; index < 256; index += 1) {
226+
cache.resolve(
227+
scopeParams({ cfg, grantToken: "grant-a", currentMessageId: `message-${index}` }),
228+
);
229+
}
230+
cache.resolve(scopeParams({ cfg, grantToken: "grant-b", currentMessageId: "message-b" }));
231+
expect(resolveGatewayScopedTools).toHaveBeenCalledTimes(257);
232+
233+
cache.resolve(scopeParams({ cfg, grantToken: "grant-a", currentMessageId: "message-0" }));
234+
expect(resolveGatewayScopedTools).toHaveBeenCalledTimes(258);
235+
236+
cache.resolve(scopeParams({ cfg, grantToken: "grant-b", currentMessageId: "message-b" }));
237+
expect(resolveGatewayScopedTools).toHaveBeenCalledTimes(258);
238+
});
239+
204240
it("never reuses ordinary private-mode tools for a source-reply-only grant", () => {
205241
const cache = new McpLoopbackToolCache();
206242
const cfg = {} as OpenClawConfig;

‎src/gateway/mcp-http.runtime.ts‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ type McpLoopbackScopeParams = Omit<McpLoopbackRequestContext, "senderIsOwner"> &
3636
cfg: OpenClawConfig;
3737
authProfileStore?: AuthProfileStore;
3838
authProfileStoreAgentDir?: string;
39-
authProfileStoreCacheKey?: string;
39+
grantToken?: string;
4040
senderIsOwner: boolean | undefined;
4141
yieldContextCacheKey?: string;
4242
onYield?: (message: string) => Promise<void> | void;
@@ -91,7 +91,7 @@ function resolveMcpLoopbackTools(
9191
const {
9292
toolsAllow: _toolsAllow,
9393
authProfileStoreAgentDir,
94-
authProfileStoreCacheKey: _authProfileStoreCacheKey,
94+
grantToken: _grantToken,
9595
...scopeParams
9696
} = params;
9797
const scoped = resolveGatewayScopedTools({
@@ -171,11 +171,14 @@ function applyPolicyToolsAllow(
171171
/** Short-lived cache for loopback tool lists keyed by session/channel context. */
172172
export class McpLoopbackToolCache {
173173
#entries = new DirectoryCache<CachedScopedTools>(TOOL_CACHE_TTL_MS, TOOL_CACHE_MAX_ENTRIES);
174+
// Revocation needs the config scopes where one grant may have cached tools.
175+
#grantConfigScopes = new Map<string, Set<OpenClawConfig>>();
174176

175177
resolve(params: McpLoopbackScopeParams): CachedScopedTools {
176178
// Callers differing only in capabilities must not share cached tool lists.
177179
const clientCapsCacheKey = [...new Set(params.clientCaps ?? [])].toSorted().join(",");
178180
const cacheKey = [
181+
params.grantToken ?? "",
179182
params.sessionKey,
180183
params.runtimePolicySessionKey ?? "",
181184
params.agentId ?? "",
@@ -185,7 +188,6 @@ export class McpLoopbackToolCache {
185188
params.cwd ?? "",
186189
params.modelProvider ?? "",
187190
params.modelId ?? "",
188-
params.authProfileStoreCacheKey ?? "",
189191
params.yieldContextCacheKey ?? "",
190192
params.messageProvider ?? "",
191193
clientCapsCacheKey,
@@ -252,6 +254,29 @@ export class McpLoopbackToolCache {
252254
toolSchema: buildMcpToolSchema(next.tools),
253255
};
254256
this.#entries.set(cacheKey, nextEntry, params.cfg);
257+
if (params.grantToken) {
258+
const scopes = this.#grantConfigScopes.get(params.grantToken) ?? new Set<OpenClawConfig>();
259+
scopes.add(params.cfg);
260+
this.#grantConfigScopes.set(params.grantToken, scopes);
261+
}
255262
return nextEntry;
256263
}
264+
265+
evictGrant(token: string): boolean {
266+
const scopes = this.#grantConfigScopes.get(token);
267+
if (!scopes) {
268+
return false;
269+
}
270+
const cacheKeyPrefix = `${token}\u0000`;
271+
for (const cfg of scopes) {
272+
this.#entries.clearMatching((cacheKey) => cacheKey.startsWith(cacheKeyPrefix), cfg);
273+
}
274+
this.#grantConfigScopes.delete(token);
275+
return true;
276+
}
277+
278+
clear(): void {
279+
this.#entries.clear();
280+
this.#grantConfigScopes.clear();
281+
}
257282
}

‎src/gateway/mcp-http.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1481,6 +1481,68 @@ describe("mcp loopback server", () => {
14811481
).toBe(401);
14821482
});
14831483

1484+
it("rejects a slow tools request revoked after header admission", async () => {
1485+
const captureKey = "slow-revoked-grant";
1486+
let resolveRequestStarted: (() => void) | undefined;
1487+
const requestStarted = new Promise<void>((resolve) => {
1488+
resolveRequestStarted = resolve;
1489+
});
1490+
beginMcpLoopbackToolCallCapture({
1491+
captureKey,
1492+
onRequestStart: () => resolveRequestStarted?.(),
1493+
onRequestClassified: vi.fn(),
1494+
onToolCallResult: vi.fn(),
1495+
});
1496+
const { runtime, port } = await startLoopbackServerForTest();
1497+
const grant = mintMcpLoopbackClientGrant({
1498+
context: { sessionKey: "agent:main:slow-revoked", senderIsOwner: true },
1499+
runtimeOwnerToken: runtime.ownerToken,
1500+
toolAuth: { store: { version: 1, profiles: {} } },
1501+
});
1502+
expect(
1503+
activateMcpLoopbackClientGrantCapture({
1504+
token: grant.token,
1505+
runtimeOwnerToken: runtime.ownerToken,
1506+
captureKey,
1507+
}),
1508+
).toBe(true);
1509+
1510+
let revoked = false;
1511+
const responsePromise = new Promise<{ status: number | undefined }>((resolve, reject) => {
1512+
const req = request(
1513+
{
1514+
hostname: "127.0.0.1",
1515+
port,
1516+
path: "/mcp",
1517+
method: "POST",
1518+
headers: {
1519+
authorization: `Bearer ${grant.token}`,
1520+
"content-type": "application/json",
1521+
"transfer-encoding": "chunked",
1522+
"x-openclaw-cli-capture-key": captureKey,
1523+
},
1524+
},
1525+
(res) => {
1526+
res.resume();
1527+
res.on("end", () => resolve({ status: res.statusCode }));
1528+
},
1529+
);
1530+
req.on("error", reject);
1531+
req.flushHeaders();
1532+
void requestStarted.then(() => {
1533+
revoked = revokeMcpLoopbackClientGrant(grant.token);
1534+
req.end(mcpToolsListBody());
1535+
});
1536+
});
1537+
1538+
await requestStarted;
1539+
const resolverCallsBeforeBody = resolveGatewayScopedToolsMock.mock.calls.length;
1540+
await expect(responsePromise).resolves.toEqual({ status: 401 });
1541+
expect(revoked).toBe(true);
1542+
expect(resolveGatewayScopedToolsMock).toHaveBeenCalledTimes(resolverCallsBeforeBody);
1543+
clearMcpLoopbackToolCallCapture(captureKey);
1544+
});
1545+
14841546
it("routes sessions_yield to the current CLI capture", async () => {
14851547
resolveGatewayScopedToolsMock.mockImplementation((input): MockGatewayScopedTools => {
14861548
const call = input as ScopedToolsCall;

‎src/gateway/mcp-http.ts‎

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
isAgentHarnessSessionStoreEntryProtected,
2121
} from "../sessions/agent-harness-session-key.js";
2222
import {
23+
registerMcpLoopbackClientGrantRevocationListener,
2324
resolveMcpLoopbackClientGrant,
2425
revokeMcpLoopbackClientGrantsForRuntime,
2526
} from "./mcp-grant-store.js";
@@ -247,9 +248,22 @@ async function startMcpLoopbackServer(port = 0): Promise<{
247248
});
248249
});
249250
markMcpLoopbackRequestClassified(cliRequestCaptureHandle);
251+
const { boundGrantToken, boundCaptureKey } = auth;
252+
const activeBoundGrant =
253+
boundGrantToken && boundCaptureKey
254+
? resolveMcpLoopbackClientGrant({
255+
token: boundGrantToken,
256+
runtimeOwnerToken: ownerToken,
257+
captureKey: boundCaptureKey,
258+
})
259+
: undefined;
260+
if (boundGrantToken && !activeBoundGrant) {
261+
res.writeHead(401, { "Content-Type": "application/json" });
262+
res.end(JSON.stringify({ error: "unauthorized" }));
263+
return;
264+
}
250265
const cfg = getRuntimeConfig();
251266
const requestContext = resolveMcpRequestContext(req, cfg, auth);
252-
const { boundGrantToken, boundCaptureKey } = auth;
253267
const authorizeToolCall =
254268
boundGrantToken && boundCaptureKey
255269
? () =>
@@ -300,15 +314,15 @@ async function startMcpLoopbackServer(port = 0): Promise<{
300314
cwd: requestContext.cwd,
301315
modelProvider: requestContext.modelProvider,
302316
modelId: requestContext.modelId,
303-
...(auth.boundToolAuth
317+
...(activeBoundGrant?.toolAuth
304318
? {
305-
authProfileStore: auth.boundToolAuth.store,
306-
...(auth.boundToolAuth.agentDir
307-
? { authProfileStoreAgentDir: auth.boundToolAuth.agentDir }
319+
authProfileStore: activeBoundGrant.toolAuth.store,
320+
...(activeBoundGrant.toolAuth.agentDir
321+
? { authProfileStoreAgentDir: activeBoundGrant.toolAuth.agentDir }
308322
: {}),
309-
...(boundGrantToken ? { authProfileStoreCacheKey: boundGrantToken } : {}),
310323
}
311324
: {}),
325+
...(boundGrantToken ? { grantToken: boundGrantToken } : {}),
312326
yieldContextCacheKey: yieldContext?.cacheKey,
313327
onYield: yieldContext?.onYield,
314328
messageProvider: requestContext.messageProvider,
@@ -485,6 +499,11 @@ async function startMcpLoopbackServer(port = 0): Promise<{
485499
if (!address || typeof address === "string") {
486500
throw new Error("mcp loopback did not bind to a TCP port");
487501
}
502+
const unregisterGrantRevocation = registerMcpLoopbackClientGrantRevocationListener((event) => {
503+
if (event.runtimeOwnerToken === ownerToken) {
504+
toolCache.evictGrant(event.token);
505+
}
506+
});
488507
// Register tokens only after the TCP listener is live so clients never learn
489508
// a bearer token for a server that failed to bind.
490509
setActiveMcpLoopbackRuntime({ port: address.port, ownerToken, nonOwnerToken });
@@ -497,6 +516,8 @@ async function startMcpLoopbackServer(port = 0): Promise<{
497516
// requests. A delayed old-server close cannot revoke a successor runtime.
498517
clearActiveMcpLoopbackRuntimeByOwnerToken(ownerToken);
499518
revokeMcpLoopbackClientGrantsForRuntime(ownerToken);
519+
unregisterGrantRevocation();
520+
toolCache.clear();
500521
return new Promise<void>((resolve, reject) => {
501522
httpServer.close((error) => {
502523
if (!error) {

0 commit comments

Comments
 (0)