Skip to content

Commit a3d2ac7

Browse files
authored
fix(telegram): inherit root group policy across accounts
Use channels.telegram.groups as the shared default when an account omits groups. Explicit account maps, including {}, remain full replacements. This keeps chat admission and sender restrictions on one policy path and fixes silent multi-account authorization failures. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 5297429 commit a3d2ac7

7 files changed

Lines changed: 163 additions & 65 deletions

File tree

‎docs/channels/telegram.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@ curl "https://api.telegram.org/bot<bot_token>/getUpdates"
200200

201201
`groupAllowFrom` filters group senders; if unset, Telegram falls back to `allowFrom` (not the pairing store — group sender auth never inherits DM pairing-store approvals, a security boundary since `2026.2.25`).
202202
`groupAllowFrom` entries should be numeric Telegram user IDs (`telegram:` / `tg:` prefixes are normalized); non-numeric entries are ignored. Do not put group or supergroup chat IDs here — negative chat IDs belong under `channels.telegram.groups`.
203+
In multi-account configs, root `channels.telegram.groups` is the shared default for accounts that omit `groups`. An account-level `groups` map replaces the root map for that account; it is not deep-merged. An explicit empty account map (`groups: {}`) keeps that account isolated from the shared groups.
203204
Practical pattern for one-owner bots: set your user ID in `channels.telegram.allowFrom`, leave `groupAllowFrom` unset, and allow the target groups under `channels.telegram.groups`.
204205
If `channels.telegram` is entirely missing from config, runtime defaults to fail-closed `groupPolicy="allowlist"` unless `channels.defaults.groupPolicy` is explicitly set.
205206

