Skip to content

Commit f9a2b20

Browse files
committed
fix(steering): require matching tool authority for /steer injection
The authorized-sender command gate is weaker than tool-authority equality. Make /steer and gateway injection present the same projected evidence as channel steering so mismatches fall back to a normal prompt under the sender’s own authority.
1 parent 0c71b12 commit f9a2b20

6 files changed

Lines changed: 171 additions & 65 deletions

File tree

‎src/auto-reply/reply/commands-steer.test.ts‎

Lines changed: 91 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
// Tests /steer target capture, accepted delivery, and visible fallback.
22
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3+
import type { ChatType } from "../../channels/chat-type.js";
34
import type { OpenClawConfig } from "../../config/types.openclaw.js";
45
import { buildCommandTestParams } from "./commands.test-harness.js";
56
import type { ReplyBackendQueueMessageOptions, ReplyOperation } from "./reply-run-registry.js";
67
import { createReplyOperation } from "./reply-run-registry.js";
8+
import {
9+
createFollowupRunToolAuthorityProjector,
10+
resolveFollowupRunToolAuthorityFingerprint,
11+
} from "./reply-tool-authority.js";
12+
import { createMockFollowupRun } from "./test-helpers.js";
713

814
const { handleSteerCommand } = await import("./commands-steer.js");
915

