Skip to content

Commit 8d1afa5

Browse files
committed
refactor(gateway): consolidate chat abort authorization
1 parent 85fd4c9 commit 8d1afa5

4 files changed

Lines changed: 69 additions & 180 deletions

File tree

‎src/gateway/server-methods/chat-abort-authorization.ts‎

Lines changed: 3 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import { uniqueStrings } from "@openclaw/normalization-core/string-normalization
33
import { normalizeAgentId } from "../../routing/session-key.js";
44
import { parseAgentSessionKey } from "../../sessions/session-key-utils.js";
55
import type { ChatAbortControllerEntry } from "../chat-abort.js";
6-
import type { QueuedChatTurnEntry } from "../chat-queued-turns.js";
76
import { ADMIN_SCOPE } from "../method-scopes.js";
87
import { createChatAbortMarker } from "../server-chat-state.js";
98
import { pendingChatSendDedupeKey } from "../server-shared.js";
@@ -67,36 +66,17 @@ export function resolveChatAbortRequester(
6766
}
6867

6968
export function canRequesterAbortChatRun(
70-
entry: ChatAbortControllerEntry,
71-
requester: ChatAbortRequester,
72-
): boolean {
73-
if (requester.isAdmin) {
74-
return true;
75-
}
76-
const ownerDeviceId = normalizeOptionalText(entry.ownerDeviceId);
77-
const ownerConnId = normalizeOptionalText(entry.ownerConnId);
78-
if (!ownerDeviceId && !ownerConnId) {
79-
return true;
80-
}
81-
if (ownerDeviceId && requester.deviceId && ownerDeviceId === requester.deviceId) {
82-
return true;
83-
}
84-
if (ownerConnId && requester.connId && ownerConnId === requester.connId) {
85-
return true;
86-
}
87-
return false;
88-
}
89-
90-
export function canRequesterAbortChatRunWithoutSessionMatch(
91-
entry: ChatAbortControllerEntry,
69+
entry: Pick<ChatAbortControllerEntry, "ownerDeviceId" | "ownerConnId">,
9270
requester: ChatAbortRequester,
71+
options: { requireOwnerMatch?: boolean } = {},
9372
): boolean {
9473
if (requester.isAdmin) {
9574
return true;
9675
}
9776
const ownerDeviceId = normalizeOptionalText(entry.ownerDeviceId);
9877
const ownerConnId = normalizeOptionalText(entry.ownerConnId);
9978
return Boolean(
79+
(!options.requireOwnerMatch && !ownerDeviceId && !ownerConnId) ||
10080
(ownerDeviceId && requester.deviceId && ownerDeviceId === requester.deviceId) ||
10181
(ownerConnId && requester.connId && ownerConnId === requester.connId),
10282
);
@@ -188,15 +168,8 @@ export function canRequesterAbortPreRegisteredRun(
188168
): boolean {
189169
return canRequesterAbortChatRun(
190170
{
191-
controller: new AbortController(),
192-
sessionId: "",
193-
sessionKey: normalizeUnknownText(payload.sessionKey) ?? "",
194-
startedAtMs: 0,
195-
expiresAtMs: 0,
196171
ownerConnId: normalizeUnknownText(payload.ownerConnId),
197172
ownerDeviceId: normalizeUnknownText(payload.ownerDeviceId),
198-
controlUiVisible: payload.controlUiVisible === false ? false : undefined,
199-
kind: "agent",
200173
},
201174
requester,
202175
);
@@ -439,40 +412,3 @@ export function resolveAuthorizedRunsForSessionKeys(params: {
439412
hasProtectedRuns,
440413
};
441414
}
442-
443-
export function canRequesterAbortQueuedChatTurn(
444-
entry: QueuedChatTurnEntry,
445-
requester: ChatAbortRequester,
446-
): boolean {
447-
// Same ownership rules as active chat runs.
448-
if (requester.isAdmin) {
449-
return true;
450-
}
451-
const ownerDeviceId = normalizeOptionalText(entry.ownerDeviceId);
452-
const ownerConnId = normalizeOptionalText(entry.ownerConnId);
453-
if (!ownerDeviceId && !ownerConnId) {
454-
return true;
455-
}
456-
if (ownerDeviceId && requester.deviceId && ownerDeviceId === requester.deviceId) {
457-
return true;
458-
}
459-
if (ownerConnId && requester.connId && ownerConnId === requester.connId) {
460-
return true;
461-
}
462-
return false;
463-
}
464-
465-
export function canRequesterAbortQueuedChatTurnWithoutSessionMatch(
466-
entry: QueuedChatTurnEntry,
467-
requester: ChatAbortRequester,
468-
): boolean {
469-
if (requester.isAdmin) {
470-
return true;
471-
}
472-
const ownerDeviceId = normalizeOptionalText(entry.ownerDeviceId);
473-
const ownerConnId = normalizeOptionalText(entry.ownerConnId);
474-
return Boolean(
475-
(ownerDeviceId && requester.deviceId && ownerDeviceId === requester.deviceId) ||
476-
(ownerConnId && requester.connId && ownerConnId === requester.connId),
477-
);
478-
}

‎src/gateway/server-methods/chat-abort-handler.ts‎

Lines changed: 57 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,14 @@ import {
77
import { resolveDefaultAgentId } from "../../agents/agent-scope.js";
88
import { normalizeAgentId } from "../../routing/session-key.js";
99
import { parseAgentSessionKey } from "../../sessions/session-key-utils.js";
10-
import { abortChatRunById } from "../chat-abort.js";
11-
import { abortQueuedChatTurnById } from "../chat-queued-turns.js";
10+
import { abortChatRunById, type ChatAbortControllerEntry } from "../chat-abort.js";
11+
import { abortQueuedChatTurnById, type QueuedChatTurnEntry } from "../chat-queued-turns.js";
1212
import { pendingChatSendDedupeKey } from "../server-shared.js";
1313
import { loadSessionEntry, resolveSessionStoreKey } from "../session-utils.js";
1414
import { asWorkerInferenceControl } from "../worker-environments/inference-control.js";
1515
import {
1616
canRequesterAbortChatRun,
17-
canRequesterAbortChatRunWithoutSessionMatch,
1817
canRequesterAbortPreRegisteredRun,
19-
canRequesterAbortQueuedChatTurn,
20-
canRequesterAbortQueuedChatTurnWithoutSessionMatch,
2118
readPreRegisteredAgentDedupePayloadForSession,
2219
resolveChatAbortRequester,
2320
resolveStoredGlobalRunAgentId,
@@ -28,7 +25,6 @@ import {
2825
abortChatRunsForSessionKeyWithPartials,
2926
cancelWorkerInferenceForSession,
3027
createChatAbortOps,
31-
ensureChatQueuedTurns,
3228
persistAbortedPartials,
3329
} from "./chat-abort-runtime.js";
3430
import {
@@ -43,6 +39,11 @@ type ChatAbortLifecycle = {
4339
excludeRunIds?: ReadonlySet<string>;
4440
};
4541

42+
type ChatAbortTarget = Pick<
43+
ChatAbortControllerEntry | QueuedChatTurnEntry,
44+
"sessionKey" | "agentId" | "ownerConnId" | "ownerDeviceId"
45+
>;
46+
4647
export async function handleChatAbortRequestWithLifecycle(
4748
{ params, respond, context, client }: GatewayRequestHandlerOptions,
4849
lifecycle: ChatAbortLifecycle = {},
@@ -130,45 +131,60 @@ export async function handleChatAbortRequestWithLifecycle(
130131
return;
131132
}
132133
const normalizedAgentIdOverride = abortAgentId?.toLowerCase();
134+
const authorizeRunTarget = (target: ChatAbortTarget): boolean => {
135+
if (
136+
target.sessionKey !== rawSessionKey &&
137+
target.sessionKey !== canonicalAbortSessionKey &&
138+
!canRequesterAbortChatRun(target, requester, { requireOwnerMatch: true })
139+
) {
140+
respond(
141+
false,
142+
undefined,
143+
errorShape(ErrorCodes.INVALID_REQUEST, "runId does not match sessionKey"),
144+
);
145+
return false;
146+
}
147+
if (
148+
normalizedAgentIdOverride &&
149+
target.sessionKey === "global" &&
150+
resolveStoredGlobalRunAgentId(target.agentId, defaultAgentId) !== normalizedAgentIdOverride
151+
) {
152+
respond(
153+
false,
154+
undefined,
155+
errorShape(ErrorCodes.INVALID_REQUEST, "runId does not match agentId"),
156+
);
157+
return false;
158+
}
159+
if (!canRequesterAbortChatRun(target, requester)) {
160+
respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, "unauthorized"));
161+
return false;
162+
}
163+
return true;
164+
};
133165

134166
const active = context.chatAbortControllers.get(runId);
135167
if (!active) {
136168
const readPendingRunForAbort = (
137169
entry: GatewayRequestContext["dedupe"] extends Map<string, infer T> ? T | undefined : never,
138170
) => {
139-
const canonicalMatch = readPreRegisteredAgentDedupePayloadForSession({
140-
entry,
141-
runId,
142-
sessionKey: canonicalAbortSessionKey,
143-
agentId: abortAgentId,
144-
defaultAgentId,
145-
includeHidden: true,
146-
});
147-
if (canonicalMatch) {
148-
return {
149-
sessionKey: normalizeUnknownText(canonicalMatch.sessionKey)
150-
? canonicalAbortSessionKey
151-
: undefined,
152-
payload: canonicalMatch,
153-
};
154-
}
155-
if (rawSessionKey === canonicalAbortSessionKey) {
156-
return undefined;
171+
for (const sessionKey of new Set([canonicalAbortSessionKey, rawSessionKey])) {
172+
const payload = readPreRegisteredAgentDedupePayloadForSession({
173+
entry,
174+
runId,
175+
sessionKey,
176+
agentId: abortAgentId,
177+
defaultAgentId,
178+
includeHidden: true,
179+
});
180+
if (payload) {
181+
return {
182+
sessionKey: normalizeUnknownText(payload.sessionKey) ? sessionKey : undefined,
183+
payload,
184+
};
185+
}
157186
}
158-
const aliasMatch = readPreRegisteredAgentDedupePayloadForSession({
159-
entry,
160-
runId,
161-
sessionKey: rawSessionKey,
162-
agentId: abortAgentId,
163-
defaultAgentId,
164-
includeHidden: true,
165-
});
166-
return aliasMatch
167-
? {
168-
sessionKey: normalizeUnknownText(aliasMatch.sessionKey) ? rawSessionKey : undefined,
169-
payload: aliasMatch,
170-
}
171-
: undefined;
187+
return undefined;
172188
};
173189
const pendingChatMatch = readPendingRunForAbort(
174190
context.dedupe.get(pendingChatSendDedupeKey(runId)),
@@ -207,35 +223,10 @@ export async function handleChatAbortRequestWithLifecycle(
207223
}
208224
// Queued followup/collect turns keep a cancel identity after chat.send
209225
// terminalizes; abort them here so Esc cannot report done while they run.
210-
const chatQueuedTurns = ensureChatQueuedTurns(context);
226+
const chatQueuedTurns = context.chatQueuedTurns;
211227
const queued = chatQueuedTurns.get(runId);
212228
if (queued) {
213-
const abortSessionKeysForQueued = new Set([rawSessionKey, canonicalAbortSessionKey]);
214-
if (
215-
!abortSessionKeysForQueued.has(queued.sessionKey) &&
216-
!canRequesterAbortQueuedChatTurnWithoutSessionMatch(queued, requester)
217-
) {
218-
respond(
219-
false,
220-
undefined,
221-
errorShape(ErrorCodes.INVALID_REQUEST, "runId does not match sessionKey"),
222-
);
223-
return;
224-
}
225-
if (
226-
normalizedAgentIdOverride &&
227-
queued.sessionKey === "global" &&
228-
resolveStoredGlobalRunAgentId(queued.agentId, defaultAgentId) !== normalizedAgentIdOverride
229-
) {
230-
respond(
231-
false,
232-
undefined,
233-
errorShape(ErrorCodes.INVALID_REQUEST, "runId does not match agentId"),
234-
);
235-
return;
236-
}
237-
if (!canRequesterAbortQueuedChatTurn(queued, requester)) {
238-
respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, "unauthorized"));
229+
if (!authorizeRunTarget(queued)) {
239230
return;
240231
}
241232
const queuedRes = abortQueuedChatTurnById(chatQueuedTurns, {
@@ -265,32 +256,7 @@ export async function handleChatAbortRequestWithLifecycle(
265256
respondWithWorkerRuns([]);
266257
return;
267258
}
268-
const abortSessionKeysForRun = new Set([rawSessionKey, canonicalAbortSessionKey]);
269-
if (
270-
!abortSessionKeysForRun.has(active.sessionKey) &&
271-
!canRequesterAbortChatRunWithoutSessionMatch(active, requester)
272-
) {
273-
respond(
274-
false,
275-
undefined,
276-
errorShape(ErrorCodes.INVALID_REQUEST, "runId does not match sessionKey"),
277-
);
278-
return;
279-
}
280-
if (
281-
normalizedAgentIdOverride &&
282-
active.sessionKey === "global" &&
283-
resolveStoredGlobalRunAgentId(active.agentId, defaultAgentId) !== normalizedAgentIdOverride
284-
) {
285-
respond(
286-
false,
287-
undefined,
288-
errorShape(ErrorCodes.INVALID_REQUEST, "runId does not match agentId"),
289-
);
290-
return;
291-
}
292-
if (!canRequesterAbortChatRun(active, requester)) {
293-
respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, "unauthorized"));
259+
if (!authorizeRunTarget(active)) {
294260
return;
295261
}
296262

‎src/gateway/server-methods/chat-abort-runtime.ts‎

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,13 @@ import {
33
type ChatAbortControllerEntry,
44
type ChatAbortOps,
55
} from "../chat-abort.js";
6-
import {
7-
abortQueuedChatTurns,
8-
listQueuedChatTurnsForSession,
9-
type QueuedChatTurnMap,
10-
} from "../chat-queued-turns.js";
6+
import { abortQueuedChatTurns, listQueuedChatTurnsForSession } from "../chat-queued-turns.js";
117
import { PENDING_CHAT_SEND_DEDUPE_PREFIX } from "../server-shared.js";
128
// Cancellation orchestration across active, queued, pending, and worker runs.
139
import { loadSessionEntry } from "../session-utils.js";
1410
import { asWorkerInferenceControl } from "../worker-environments/inference-control.js";
1511
import {
16-
canRequesterAbortQueuedChatTurn,
12+
canRequesterAbortChatRun,
1713
resolveAuthorizedPreRegisteredRunsForSessionKeys,
1814
resolveAuthorizedRunsForSessionKeys,
1915
writePreRegisteredAgentAbort,
@@ -114,10 +110,6 @@ export function createChatAbortOps(context: GatewayRequestContext): ChatAbortOps
114110
};
115111
}
116112

117-
export function ensureChatQueuedTurns(context: GatewayRequestContext): QueuedChatTurnMap {
118-
return context.chatQueuedTurns;
119-
}
120-
121113
function resolveAuthorizedQueuedTurnsForSession(params: {
122114
context: GatewayRequestContext;
123115
sessionKeys: string[];
@@ -126,19 +118,15 @@ function resolveAuthorizedQueuedTurnsForSession(params: {
126118
defaultAgentId: string;
127119
requester: ChatAbortRequester;
128120
}) {
129-
const chatQueuedTurns = ensureChatQueuedTurns(params.context);
130121
const matches = listQueuedChatTurnsForSession({
131-
chatQueuedTurns,
122+
chatQueuedTurns: params.context.chatQueuedTurns,
132123
sessionKeys: params.sessionKeys,
133124
sessionIds: [params.sessionId],
134125
agentId: params.agentId,
135126
defaultAgentId: params.defaultAgentId,
136127
});
137-
if (matches.length === 0) {
138-
return { authorized: [], hasUnauthorizedRuns: false };
139-
}
140-
const authorized = matches.filter((m) =>
141-
canRequesterAbortQueuedChatTurn(m.entry, params.requester),
128+
const authorized = matches.filter((match) =>
129+
canRequesterAbortChatRun(match.entry, params.requester),
142130
);
143131
return {
144132
authorized,
@@ -310,7 +298,7 @@ export async function abortChatRunsForSessionKeyWithPartials(params: {
310298
// Abort queued owners before any active-work signal can promote a successor.
311299
// Keep them first in the response to preserve the established runIds ordering.
312300
const runIds: string[] = abortQueuedChatTurns(
313-
ensureChatQueuedTurns(params.context),
301+
params.context.chatQueuedTurns,
314302
queuedPlan.authorized,
315303
params.stopReason,
316304
);

0 commit comments

Comments
 (0)