Skip to content

Commit fb137a7

Browse files
author
Cad from Arca
committed
fix(gateway): revoke attach grants on deletion
1 parent 1b281de commit fb137a7

10 files changed

Lines changed: 316 additions & 11 deletions

‎src/config/sessions/session-accessor.sqlite.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1022,7 +1022,10 @@ async function deleteSqliteSessionEntryLifecycleInternal(
10221022
kind: "delete",
10231023
previous: {
10241024
...(current.entry.sessionId ? { sessionId: current.entry.sessionId } : {}),
1025-
sessionKeys: targetSnapshot.rows.map((row) => row.sessionKey),
1025+
sessionKeys: uniqueStrings([
1026+
normalizeSqliteSessionKey(params.target.canonicalKey),
1027+
...targetSnapshot.rows.map((row) => row.sessionKey),
1028+
]),
10261029
},
10271030
});
10281031
}

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { beforeEach, describe, expect, it } from "vitest";
2+
import { emitSessionIdentityMutation } from "../sessions/session-lifecycle-events.js";
23
import {
34
activateMcpLoopbackClientGrantCapture,
45
attachGrantStoreSize,
@@ -73,6 +74,34 @@ describe("mcp-grant-store", () => {
7374
expect(attachGrantStoreSize()).toBe(1);
7475
});
7576

77+
it("revokes only grants bound to a committed session deletion", () => {
78+
const target = mintAttachGrant({ sessionKey: "agent:main:target", nowMs: T0 });
79+
const unrelated = mintAttachGrant({ sessionKey: "agent:main:unrelated", nowMs: T0 });
80+
81+
emitSessionIdentityMutation({
82+
kind: "delete",
83+
previous: {
84+
sessionId: "target-session-id",
85+
sessionKeys: ["agent:main:target"],
86+
},
87+
});
88+
89+
expect(resolveAttachGrant(target.token, T0)).toBeUndefined();
90+
expect(resolveAttachGrant(unrelated.token, T0)).toBeDefined();
91+
});
92+
93+
it("preserves grants when session identity is reset instead of deleted", () => {
94+
const target = mintAttachGrant({ sessionKey: "agent:main:target", nowMs: T0 });
95+
96+
emitSessionIdentityMutation({
97+
kind: "reset",
98+
previous: { sessionId: "old-session-id", sessionKeys: ["agent:main:target"] },
99+
current: { sessionId: "new-session-id", sessionKeys: ["agent:main:target"] },
100+
});
101+
102+
expect(resolveAttachGrant(target.token, T0)).toBeDefined();
103+
});
104+
76105
it("clamps TTL: default for non-positive, ceiling at 12h", () => {
77106
const def = mintAttachGrant({ sessionKey: "s", nowMs: T0 });
78107
expect(def.expiresAtMs).toBe(T0 + 60 * 60 * 1000);

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import type {
77
} from "../auto-reply/get-reply-options.types.js";
88
import type { InboundEventKind } from "../channels/inbound-event/kind.js";
99
import type { PluginHookChannelContext } from "../plugins/hook-types.js";
10+
import { normalizeAgentId, parseAgentSessionKey } from "../routing/session-key.js";
11+
import { onSessionIdentityMutation } from "../sessions/session-lifecycle-events.js";
1012

1113
export type McpLoopbackRequestContext = {
1214
sessionKey: string;
@@ -73,6 +75,22 @@ const MAX_TTL_MS = 12 * 60 * 60 * 1000;
7375

7476
const grantsByToken = new Map<string, McpAttachGrant>();
7577
const clientGrantsByToken = new Map<string, StoredMcpLoopbackClientGrant>();
78+
let sessionDeletionObserverStarted = false;
79+
80+
function ensureSessionDeletionObserver(): void {
81+
if (sessionDeletionObserverStarted) {
82+
return;
83+
}
84+
sessionDeletionObserverStarted = true;
85+
onSessionIdentityMutation((mutation) => {
86+
if (mutation.kind !== "delete") {
87+
return;
88+
}
89+
for (const sessionKey of mutation.previous.sessionKeys) {
90+
revokeAttachGrantsForSession(sessionKey);
91+
}
92+
});
93+
}
7694

7795
function clampTtlMs(ttlMs: number | undefined): number {
7896
if (!Number.isFinite(ttlMs) || (ttlMs as number) <= 0) {
@@ -91,6 +109,7 @@ export function mintAttachGrant(params: {
91109
throw new Error("mintAttachGrant: sessionKey is required");
92110
}
93111
const nowMs = params.nowMs ?? Date.now();
112+
ensureSessionDeletionObserver();
94113
// Mint sweeps stale entries so abandoned grants do not accumulate.
95114
sweepExpiredAttachGrants(nowMs);
96115
const grant: McpAttachGrant = {
@@ -134,6 +153,18 @@ export function revokeAttachGrantsForSession(sessionKey: string): number {
134153
return removed;
135154
}
136155

156+
export function revokeAttachGrantsForAgent(agentId: string): number {
157+
const normalizedAgentId = normalizeAgentId(agentId);
158+
let removed = 0;
159+
for (const [token, grant] of grantsByToken) {
160+
if (parseAgentSessionKey(grant.sessionKey)?.agentId === normalizedAgentId) {
161+
grantsByToken.delete(token);
162+
removed += 1;
163+
}
164+
}
165+
return removed;
166+
}
167+
137168
export function sweepExpiredAttachGrants(nowMs: number = Date.now()): number {
138169
let removed = 0;
139170
for (const [token, grant] of grantsByToken) {

‎src/gateway/server-methods/agents-mutate.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@
44
import { expectDefined } from "@openclaw/normalization-core";
55
import { describe, expect, it, vi, beforeEach } from "vitest";
66
import { FsSafeError } from "../../infra/fs-safe.js";
7+
import {
8+
mintAttachGrant,
9+
resetAttachGrantsForTest,
10+
resolveAttachGrant,
11+
} from "../mcp-grant-store.js";
712
/* ------------------------------------------------------------------ */
813
/* Mocks */
914
/* ------------------------------------------------------------------ */
@@ -207,6 +212,7 @@ const { testing: agentsTesting, agentsHandlers } = await import("./agents.js");
207212
/* ------------------------------------------------------------------ */
208213

209214
beforeEach(() => {
215+
resetAttachGrantsForTest();
210216
agentsTesting.resetDepsForTests();
211217
mocks.listAgentEntries.mockImplementation((cfg: unknown) => getAgentList(cfg));
212218
mocks.findAgentEntryIndex.mockImplementation((list: unknown, agentId?: string) =>
@@ -1129,6 +1135,17 @@ describe("agents.delete", () => {
11291135
expect(mocks.movePathToTrash).toHaveBeenCalled();
11301136
});
11311137

1138+
it("revokes only attach grants owned by the deleted agent", async () => {
1139+
const deletedAgentGrant = mintAttachGrant({ sessionKey: "agent:test-agent:work" });
1140+
const unrelatedGrant = mintAttachGrant({ sessionKey: "agent:other:work" });
1141+
1142+
const { promise } = makeCall("agents.delete", { agentId: "test-agent", deleteFiles: false });
1143+
await promise;
1144+
1145+
expect(resolveAttachGrant(deletedAgentGrant.token)).toBeUndefined();
1146+
expect(resolveAttachGrant(unrelatedGrant.token)).toBeDefined();
1147+
});
1148+
11321149
it("trashes workspace attestations when deleting the last workspace owner", async () => {
11331150
const { respond, promise } = makeCall("agents.delete", {
11341151
agentId: "test-agent",

‎src/gateway/server-methods/agents.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import { root, FsSafeError, type ReadResult } from "../../infra/fs-safe.js";
4848
import { movePathToTrash } from "../../plugin-sdk/browser-maintenance.js";
4949
import { DEFAULT_AGENT_ID, normalizeAgentId } from "../../routing/session-key.js";
5050
import { resolveUserPath } from "../../utils.js";
51+
import { revokeAttachGrantsForAgent } from "../mcp-grant-store.js";
5152
import { listAgentsForGateway } from "../session-utils.js";
5253
import {
5354
AgentConfigPreconditionError,
@@ -734,6 +735,8 @@ export const agentsHandlers: GatewayRequestHandlers = {
734735
return;
735736
}
736737

738+
revokeAttachGrantsForAgent(agentId);
739+
737740
// Purge session store entries so orphaned sessions cannot be targeted (#65524).
738741
await purgeAgentSessionStoreEntries(cfg, agentId);
739742

‎src/gateway/server-methods/attach.test.ts‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ import { attachHandlers } from "./attach.js";
66
import type { GatewayRequestHandlerOptions } from "./types.js";
77

88
const loadSessionEntryMock = vi.hoisted(() =>
9-
vi.fn((_sessionKey: string) => ({ entry: undefined as Record<string, unknown> | undefined })),
9+
vi.fn((sessionKey: string) => ({
10+
canonicalKey: sessionKey,
11+
entry: undefined as Record<string, unknown> | undefined,
12+
})),
1013
);
1114

1215
vi.mock("../../config/sessions/session-accessor.js", async (importOriginal) => {
@@ -29,7 +32,10 @@ describe("attach gateway methods", () => {
2932
beforeEach(() => {
3033
resetAttachGrantsForTest();
3134
loadSessionEntryMock.mockReset();
32-
loadSessionEntryMock.mockReturnValue({ entry: undefined });
35+
loadSessionEntryMock.mockImplementation((sessionKey: string) => ({
36+
canonicalKey: sessionKey,
37+
entry: undefined,
38+
}));
3339
});
3440
afterEach(async () => {
3541
resetAttachGrantsForTest();
@@ -64,6 +70,23 @@ describe("attach gateway methods", () => {
6470
expect(resolveAttachGrant(body.token)?.sessionKey).toBe("agent:main:attach-method");
6571
});
6672

73+
it("attach.grant binds aliases to the canonical logical session key", async () => {
74+
loadSessionEntryMock.mockReturnValue({
75+
canonicalKey: "agent:main:discord:group:attach",
76+
entry: { sessionId: "alias-session" },
77+
});
78+
const respond = vi.fn();
79+
80+
await expectDefined(
81+
attachHandlers["attach.grant"],
82+
'attachHandlers["attach.grant"] test invariant',
83+
)(grantOpts("discord:group:attach", respond));
84+
85+
const body = respond.mock.calls[0]?.[1] as { sessionKey: string; token: string };
86+
expect(body.sessionKey).toBe("agent:main:discord:group:attach");
87+
expect(resolveAttachGrant(body.token)?.sessionKey).toBe(body.sessionKey);
88+
});
89+
6790
it("rejects attach grants for reserved harness sessions", async () => {
6891
const respond = vi.fn();
6992
await expectDefined(
@@ -82,6 +105,7 @@ describe("attach gateway methods", () => {
82105

83106
it("allows an existing unlocked legacy harness-prefixed session", async () => {
84107
loadSessionEntryMock.mockReturnValue({
108+
canonicalKey: "agent:main:harness:legacy-notes",
85109
entry: { sessionId: "legacy-session", modelSelectionLocked: false },
86110
});
87111
const respond = vi.fn();
@@ -101,6 +125,7 @@ describe("attach gateway methods", () => {
101125

102126
it("rejects attach grants for existing locked harness sessions", async () => {
103127
loadSessionEntryMock.mockReturnValue({
128+
canonicalKey: "agent:main:harness:codex:supervision:native-thread",
104129
entry: {
105130
sessionId: "locked-session",
106131
agentHarnessId: "codex",

‎src/gateway/server-methods/attach.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,10 @@ export const attachHandlers: GatewayRequestHandlers = {
3232
"attach.grant": async ({ params, respond, context }) => {
3333
const grantParams = paramRecord(params);
3434
const cfg = context.getRuntimeConfig();
35-
const sessionKey = readString(grantParams, "sessionKey") ?? resolveMainSessionKey(cfg);
36-
const harnessEntry = isAgentHarnessSessionKey(sessionKey)
37-
? resolveSessionEntryAccessTarget({ cfg, sessionKey }).entry
38-
: undefined;
35+
const requestedSessionKey = readString(grantParams, "sessionKey") ?? resolveMainSessionKey(cfg);
36+
const sessionTarget = resolveSessionEntryAccessTarget({ cfg, sessionKey: requestedSessionKey });
37+
const sessionKey = sessionTarget.canonicalKey;
38+
const harnessEntry = isAgentHarnessSessionKey(sessionKey) ? sessionTarget.entry : undefined;
3939
if (
4040
isAgentHarnessSessionKey(sessionKey) &&
4141
(!harnessEntry || isAgentHarnessSessionStoreEntryProtected(sessionKey, harnessEntry))

0 commit comments

Comments
 (0)