@@ -24,8 +30,20 @@ function beginActiveOperation(
2430
sessionKey: string,
2531
sessionId = "session-active",
2632
taskSuggestionDeliveryMode?: "gateway",
33+
authorityRun = createMockFollowupRun({ run: { sessionId, sessionKey } }),
2734
) {
2835
const operation = createReplyOperation({ sessionKey, sessionId, resetTriggered: false });
36+
const authorityRoute = {
37+
provider: authorityRun.run.provider,
38+
model: authorityRun.run.model,
39+
};
40+
const toolAuthorityFingerprint = resolveFollowupRunToolAuthorityFingerprint(
41+
authorityRun,
42+
authorityRoute,
43+
);
44+
operation.bindToolAuthorityProjector(createFollowupRunToolAuthorityProjector(authorityRun));
45+
operation.bindToolAuthorityRoute(authorityRoute);
46+
operation.bindToolAuthorityFingerprint(toolAuthorityFingerprint);
2947
operation.setPhase("running");
3048
operation.attachBackend({
3149
kind: "embedded",
@@ -34,7 +52,47 @@ function beginActiveOperation(
3452
messageInjection: { isAvailable: () => true, queueMessage },
3553
});
3654
operations.push(operation);
37-
return operation;
55+
return { operation, toolAuthorityFingerprint };
56+
}
57+
58+
function createCommandAuthorityRun(params: ReturnType<typeof buildParams>) {
59+
return createMockFollowupRun({
60+
originatingChannel: params.ctx.OriginatingChannel,
61+
toolsAllow: params.opts?.toolsAllow,
62+
disableTools: params.opts?.disableTools,
63+
run: {
64+
agentId: params.agentId ?? "main",
65+
agentDir: params.agentDir ?? "/tmp/agent",
66+
sessionId: "session-active",
67+
sessionKey: params.sessionKey,
68+
messageProvider: params.ctx.OriginatingChannel ?? params.ctx.Provider ?? params.ctx.Surface,
69+
chatType: params.ctx.ChatType as ChatType | undefined,
70+
agentAccountId: params.ctx.AccountId,
71+
conversationToolPolicy: params.ctx.ConversationToolPolicy,
72+
groupId: undefined,
73+
groupChannel: undefined,
74+
groupSpace: undefined,
75+
memberRoleIds: params.ctx.MemberRoleIds,
76+
spawnedBy: params.sessionEntry?.spawnedBy,
77+
senderId: params.ctx.SenderId,
78+
senderName: params.ctx.SenderName,
79+
senderUsername: params.ctx.SenderUsername,
80+
senderE164: params.ctx.SenderE164,
81+
senderIsOwner: params.command.senderIsOwner,
82+
traceAuthorized:
83+
params.command.senderIsOwner ||
84+
(params.ctx.GatewayClientScopes ?? []).includes("operator.admin"),
85+
approvalReviewerDeviceId: params.ctx.ApprovalReviewerDeviceId,
86+
clientCaps: params.ctx.GatewayClientCaps,
87+
toolBindings: params.ctx.GatewayRunToolBindings,
88+
inputProvenance: params.ctx.InputProvenance,
89+
workspaceDir: params.workspaceDir,
90+
config: params.cfg,
91+
toolOverrides: params.sessionEntry?.toolOverrides,
92+
provider: params.provider,
93+
model: params.model,
94+
},
95+
});
3896
}
3997

4098
describe("handleSteerCommand", () => {
@@ -46,23 +104,52 @@ describe("handleSteerCommand", () => {
46104
}
47105
});
48106

49-
it("injects into the captured current text-command session", async () => {
50-
beginActiveOperation("agent:main:main");
107+
it("matching authority /steer injects into the captured operation", async () => {
108+
const params = buildParams("/steer keep going");
109+
params.opts = { toolsAllow: ["read"] };
110+
const { toolAuthorityFingerprint } = beginActiveOperation(
111+
"agent:main:main",
112+
"session-active",
113+
undefined,
114+
createCommandAuthorityRun(params),
115+
);
51116

52-
const result = await handleSteerCommand(buildParams("/steer keep going"), true);
117+
const result = await handleSteerCommand(params, true);
53118

54119
expect(result).toEqual({
55120
shouldContinue: false,
56121
reply: { text: "steered current session." },
57122
});
58123
expect(queueMessage).toHaveBeenCalledWith("keep going", {
59124
steeringMode: "all",
125+
isInboundUserMessage: true,
126+
toolAuthorityFingerprint,
60127
debounceMs: 0,
61128
taskSuggestionDeliveryMode: undefined,
62129
onQueueAccepted: expect.any(Function),
63130
});
64131
});
65132

133+
it("authorized sender with mismatched tool authority cannot inject via /steer", async () => {
134+
const activeParams = buildParams("/steer keep going");
135+
activeParams.opts = { toolsAllow: ["exec"] };
136+
beginActiveOperation(
137+
"agent:main:main",
138+
"session-active",
139+
undefined,
140+
createCommandAuthorityRun(activeParams),
141+
);
142+
const params = buildParams("/steer keep going");
143+
params.opts = { toolsAllow: ["read"] };
144+
145+
const result = await handleSteerCommand(params, true);
146+
147+
expect(result).toEqual({ shouldContinue: true });
148+
expect(params.ctx.BodyForAgent).toBe("keep going");
149+
expect(params.command.commandBodyNormalized).toBe("keep going");
150+
expect(queueMessage).not.toHaveBeenCalled();
151+
});
152+
66153
it("passes the initiating surface task capability into steering", async () => {
67154
beginActiveOperation("agent:main:main", "session-active", "gateway");
68155
const params = buildParams("/steer keep going");

‎src/auto-reply/reply/commands-steer.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
replyRunRegistry,
2121
type ReplyMessageInjectionTarget,
2222
} from "./reply-run-registry.js";
23+
import { resolveInboundReplyToolAuthorityOverlay } from "./reply-tool-authority.js";
2324

2425
const STEER_USAGE = "Usage: /steer <message>";
2526

@@ -60,15 +61,15 @@ function listSteerCandidateSessionKeys(targetSessionKey: string): string[] {
6061

6162
function resolveSteerTarget(
6263
targetSessionKey: string,
63-
): { sessionId: string; target: ReplyMessageInjectionTarget } | undefined {
64+
): { sessionId: string; sessionKey: string; target: ReplyMessageInjectionTarget } | undefined {
6465
const candidateKeys = listSteerCandidateSessionKeys(targetSessionKey);
6566
for (const candidateKey of candidateKeys) {
6667
const operation = replyRunRegistry.get(candidateKey);
6768
const target = operation
6869
? replyRunRegistry.resolveCurrentMessageInjectionTarget(candidateKey)
6970
: undefined;
7071
if (operation && target) {
71-
return { sessionId: operation.sessionId, target };
72+
return { sessionId: operation.sessionId, sessionKey: candidateKey, target };
7273
}
7374
}
7475

@@ -114,6 +115,16 @@ export const handleSteerCommand: CommandHandler = defineAuthorizedTextCommand(
114115
target: steerTarget.target,
115116
attempt: beginReplyMessageInjectionTarget(steerTarget.target, message, {
116117
steeringMode: "all",
118+
isInboundUserMessage: true,
119+
toolAuthorityOverlay: resolveInboundReplyToolAuthorityOverlay({
120+
ctx: params.ctx,
121+
sessionEntry:
122+
params.sessionStore?.[steerTarget.sessionKey] ??
123+
(params.sessionKey === steerTarget.sessionKey ? params.sessionEntry : undefined),
124+
senderIsOwner: params.command.senderIsOwner,
125+
toolsAllow: params.opts?.toolsAllow,
126+
disableTools: params.opts?.disableTools === true,
127+
}),
117128
debounceMs: 0,
118129
...(params.opts?.sourceReplyDeliveryMode
119130
? { sourceReplyDeliveryMode: params.opts.sourceReplyDeliveryMode }

‎src/auto-reply/reply/reply-run-registry.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { enqueueCommandInLane, setCommandLaneConcurrency } from "../../process/c
1616
import { resetCommandQueueStateForTest } from "../../process/command-queue.test-support.js";
1717
import { createQueueTestRun } from "./queue.test-helpers.js";
1818
import { beginReplyOperationFinalizationWork } from "./reply-run-finalization-lease.js";
19+
import type { ReplyToolAuthorityOverlay } from "./reply-run-registry.contracts.js";
1920
import {
2021
abortActiveReplyRuns,
2122
beginReplyMessageInjectionTarget,
@@ -32,7 +33,6 @@ import {
3233
REPLY_RUN_TERMINAL_SETTLE_TIMEOUT_MS,
3334
registerReplyOperationSuccessorBarrier,
3435
type ReplyBackendQueueMessageOptions,
35-
type ReplyToolAuthorityOverlay,
3636
ReplyRunAlreadyActiveError,
3737
ReplyRunSuccessorAdmissionBlockedError,
3838
replyRunRegistry,

‎src/auto-reply/reply/reply-run-registry.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ export type {
1414
ReplyMessageInjectionTarget,
1515
ReplyOperation,
1616
ReplyOperationPhase,
17-
ReplyToolAuthorityOverlay,
1817
ReplyTurnKind,
1918
} from "./reply-run-registry.contracts.js";
2019
export {

‎src/auto-reply/reply/reply-tool-authority.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
import { createHash } from "node:crypto";
22
import { stableStringify } from "@openclaw/normalization-core";
3+
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
34
import { resolveConversationCapabilityProfile } from "../../agents/conversation-capability-profile.js";
45
import { resolveSandboxRuntimeStatus } from "../../agents/sandbox/runtime-status.js";
56
import { readToolAllowlistIntersection } from "../../agents/tool-policy.js";
7+
import { normalizeChatType } from "../../channels/chat-type.js";
8+
import type { SessionEntry } from "../../config/sessions.js";
9+
import { resolveGroupSessionKey } from "../../config/sessions/group.js";
10+
import type { RuntimeMsgContext } from "../templating.js";
11+
import { resolveOriginMessageProvider } from "./origin-routing.js";
612
import type { FollowupRun } from "./queue.js";
713
import type {
814
ReplyToolAuthorityOverlay,
@@ -18,6 +24,53 @@ type ReplyToolAuthoritySnapshot = {
1824
run: FollowupRun["run"];
1925
};
2026

27+
/** Projects current inbound facts against the active run's frozen authority snapshot. */
28+
export function resolveInboundReplyToolAuthorityOverlay(params: {
29+
ctx: RuntimeMsgContext;
30+
sessionEntry?: Pick<SessionEntry, "spawnedBy">;
31+
senderIsOwner: boolean;
32+
toolsAllow?: string[];
33+
disableTools: boolean;
34+
}): ReplyToolAuthorityOverlay {
35+
const { ctx } = params;
36+
return {
37+
originatingChannel: ctx.OriginatingChannel,
38+
messageProvider: resolveOriginMessageProvider({
39+
originatingChannel: ctx.OriginatingChannel,
40+
provider: ctx.Provider ?? ctx.Surface,
41+
}),
42+
chatType: normalizeChatType(ctx.ChatType),
43+
agentAccountId: ctx.AccountId,
44+
conversationToolPolicy: ctx.ConversationToolPolicy,
45+
groupId: resolveGroupSessionKey(ctx)?.id,
46+
groupChannel:
47+
normalizeOptionalString(ctx.GroupChannel) ?? normalizeOptionalString(ctx.GroupSubject),
48+
groupSpace: normalizeOptionalString(ctx.GroupSpace),
49+
memberRoleIds: Array.isArray(ctx.MemberRoleIds)
50+
? ctx.MemberRoleIds.map((roleId) => normalizeOptionalString(roleId)).filter(
51+
(roleId): roleId is string => Boolean(roleId),
52+
)
53+
: undefined,
54+
spawnedBy: normalizeOptionalString(params.sessionEntry?.spawnedBy),
55+
senderId: normalizeOptionalString(ctx.SenderId),
56+
senderName: normalizeOptionalString(ctx.SenderName),
57+
senderUsername: normalizeOptionalString(ctx.SenderUsername),
58+
senderE164: normalizeOptionalString(ctx.SenderE164),
59+
senderIsOwner: params.senderIsOwner,
60+
inputProvenance: ctx.InputProvenance,
61+
trustedInternalHandoff: undefined,
62+
scheduledToolPolicy: undefined,
63+
runtimePluginToolGrant: undefined,
64+
toolsAllow: params.toolsAllow,
65+
disableTools: params.disableTools,
66+
traceAuthorized:
67+
params.senderIsOwner || (ctx.GatewayClientScopes ?? []).includes("operator.admin"),
68+
approvalReviewerDeviceId: normalizeOptionalString(ctx.ApprovalReviewerDeviceId),
69+
clientCaps: ctx.GatewayClientCaps,
70+
toolBindings: ctx.GatewayRunToolBindings,
71+
};
72+
}
73+
2174
function snapshotFollowupRunToolAuthority(run: FollowupRun): ReplyToolAuthoritySnapshot {
2275
return {
2376
originatingChannel: run.originatingChannel,

‎src/gateway/server-methods/chat-send-message-injection.ts‎

Lines changed: 13 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,19 @@
1-
import {
2-
normalizeLowercaseStringOrEmpty,
3-
normalizeOptionalString,
4-
} from "@openclaw/normalization-core/string-coerce";
1+
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
52
import { resolveCommandAuthorization } from "../../auto-reply/command-auth.js";
63
import { emitInboundMessageAuditTerminal } from "../../auto-reply/reply/dispatch-from-config.audit.js";
74
import { finalizeInboundContext } from "../../auto-reply/reply/inbound-context.js";
85
import { hasInboundAudio } from "../../auto-reply/reply/inbound-media.js";
96
import { emitMessageReceivedHooks } from "../../auto-reply/reply/message-received-hooks.js";
10-
import { resolveOriginMessageProvider } from "../../auto-reply/reply/origin-routing.js";
117
import { resolveQueueSettings } from "../../auto-reply/reply/queue/settings-runtime.js";
128
import {
139
beginReplyMessageInjectionTarget,
1410
finalizeReplyMessageInjectionAttempt,
1511
type ReplyBackendQueueMessageOptions,
1612
type ReplyMessageInjectionAttempt,
1713
type ReplyMessageInjectionTarget,
18-
type ReplyToolAuthorityOverlay,
1914
} from "../../auto-reply/reply/reply-run-registry.js";
15+
import { resolveInboundReplyToolAuthorityOverlay } from "../../auto-reply/reply/reply-tool-authority.js";
2016
import type { RuntimeMsgContext } from "../../auto-reply/templating.js";
21-
import { normalizeChatType } from "../../channels/chat-type.js";
22-
import { resolveGroupSessionKey } from "../../config/sessions/group.js";
2317
import { updateSessionEntry } from "../../config/sessions/session-accessor.js";
2418
import { isDiagnosticsEnabled } from "../../infra/diagnostic-events.js";
2519
import { logMessageProcessed, logMessageReceived } from "../../logging/diagnostic.js";
@@ -32,54 +26,6 @@ import type { PreparedChatSendSession } from "./chat-send-session.js";
3226
import type { prepareChatSendUserTurn } from "./chat-send-user-turn.js";
3327
import type { GatewayRequestContext } from "./types.js";
3428

35-
function resolveChatSendToolAuthorityOverlay(params: {
36-
ctx: RuntimeMsgContext;
37-
session: Pick<PreparedChatSendSession, "cfg" | "entry">;
38-
}): ReplyToolAuthorityOverlay {
39-
const { ctx, session } = params;
40-
const authorization = resolveCommandAuthorization({
41-
ctx,
42-
cfg: session.cfg,
43-
commandAuthorized: ctx.CommandAuthorized === true,
44-
});
45-
const senderIsOwner = authorization.senderIsOwner;
46-
return {
47-
originatingChannel: ctx.OriginatingChannel,
48-
messageProvider: resolveOriginMessageProvider({
49-
originatingChannel: ctx.OriginatingChannel,
50-
provider: ctx.Provider,
51-
}),
52-
chatType: normalizeChatType(ctx.ChatType),
53-
agentAccountId: ctx.AccountId,
54-
conversationToolPolicy: ctx.ConversationToolPolicy,
55-
groupId: resolveGroupSessionKey(ctx)?.id,
56-
groupChannel:
57-
normalizeOptionalString(ctx.GroupChannel) ?? normalizeOptionalString(ctx.GroupSubject),
58-
groupSpace: normalizeOptionalString(ctx.GroupSpace),
59-
memberRoleIds: Array.isArray(ctx.MemberRoleIds)
60-
? ctx.MemberRoleIds.map((roleId) => normalizeOptionalString(roleId)).filter(
61-
(roleId): roleId is string => Boolean(roleId),
62-
)
63-
: undefined,
64-
spawnedBy: session.entry?.spawnedBy,
65-
senderId: normalizeOptionalString(ctx.SenderId),
66-
senderName: normalizeOptionalString(ctx.SenderName),
67-
senderUsername: normalizeOptionalString(ctx.SenderUsername),
68-
senderE164: normalizeOptionalString(ctx.SenderE164),
69-
senderIsOwner,
70-
inputProvenance: ctx.InputProvenance,
71-
trustedInternalHandoff: undefined,
72-
scheduledToolPolicy: undefined,
73-
runtimePluginToolGrant: undefined,
74-
toolsAllow: undefined,
75-
disableTools: false,
76-
traceAuthorized: senderIsOwner || (ctx.GatewayClientScopes ?? []).includes("operator.admin"),
77-
approvalReviewerDeviceId: normalizeOptionalString(ctx.ApprovalReviewerDeviceId),
78-
clientCaps: ctx.GatewayClientCaps,
79-
toolBindings: ctx.GatewayRunToolBindings,
80-
};
81-
}
82-
8329
/** Captures the prepared request data used by both pre-ACK and detached injection attempts. */
8430
export function createChatSendMessageInjectionStarter(params: {
8531
target: ReplyMessageInjectionTarget | undefined;
@@ -105,6 +51,11 @@ export function createChatSendMessageInjectionStarter(params: {
10551
inlineMode: p.queueMode,
10652
});
10753
const text = ctx.BodyForAgent ?? ctx.Body ?? rawMessage;
54+
const authorization = resolveCommandAuthorization({
55+
ctx,
56+
cfg,
57+
commandAuthorized: ctx.CommandAuthorized === true,
58+
});
10859
const attempt = beginReplyMessageInjectionTarget(
10960
params.target,
11061
p.replyToId
@@ -113,7 +64,12 @@ export function createChatSendMessageInjectionStarter(params: {
11364
{
11465
steeringMode: "all",
11566
isInboundUserMessage: true,
116-
toolAuthorityOverlay: resolveChatSendToolAuthorityOverlay({ ctx, session: params.session }),
67+
toolAuthorityOverlay: resolveInboundReplyToolAuthorityOverlay({
68+
ctx,
69+
sessionEntry: entry,
70+
senderIsOwner: authorization.senderIsOwner,
71+
disableTools: false,
72+
}),
11773
...(replyOptionImages?.length ? { images: replyOptionImages } : {}),
11874
...(params.imageOrder?.length ? { imageOrder: params.imageOrder } : {}),
11975
...(replyOptionMedia?.length ? { media: replyOptionMedia } : {}),

0 commit comments

Comments
 (0)