‎docs/channels/whatsapp.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -625,7 +625,7 @@ Resolution for direct messages follows the identical pattern against the `direct
625625
This account-replaces-root behavior for prompt resolution is a plain shallow override: any account `groups`/`direct` key, including an explicit empty object, replaces the root map. It differs from the group-membership allowlist check described above, which has a single-account safety net for an accidentally empty `groups: {}`.
626626
</Note>
627627

628-
**Difference from Telegram:** Telegram suppresses root `groups` for every account in a multi-account setup (even accounts with no `groups` of their own) to stop a bot receiving group messages for groups it does not belong to. WhatsApp does not apply that guard — root `groups`/`direct` are inherited by any account without its own override, regardless of account count. In a multi-account WhatsApp setup, define the full map under each account explicitly if you want per-account prompts.
628+
**Difference from Telegram:** Telegram uses the same whole-map account override for `groups` in multi-account configs, but a single account's empty `groups: {}` falls back to root groups as a migration safety net. Telegram's `direct` map also has separate DM-topic semantics. In WhatsApp—or for one account among several Telegram accounts—use an explicit empty `groups: {}` when that account should not inherit root group defaults.
629629

630630
Important behavior:
631631

‎extensions/policy/src/doctor/register.ingress-and-secrets.test-utils.ts‎

Lines changed: 58 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -398,7 +398,7 @@ describe("registerPolicyDoctorChecks", () => {
398398
);
399399
});
400400

401-
it("does not inherit Telegram root groups into multi-account named accounts", async () => {
401+
it("records inherited Telegram root groups for multi-account named accounts", async () => {
402402
const { cfg, result } = await runIngressPolicyScenario({
403403
telegram: {
404404
dmPolicy: "pairing",
@@ -427,19 +427,41 @@ describe("registerPolicyDoctorChecks", () => {
427427
});
428428
const evidence = scanPolicyIngress(cfg as unknown as Record<string, unknown>);
429429

430-
expect(evidence).not.toEqual(
430+
expect(evidence).toEqual(
431431
expect.arrayContaining([
432432
expect.objectContaining({
433433
accountId: "work",
434434
groupId: "ops",
435435
kind: "channelRequireMention",
436+
source: "oc://openclaw.config/channels/telegram/groups/ops/requireMention",
437+
value: false,
438+
}),
439+
expect.objectContaining({
440+
accountId: "personal",
441+
groupId: "ops",
442+
kind: "channelRequireMention",
443+
source: "oc://openclaw.config/channels/telegram/groups/ops/requireMention",
444+
value: false,
445+
}),
446+
]),
447+
);
448+
expect(result.findings).toEqual(
449+
expect.arrayContaining([
450+
expect.objectContaining({
451+
checkId: "policy/ingress-group-mention-required",
452+
ocPath: "oc://openclaw.config/channels/telegram/groups/ops/requireMention",
453+
message: expect.stringContaining("account 'work'"),
454+
}),
455+
expect.objectContaining({
456+
checkId: "policy/ingress-group-mention-required",
457+
ocPath: "oc://openclaw.config/channels/telegram/groups/ops/requireMention",
458+
message: expect.stringContaining("account 'personal'"),
436459
}),
437460
]),
438461
);
439-
expect(result.findings).toEqual([]);
440462
});
441463

442-
it("lets Telegram account groups override root group inheritance", () => {
464+
it("lets an explicit Telegram account groups map override root inheritance", () => {
443465
const cfg = {
444466
channels: {
445467
telegram: {
@@ -453,6 +475,7 @@ describe("registerPolicyDoctorChecks", () => {
453475
work: {
454476
groups: {},
455477
},
478+
personal: {},
456479
},
457480
},
458481
},
@@ -471,6 +494,37 @@ describe("registerPolicyDoctorChecks", () => {
471494
);
472495
});
473496

497+
it("inherits root groups through a single Telegram account empty map", () => {
498+
const cfg = {
499+
channels: {
500+
telegram: {
501+
groups: {
502+
ops: {
503+
requireMention: false,
504+
},
505+
},
506+
accounts: {
507+
work: {
508+
groups: {},
509+
},
510+
},
511+
},
512+
},
513+
};
514+
515+
expect(scanPolicyIngress(cfg)).toEqual(
516+
expect.arrayContaining([
517+
expect.objectContaining({
518+
accountId: "work",
519+
groupId: "ops",
520+
kind: "channelRequireMention",
521+
source: "oc://openclaw.config/channels/telegram/groups/ops/requireMention",
522+
value: false,
523+
}),
524+
]),
525+
);
526+
});
527+
474528
it("records inherited root group overrides for multi-account ingress", async () => {
475529
const { cfg, result } = await runIngressPolicyScenario({
476530
slack: {

‎extensions/policy/src/policy-state-ingress.ts‎

Lines changed: 53 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -60,13 +60,13 @@ export function scanPolicyIngress(cfg: Record<string, unknown>): readonly Policy
6060
});
6161
}
6262
for (const [accountId, account] of activeAccounts) {
63-
const inheritsNestedContainers = channel !== "telegram" || configuredAccounts.length <= 1;
6463
pushChannelIngress(entries, {
6564
channel,
6665
accountId,
6766
config: account,
6867
inheritedConfig: value,
69-
inheritNestedContainers: inheritsNestedContainers,
68+
inheritNestedContainers: true,
69+
inheritEmptyNestedContainers: channel === "telegram" && configuredAccounts.length <= 1,
7070
sourceBase: `${channelSource}/accounts/${ocPathSegment(accountId)}`,
7171
inheritedSourceBase: channelSource,
7272
fallbackConfig: inheritedChannelDefaults,
@@ -140,6 +140,7 @@ type ChannelIngressParams = {
140140
readonly config: Record<string, unknown>;
141141
readonly inheritedConfig: Record<string, unknown>;
142142
readonly inheritNestedContainers?: boolean;
143+
readonly inheritEmptyNestedContainers?: boolean;
143144
readonly sourceBase: string;
144145
readonly inheritedSourceBase: string;
145146
readonly fallbackConfig?: Record<string, unknown>;
@@ -212,22 +213,15 @@ function channelImplicitGroupPolicy(params: ChannelIngressParams): {
212213
readonly source: string;
213214
readonly value: "allowlist" | "open";
214215
} {
215-
for (const [config, sourceBase] of [
216-
[params.config, params.sourceBase],
217-
...(params.inheritNestedContainers === true
218-
? ([[params.inheritedConfig, params.inheritedSourceBase]] as const)
219-
: []),
220-
[params.fallbackConfig, params.fallbackSourceBase],
221-
] as const) {
222-
if (config === undefined || sourceBase === undefined) {
223-
continue;
224-
}
225-
for (const key of ["groups"] as const) {
226-
const container = isRecord(config[key]) ? config[key] : undefined;
227-
if (container !== undefined && Object.keys(container).length > 0) {
228-
return { source: `${sourceBase}/${key}`, value: "allowlist" };
229-
}
230-
}
216+
const groups = effectiveNestedIngressContainer(params, "groups");
217+
if (groups !== undefined) {
218+
return { source: `${groups.sourceBase}/groups`, value: "allowlist" };
219+
}
220+
const fallbackGroups = isRecord(params.fallbackConfig?.groups)
221+
? params.fallbackConfig.groups
222+
: undefined;
223+
if (fallbackGroups !== undefined && Object.keys(fallbackGroups).length > 0) {
224+
return { source: `${params.fallbackSourceBase}/groups`, value: "allowlist" };
231225
}
232226
return {
233227
source: `${params.sourceBase}/groupPolicy`,
@@ -306,24 +300,28 @@ function channelDefaultRequireMention(params: ChannelIngressParams): boolean {
306300
function channelWildcardRequireMention(
307301
params: ChannelIngressParams,
308302
): { readonly source: string; readonly value: boolean } | undefined {
309-
for (const [config, sourceBase] of [
310-
[params.config, params.sourceBase],
311-
[params.inheritedConfig, params.inheritedSourceBase],
312-
[params.fallbackConfig, params.fallbackSourceBase],
313-
] as const) {
314-
if (config === undefined || sourceBase === undefined) {
315-
continue;
303+
for (const key of ["groups", "guilds", "channels", "rooms", "teams"] as const) {
304+
const effective = effectiveNestedIngressContainer(params, key);
305+
const wildcard = isRecord(effective?.container["*"]) ? effective.container["*"] : undefined;
306+
const requireMention = readBoolean(wildcard?.requireMention);
307+
if (wildcard?.enabled !== false && requireMention !== undefined && effective !== undefined) {
308+
return {
309+
source: `${effective.sourceBase}/${key}/${ocPathSegment("*")}/requireMention`,
310+
value: requireMention,
311+
};
316312
}
317-
for (const key of ["groups", "guilds", "channels", "rooms", "teams"] as const) {
318-
const container = isRecord(config[key]) ? config[key] : undefined;
319-
const wildcard = isRecord(container?.["*"]) ? container["*"] : undefined;
320-
const requireMention = readBoolean(wildcard?.requireMention);
321-
if (wildcard?.enabled !== false && requireMention !== undefined) {
322-
return {
323-
source: `${sourceBase}/${key}/${ocPathSegment("*")}/requireMention`,
324-
value: requireMention,
325-
};
326-
}
313+
const fallbackContainer = isRecord(params.fallbackConfig?.[key])
314+
? params.fallbackConfig[key]
315+
: undefined;
316+
const fallbackWildcard = isRecord(fallbackContainer?.["*"])
317+
? fallbackContainer["*"]
318+
: undefined;
319+
const fallbackRequireMention = readBoolean(fallbackWildcard?.requireMention);
320+
if (fallbackWildcard?.enabled !== false && fallbackRequireMention !== undefined) {
321+
return {
322+
source: `${params.fallbackSourceBase}/${key}/${ocPathSegment("*")}/requireMention`,
323+
value: fallbackRequireMention,
324+
};
327325
}
328326
}
329327
return undefined;
@@ -340,25 +338,31 @@ function nestedIngressContainers(params: ChannelIngressParams): readonly {
340338
readonly sourceBase: string;
341339
}[] = [];
342340
for (const key of ["groups", "guilds", "channels", "rooms", "teams"] as const) {
343-
const local = isRecord(params.config[key]) ? params.config[key] : undefined;
344-
const inherited = isRecord(params.inheritedConfig[key])
345-
? params.inheritedConfig[key]
346-
: undefined;
347-
if (local !== undefined) {
348-
if (Object.keys(local).length > 0) {
349-
containers.push({ containerKey: key, container: local, sourceBase: params.sourceBase });
350-
}
351-
} else if (params.inheritNestedContainers === true && inherited !== undefined) {
352-
containers.push({
353-
containerKey: key,
354-
container: inherited,
355-
sourceBase: params.inheritedSourceBase,
356-
});
341+
const effective = effectiveNestedIngressContainer(params, key);
342+
if (effective !== undefined) {
343+
containers.push({ containerKey: key, ...effective });
357344
}
358345
}
359346
return containers;
360347
}
361348

349+
function effectiveNestedIngressContainer(
350+
params: ChannelIngressParams,
351+
key: "groups" | "guilds" | "channels" | "rooms" | "teams",
352+
): { readonly container: Record<string, unknown>; readonly sourceBase: string } | undefined {
353+
const local = isRecord(params.config[key]) ? params.config[key] : undefined;
354+
const inherited = isRecord(params.inheritedConfig[key]) ? params.inheritedConfig[key] : undefined;
355+
if (local !== undefined && Object.keys(local).length > 0) {
356+
return { container: local, sourceBase: params.sourceBase };
357+
}
358+
const inheritsEmpty = local !== undefined && params.inheritEmptyNestedContainers === true;
359+
const inheritsMissing = local === undefined && params.inheritNestedContainers === true;
360+
if ((inheritsEmpty || inheritsMissing) && inherited !== undefined) {
361+
return { container: inherited, sourceBase: params.inheritedSourceBase };
362+
}
363+
return undefined;
364+
}
365+
362366
function pushNestedRequireMentionIngress(
363367
entries: PolicyIngressEvidence[],
364368
params: ChannelIngressParams,

‎extensions/telegram/src/account-config.ts‎

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -72,17 +72,14 @@ export function mergeTelegramAccountConfig(
7272
};
7373
const account = resolveTelegramAccountConfig(cfg, accountId) ?? {};
7474

75-
// Multi-account bots must not inherit channel-level groups unless explicitly set.
76-
// Single-account bots fall back to root `channels.telegram.groups` when the
77-
// account does not declare its own groups — including the empty-literal case
78-
// `accounts.<id>.groups: {}`, which is almost always a config-migration
79-
// artifact rather than an intentional "block all" declaration (use
80-
// `groupPolicy: "disabled"` for that).
75+
// Root groups are shared defaults; an account groups map replaces the whole map.
76+
// In multi-account configs an explicit empty map remains an account-local opt-out,
77+
// while the single-account empty-map migration artifact still falls back to root.
8178
const configuredAccountIds = Object.keys(cfg.channels?.telegram?.accounts ?? {});
8279
const isMultiAccount = configuredAccountIds.length > 1;
8380
const hasAccountGroups = account.groups && Object.keys(account.groups).length > 0;
8481
const groups = isMultiAccount
85-
? account.groups
82+
? (account.groups ?? channelGroups)
8683
: hasAccountGroups
8784
? account.groups
8885
: channelGroups;

‎extensions/telegram/src/accounts.test.ts‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -666,22 +666,34 @@ describe("resolveTelegramAccount groups inheritance (#30673)", () => {
666666
expect(resolved.config.groups).toEqual({ "-100123": { requireMention: false } });
667667
});
668668

669-
it("does NOT inherit channel-level groups to secondary account in multi-account setup", () => {
669+
it("inherits channel-level groups to secondary account when no account map is configured", () => {
670670
const resolved = resolveTelegramAccount({
671671
cfg: createMultiAccountGroupsConfig(),
672672
accountId: "dev",
673673
});
674674

675-
expect(resolved.config.groups).toBeUndefined();
675+
expect(resolved.config.groups).toEqual({ "-100123": { requireMention: false } });
676676
});
677677

678-
it("does NOT inherit channel-level groups to default account in multi-account setup", () => {
678+
it("inherits channel-level groups to default account when no account map is configured", () => {
679679
const resolved = resolveTelegramAccount({
680680
cfg: createMultiAccountGroupsConfig(),
681681
accountId: "default",
682682
});
683683

684-
expect(resolved.config.groups).toBeUndefined();
684+
expect(resolved.config.groups).toEqual({ "-100123": { requireMention: false } });
685+
});
686+
687+
it("keeps an explicit empty account groups map isolated in multi-account setup", () => {
688+
const cfg = createMultiAccountGroupsConfig();
689+
if (!cfg.channels?.telegram?.accounts?.dev) {
690+
throw new Error("expected dev Telegram account");
691+
}
692+
cfg.channels.telegram.accounts.dev.groups = {};
693+
694+
const resolved = resolveTelegramAccount({ cfg, accountId: "dev" });
695+
696+
expect(resolved.config.groups).toEqual({});
685697
});
686698

687699
it("uses account-level groups even in multi-account setup", () => {

‎extensions/telegram/src/bot.create-telegram-bot.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3470,6 +3470,36 @@ describe("createTelegramBot", () => {
34703470
},
34713471
expectedReplyCount: 1,
34723472
}),
3473+
makeMessagePolicyCase({
3474+
name: "inherits root per-group sender access in multi-account config",
3475+
telegram: {
3476+
groupPolicy: "allowlist",
3477+
groupAllowFrom: ["111111111"],
3478+
groups: {
3479+
"-100123456789": { allowFrom: ["123456789"], requireMention: false },
3480+
},
3481+
accounts: {
3482+
default: { botToken: "123:default" },
3483+
shadow: { enabled: false },
3484+
},
3485+
},
3486+
expectedReplyCount: 1,
3487+
}),
3488+
makeMessagePolicyCase({
3489+
name: "enforces root per-group sender access in multi-account config",
3490+
telegram: {
3491+
groupPolicy: "allowlist",
3492+
groupAllowFrom: ["123456789"],
3493+
groups: {
3494+
"-100123456789": { allowFrom: ["111111111"], requireMention: false },
3495+
},
3496+
accounts: {
3497+
default: { botToken: "123:default" },
3498+
shadow: { enabled: false },
3499+
},
3500+
},
3501+
expectedReplyCount: 0,
3502+
}),
34733503
makeMessagePolicyCase({
34743504
name: "blocks group messages when allowFrom is configured with @username entries (numeric IDs required)",
34753505
telegram: {

0 commit comments

Comments
 (0)