Skip to content

Commit c39abce

Browse files
authored
fix(security): report DM isolation from effective routing (#121741)
* fix(security): audit effective DM session ownership Resolve admitted DM principals through canonical route, account, identity-link, and channel-owned session policy before reporting shared-session risk. Doctor now renders the structured channel security owner instead of duplicating the global-only default-account heuristic.\n\nCloses #121711 * chore(plugin-sdk): refresh API contract baseline * fix(telegram): preserve direct peer SDK export * fix(telegram): preserve direct peer resolver signature * fix(ci): use supported DM audit grouping * fix(protocol): refresh approval reviewer Swift models
1 parent cf432ec commit c39abce

23 files changed

Lines changed: 1127 additions & 375 deletions

‎docs/.generated/plugin-sdk-api-baseline.jsonl‎

Lines changed: 65 additions & 65 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎docs/plugins/sdk-channel-plugins.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -870,6 +870,19 @@ unrelated inbound runtime helpers.
870870

871871
For channels that accept both canonical top-level DM keys and legacy nested keys, use the helpers from `plugin-sdk/channel-config-helpers`: `resolveChannelDmAccess`, `resolveChannelDmPolicy`, `resolveChannelDmAllowFrom`, and `normalizeChannelDmPolicy` keep account-local values ahead of inherited root values. Pair the same resolver with doctor repair through `normalizeLegacyDmAliases` so runtime and migration read the same contract.
872872

873+
If a channel intentionally applies stricter DM session routing than the
874+
global config, expose that behavior through `security.dmRouting` so Doctor
875+
and security audit resolve the same session owner as runtime. The optional
876+
`resolveDmScope` callback runs before core route resolution; its context
877+
includes `cfg`, `accountId`, the resolved `account`, and a `principalId`
878+
for finite allowlist entries. `resolveDmRoute` receives those fields plus
879+
the resolved core `route`; it may return `{ sessionKey }` for a shared final
880+
bucket, `{ kind: "isolated" }` for an unknown peer, or `{ kind: "core" }`
881+
to preserve core `dmScope` namespace analysis. For wildcard/open policy,
882+
`principalId` is absent and an undefined result is reported as unverified.
883+
Diagnostics never invent a peer ID. Keep both callbacks pure and
884+
import-safe because read-only diagnostics run without channel runtime.
885+
873886
<Accordion title="What createChatChannelPlugin does for you">
874887
Instead of implementing low-level adapter interfaces manually, you pass
875888
declarative options and the builder composes them:

‎extensions/telegram/api.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,6 @@ export {
5151
isBinaryContent,
5252
normalizeForwardedContext,
5353
resetTelegramForumFlagCacheForTest,
54-
resolveTelegramDirectPeerId,
5554
resolveTelegramForumFlag,
5655
resolveTelegramForumThreadId,
5756
resolveTelegramGroupAllowFromContext,
@@ -64,6 +63,7 @@ export {
6463
type TelegramThreadSpec,
6564
withResolvedTelegramForumFlag,
6665
} from "./src/bot/helpers.js";
66+
export { resolveTelegramDirectPeerId } from "./src/dm-session-key.js";
6767
export {
6868
normalizeTelegramCommandDescription,
6969
normalizeTelegramCommandName,

‎extensions/telegram/src/bot/helpers.test.ts‎

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import {
77
hasBotMention,
88
isBinaryContent,
99
normalizeForwardedContext,
10-
resolveTelegramDirectPeerId,
1110
resolveTelegramBotHasTopicsEnabled,
1211
resolveTelegramForumFlag,
1312
resolveTelegramForumThreadId,
@@ -216,20 +215,6 @@ describe("resolveTelegramBotHasTopicsEnabled", () => {
216215
});
217216
});
218217

219-
describe("resolveTelegramDirectPeerId", () => {
220-
it("prefers sender id when available", () => {
221-
expect(resolveTelegramDirectPeerId({ chatId: 777777777, senderId: 123456789 })).toBe(
222-
"123456789",
223-
);
224-
});
225-
226-
it("falls back to chat id when sender id is missing", () => {
227-
expect(resolveTelegramDirectPeerId({ chatId: 777777777, senderId: undefined })).toBe(
228-
"777777777",
229-
);
230-
});
231-
});
232-
233218
describe("normalizeForwardedContext", () => {
234219
it("handles forward_origin users", () => {
235220
const ctx = normalizeForwardedContext({

‎extensions/telegram/src/bot/helpers.ts‎

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ import {
1919
resolveExpiresAtMsFromDurationMs,
2020
} from "openclaw/plugin-sdk/number-runtime";
2121
import { normalizeAccountId } from "openclaw/plugin-sdk/routing";
22-
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
2322
import { expandTelegramAllowFromWithAccessGroups } from "../access-groups.js";
2423
import {
2524
firstDefined,
@@ -546,25 +545,6 @@ export function buildTelegramGroupPeerId(chatId: number | string, messageThreadI
546545
return messageThreadId != null ? `${chatId}:topic:${messageThreadId}` : String(chatId);
547546
}
548547

549-
/**
550-
* Resolve the direct-message peer identifier for Telegram routing/session keys.
551-
*
552-
* In some Telegram DM deliveries (for example certain business/chat bridge flows),
553-
* `chat.id` can differ from the actual sender user id. Prefer sender id when present
554-
* so per-peer DM scopes isolate users correctly.
555-
*/
556-
export function resolveTelegramDirectPeerId(params: {
557-
chatId: number | string;
558-
senderId?: number | string | null;
559-
}) {
560-
const senderId =
561-
params.senderId != null ? (normalizeOptionalString(String(params.senderId)) ?? "") : "";
562-
if (senderId) {
563-
return senderId;
564-
}
565-
return String(params.chatId);
566-
}
567-
568548
export function buildTelegramGroupFrom(chatId: number | string, messageThreadId?: number) {
569549
return `telegram:group:${buildTelegramGroupPeerId(chatId, messageThreadId)}`;
570550
}

‎extensions/telegram/src/conversation-route.ts‎

Lines changed: 10 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,17 @@ import {
88
import {
99
buildAgentSessionKey,
1010
deriveLastRoutePolicy,
11-
normalizeAccountId,
1211
resolveAgentRoute,
1312
} from "openclaw/plugin-sdk/routing";
1413
import { buildAgentMainSessionKey, sanitizeAgentId } from "openclaw/plugin-sdk/routing";
1514
import { logVerbose } from "openclaw/plugin-sdk/runtime-env";
1615
import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coerce-runtime";
1716
import { resolveDefaultTelegramAccountId } from "./accounts.js";
17+
import { buildTelegramGroupPeerId, buildTelegramParentPeer } from "./bot/helpers.js";
1818
import {
19-
buildTelegramGroupPeerId,
20-
buildTelegramParentPeer,
2119
resolveTelegramDirectPeerId,
22-
} from "./bot/helpers.js";
20+
resolveTelegramNamedAccountBaseSessionKey,
21+
} from "./dm-session-key.js";
2322

2423
type TelegramResolvedRoute = ReturnType<typeof resolveAgentRoute>;
2524
type ConfiguredTelegramBinding = NonNullable<ConfiguredBindingRouteResult["bindingResolution"]>;
@@ -54,10 +53,7 @@ export function resolveTelegramConversationRoute(params: {
5453
}): TelegramConversationRouteResult {
5554
const peerId = params.isGroup
5655
? buildTelegramGroupPeerId(params.chatId, params.resolvedThreadId)
57-
: resolveTelegramDirectPeerId({
58-
chatId: params.chatId,
59-
senderId: params.senderId,
60-
});
56+
: resolveTelegramDirectPeerId({ chatId: params.chatId, senderId: params.senderId });
6157
const parentPeer = buildTelegramParentPeer({
6258
isGroup: params.isGroup,
6359
resolvedThreadId: params.resolvedThreadId,
@@ -158,37 +154,11 @@ export function resolveTelegramConversationRoute(params: {
158154
};
159155
}
160156

161-
export function resolveTelegramConversationBaseSessionKey(params: {
162-
cfg: OpenClawConfig;
163-
route: Pick<
164-
ReturnType<typeof resolveTelegramConversationRoute>["route"],
165-
"agentId" | "accountId" | "matchedBy" | "sessionKey"
166-
>;
167-
chatId: number | string;
168-
isGroup: boolean;
169-
senderId?: string | number | null;
170-
}): string {
171-
const routeAccountId = normalizeAccountId(params.route.accountId);
172-
const defaultAccountId = normalizeAccountId(resolveDefaultTelegramAccountId(params.cfg));
173-
const isNamedAccountFallback =
174-
routeAccountId !== defaultAccountId && params.route.matchedBy === "default";
175-
if (!isNamedAccountFallback || params.isGroup) {
176-
return params.route.sessionKey;
177-
}
178-
return normalizeLowercaseStringOrEmpty(
179-
buildAgentSessionKey({
180-
agentId: params.route.agentId,
181-
channel: "telegram",
182-
accountId: params.route.accountId,
183-
peer: {
184-
kind: "direct",
185-
id: resolveTelegramDirectPeerId({
186-
chatId: params.chatId,
187-
senderId: params.senderId,
188-
}),
189-
},
190-
dmScope: "per-account-channel-peer",
191-
identityLinks: params.cfg.session?.identityLinks,
192-
}),
157+
export function resolveTelegramConversationBaseSessionKey(
158+
params: Parameters<typeof resolveTelegramNamedAccountBaseSessionKey>[1],
159+
): string {
160+
return resolveTelegramNamedAccountBaseSessionKey(
161+
resolveDefaultTelegramAccountId(params.cfg),
162+
params,
193163
);
194164
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { describe, expect, it } from "vitest";
2+
import { resolveTelegramDirectPeerId, resolveTelegramSecurityDmRoute } from "./dm-session-key.js";
3+
4+
describe("Telegram DM session keys", () => {
5+
it("prefers sender id and falls back to chat id", () => {
6+
expect(resolveTelegramDirectPeerId({ chatId: 777777777, senderId: 123456789 })).toBe(
7+
"123456789",
8+
);
9+
expect(resolveTelegramDirectPeerId({ chatId: 777777777 })).toBe("777777777");
10+
});
11+
12+
it.each([
13+
{
14+
name: "named-account default fallback",
15+
accountId: "personal",
16+
fallbackRoute: { dmScope: "main" as const, matchedBy: "default" as const },
17+
expected: "isolated",
18+
},
19+
{
20+
name: "default-account main scope",
21+
accountId: "default",
22+
fallbackRoute: { dmScope: "main" as const, matchedBy: "default" as const },
23+
expected: "shared",
24+
},
25+
{
26+
name: "named account with a winning binding",
27+
accountId: "personal",
28+
fallbackRoute: { dmScope: "main" as const, matchedBy: "binding.account" as const },
29+
expected: "shared",
30+
},
31+
{
32+
name: "account-isolated core scope",
33+
accountId: "default",
34+
fallbackRoute: {
35+
dmScope: "per-account-channel-peer" as const,
36+
matchedBy: "default" as const,
37+
},
38+
expected: "isolated",
39+
},
40+
{
41+
name: "per-peer core namespace",
42+
accountId: "default",
43+
fallbackRoute: { dmScope: "per-peer" as const, matchedBy: "default" as const },
44+
expected: "core",
45+
},
46+
{
47+
name: "per-channel core namespace",
48+
accountId: "default",
49+
fallbackRoute: { dmScope: "per-channel-peer" as const, matchedBy: "default" as const },
50+
expected: "core",
51+
},
52+
])("classifies $name as $expected", ({ accountId, fallbackRoute, expected }) => {
53+
const result = resolveTelegramSecurityDmRoute("default", {
54+
cfg: {},
55+
accountId,
56+
route: {
57+
...fallbackRoute,
58+
agentId: "main",
59+
accountId,
60+
channel: "telegram",
61+
sessionKey: "agent:main:main",
62+
mainSessionKey: "agent:main:main",
63+
lastRoutePolicy: "main",
64+
},
65+
});
66+
expect("kind" in result ? result.kind : "shared").toBe(expected);
67+
});
68+
});
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
2+
import {
3+
buildAgentSessionKey,
4+
normalizeAccountId,
5+
type ResolvedAgentRoute,
6+
} from "openclaw/plugin-sdk/routing";
7+
8+
export function resolveTelegramDirectPeerId(params: {
9+
chatId: number | string;
10+
senderId?: number | string | null;
11+
}) {
12+
const normalized = params.senderId == null ? "" : String(params.senderId).trim();
13+
return normalized || String(params.chatId);
14+
}
15+
16+
export function resolveTelegramNamedAccountBaseSessionKey(
17+
defaultAccountId: string,
18+
params: {
19+
cfg: OpenClawConfig;
20+
route: Pick<ResolvedAgentRoute, "agentId" | "accountId" | "matchedBy" | "sessionKey">;
21+
chatId: number | string;
22+
isGroup: boolean;
23+
senderId?: string | number | null;
24+
},
25+
): string {
26+
const routeAccountId = normalizeAccountId(params.route.accountId);
27+
const normalizedDefaultAccountId = normalizeAccountId(defaultAccountId);
28+
const isNamedAccountFallback =
29+
routeAccountId !== normalizedDefaultAccountId && params.route.matchedBy === "default";
30+
if (!isNamedAccountFallback || params.isGroup) {
31+
return params.route.sessionKey;
32+
}
33+
return buildAgentSessionKey({
34+
agentId: params.route.agentId,
35+
channel: "telegram",
36+
accountId: params.route.accountId,
37+
peer: {
38+
kind: "direct",
39+
id: resolveTelegramDirectPeerId({
40+
chatId: params.chatId,
41+
senderId: params.senderId,
42+
}),
43+
},
44+
dmScope: "per-account-channel-peer",
45+
identityLinks: params.cfg.session?.identityLinks,
46+
});
47+
}
48+
49+
export function resolveTelegramSecurityDmRoute(
50+
defaultAccountId: string,
51+
params: {
52+
cfg: OpenClawConfig;
53+
accountId: string;
54+
route: ResolvedAgentRoute;
55+
principalId?: string;
56+
},
57+
): { kind: "core" | "isolated" } | { sessionKey: string } {
58+
if (params.principalId !== undefined) {
59+
return {
60+
sessionKey: resolveTelegramNamedAccountBaseSessionKey(defaultAccountId, {
61+
...params,
62+
chatId: params.principalId,
63+
isGroup: false,
64+
senderId: params.principalId,
65+
}),
66+
};
67+
}
68+
const isNamedAccountFallback =
69+
normalizeAccountId(params.accountId) !== normalizeAccountId(defaultAccountId) &&
70+
params.route.matchedBy === "default";
71+
if (isNamedAccountFallback || params.route.dmScope === "per-account-channel-peer") {
72+
return { kind: "isolated" };
73+
}
74+
return params.route.dmScope === "main"
75+
? { sessionKey: params.route.sessionKey }
76+
: { kind: "core" };
77+
}

‎extensions/telegram/src/security.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
import { createScopedDmSecurityResolver } from "openclaw/plugin-sdk/channel-config-helpers";
33
import type { ChannelPlugin } from "openclaw/plugin-sdk/channel-core";
44
import { createAllowlistProviderRouteAllowlistWarningCollector } from "openclaw/plugin-sdk/channel-policy";
5+
import { resolveDefaultTelegramAccountId } from "./account-selection.js";
56
import type { ResolvedTelegramAccount } from "./accounts.js";
7+
import { resolveTelegramSecurityDmRoute } from "./dm-session-key.js";
68
import { collectTelegramSecurityAuditFindings } from "./security-audit.js";
79

810
const resolveTelegramDmPolicy = createScopedDmSecurityResolver<ResolvedTelegramAccount>({
@@ -36,6 +38,10 @@ const collectTelegramSecurityWarnings =
3638

3739
export const telegramSecurityAdapter = {
3840
resolveDmPolicy: resolveTelegramDmPolicy,
41+
dmRouting: {
42+
resolveDmRoute: (ctx) =>
43+
resolveTelegramSecurityDmRoute(resolveDefaultTelegramAccountId(ctx.cfg), ctx),
44+
},
3945
collectWarnings: collectTelegramSecurityWarnings,
4046
collectAuditFindings: collectTelegramSecurityAuditFindings,
4147
} satisfies NonNullable<ChannelPlugin<ResolvedTelegramAccount>["security"]>;

‎extensions/zalouser/src/channel.adapters.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import {
4949
parseZalouserOutboundTarget,
5050
resolveZalouserOutboundSessionRoute,
5151
} from "./session-route.js";
52+
import { resolveZalouserDmSessionScope } from "./session-scope.js";
5253
import type { ZaloSendResult } from "./types.js";
5354

5455
const loadZalouserChannelRuntime = createLazyRuntimeModule(() => import("./channel.runtime.js"));
@@ -435,6 +436,9 @@ export const zalouserAuthAdapter = {
435436

436437
export const zalouserSecurityAdapter = {
437438
resolveDmPolicy: resolveZalouserDmPolicy,
439+
dmRouting: {
440+
resolveDmScope: ({ cfg }: { cfg: OpenClawConfig }) => resolveZalouserDmSessionScope(cfg),
441+
},
438442
collectAuditFindings: async (params: {
439443
accountId?: string | null;
440444
account: ResolvedZalouserAccount;

0 commit comments

Comments
 (0)