Skip to content

Commit 03c2879

Browse files
authored
fix(matrix): bot ignores valid plain-text room mentions (#117764)
* fix(matrix): recognize native plain-text room mentions * fix(matrix): reject Unicode account-prefix mention spoofing * fix(matrix): enforce complete native mention account boundaries * fix(matrix): recognize full user ID command mentions
1 parent ddf54f2 commit 03c2879

3 files changed

Lines changed: 331 additions & 4 deletions

File tree

‎extensions/matrix/src/matrix/monitor/handler.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -952,6 +952,67 @@ describe("matrix monitor handler pairing account scope", () => {
952952
},
953953
);
954954

955+
it.each([
956+
{ label: "full Matrix user ID", body: "hello @bot:example.org" },
957+
{ label: "colon-delimited full Matrix user ID", body: "@bot:example.org: help" },
958+
{ label: "Unicode-whitespace-colon-delimited full ID", body: "@bot:example.org:\u2003help" },
959+
{ label: "localpart shorthand", body: "hello @bot" },
960+
])("processes native plain-text $label without configured mention patterns", async ({ body }) => {
961+
const getMemberDisplayName = vi.fn(async () => "sender");
962+
const { handler, recordInboundSession, runPrepared } = createMatrixHandlerTestHarness({
963+
isDirectMessage: false,
964+
mentionRegexes: [],
965+
getMemberDisplayName,
966+
});
967+
968+
await handler(
969+
"!room:example.org",
970+
createMatrixTextMessageEvent({
971+
eventId: "$native-plain-text-mention",
972+
body,
973+
mentions: { user_ids: ["@bot:example.org"] },
974+
}),
975+
);
976+
977+
expect(recordInboundSession).toHaveBeenCalledOnce();
978+
expect(runPrepared.mock.calls[0]?.[0].ctxPayload).toMatchObject({
979+
AccountId: "ops",
980+
WasMentioned: true,
981+
});
982+
expect(getMemberDisplayName).not.toHaveBeenCalledWith("!room:example.org", "@bot:example.org");
983+
});
984+
985+
it.each([
986+
{ label: "another homeserver", body: "hello @bot:evil.example" },
987+
{ label: "an unexpected homeserver port", body: "@bot:example.org:8448: help" },
988+
{ label: "an invisible full-ID command separator", body: "@bot:example.org:\ufeffhelp" },
989+
{ label: "a room-alias full-ID command collision", body: "#@bot:example.org: help" },
990+
{ label: "a longer Unicode localpart", body: "hello @boté" },
991+
{ label: "a historical exclamation localpart", body: "hello @bot!evil:evil.example" },
992+
{ label: "a historical percent localpart", body: "hello @bot%evil:evil.example" },
993+
{ label: "an exclamation-only historical account", body: "hello @bot!" },
994+
{ label: "a percent-only historical account", body: "hello @bot%" },
995+
{ label: "a Markdown-only historical account", body: "hello @bot**" },
996+
{ label: "an attached Markdown-wrapped account", body: "hello evil**@bot" },
997+
])("rejects forged plain-text native mentions targeting $label", async ({ body }) => {
998+
const { handler, recordInboundSession } = createMatrixHandlerTestHarness({
999+
isDirectMessage: false,
1000+
mentionRegexes: [],
1001+
getMemberDisplayName: async () => "sender",
1002+
});
1003+
1004+
await handler(
1005+
"!room:example.org",
1006+
createMatrixTextMessageEvent({
1007+
eventId: "$foreign-native-mention",
1008+
body,
1009+
mentions: { user_ids: ["@bot:example.org"] },
1010+
}),
1011+
);
1012+
1013+
expect(recordInboundSession).not.toHaveBeenCalled();
1014+
});
1015+
9551016
it("processes room messages mentioned via displayName in formatted_body", async () => {
9561017
const recordInboundSession = vi.fn(async () => {});
9571018
const { handler } = createMatrixHandlerTestHarness({

‎extensions/matrix/src/matrix/monitor/mentions.test.ts‎

Lines changed: 250 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,256 @@ describe("resolveMentions", () => {
3535
expect(result.hasExplicitMention).toBe(true);
3636
});
3737

38+
it.each([
39+
{
40+
label: "full Matrix user ID",
41+
mentionedUserId: "@bot:matrix.org",
42+
body: "hello @bot:matrix.org",
43+
},
44+
{
45+
label: "colon-delimited full Matrix user ID",
46+
mentionedUserId: "@bot:matrix.org",
47+
body: "@bot:matrix.org: help",
48+
},
49+
{
50+
label: "Unicode-whitespace-colon-delimited full Matrix user ID",
51+
mentionedUserId: "@bot:matrix.org",
52+
body: "@bot:matrix.org:\u2003help",
53+
},
54+
{
55+
label: "colon-delimited full Matrix user ID with a homeserver port",
56+
mentionedUserId: "@bot:matrix.org:8448",
57+
body: "@bot:matrix.org:8448: help",
58+
},
59+
{
60+
label: "localpart shorthand",
61+
mentionedUserId: "@bot:matrix.org",
62+
body: "hello @bot",
63+
},
64+
{
65+
label: "colon-delimited shorthand",
66+
mentionedUserId: "@bot:matrix.org",
67+
body: "@bot: hello",
68+
},
69+
{
70+
label: "Unicode-whitespace-delimited shorthand",
71+
mentionedUserId: "@bot:matrix.org",
72+
body: "hello\u2003@bot\u2003thanks",
73+
},
74+
{
75+
label: "sentence-ending full Matrix user ID",
76+
mentionedUserId: "@bot:matrix.org",
77+
body: "hello @bot:matrix.org,",
78+
},
79+
{
80+
label: "special localpart characters",
81+
mentionedUserId: "@foo/bar+baz=ok:matrix.org",
82+
body: "hello @foo/bar+baz=ok",
83+
},
84+
{
85+
label: "historical Unicode localpart",
86+
mentionedUserId: "@böt中:matrix.org",
87+
body: "hello @böt中",
88+
},
89+
{
90+
label: "historical punctuation localpart",
91+
mentionedUserId: "@b!o%t&=x:matrix.org",
92+
body: "hello @b!o%t&=x",
93+
},
94+
{
95+
label: "historical punctuation in a full Matrix user ID",
96+
mentionedUserId: "@b!o%t&=x:matrix.org",
97+
body: "hello @b!o%t&=x:matrix.org",
98+
},
99+
{
100+
label: "bracketed IPv6 homeserver and port",
101+
mentionedUserId: "@bot:[2001:db8::1]:8448",
102+
body: "hello @bot:[2001:db8::1]:8448",
103+
},
104+
{
105+
label: "colon-delimited bracketed IPv6 homeserver and port",
106+
mentionedUserId: "@bot:[2001:db8::1]:8448",
107+
body: "@bot:[2001:db8::1]:8448:\u2003help",
108+
},
109+
])(
110+
"detects native plain-text $label without configured mention patterns",
111+
({ mentionedUserId, body }) => {
112+
const params = {
113+
content: {
114+
msgtype: "m.text",
115+
body,
116+
"m.mentions": { user_ids: [mentionedUserId] },
117+
},
118+
userId: mentionedUserId,
119+
text: body,
120+
mentionRegexes: [],
121+
};
122+
const expected = { wasMentioned: true, hasExplicitMention: true };
123+
124+
expect(resolveMentions(params)).toEqual(expected);
125+
expect(resolveMentions(params)).toEqual(expected);
126+
},
127+
);
128+
129+
it.each([
130+
{ label: "same localpart on another homeserver", body: "hello @bot:evil.example" },
131+
{ label: "case-different homeserver", body: "hello @bot:MATRIX.ORG" },
132+
{ label: "extended DNS homeserver", body: "hello @bot:matrix.org.evil" },
133+
{ label: "unexpected homeserver port", body: "hello @bot:matrix.org:8448" },
134+
{ label: "unexpected homeserver port before a command", body: "@bot:matrix.org:8448: help" },
135+
{ label: "unexpected repeated homeserver colon", body: "@bot:matrix.org::8448" },
136+
{ label: "full Matrix user ID followed by colon alone", body: "@bot:matrix.org:" },
137+
{
138+
label: "full Matrix user ID followed by invisible BOM",
139+
body: "@bot:matrix.org:\ufeffhelp",
140+
},
141+
{
142+
label: "full Matrix user ID followed by invisible zero-width text",
143+
body: "@bot:matrix.org:\u200bhelp",
144+
},
145+
{
146+
label: "full Matrix user ID followed by bidirectional formatting",
147+
body: "@bot:matrix.org:\u202ehelp",
148+
},
149+
{
150+
label: "full Matrix user ID followed by a hidden control",
151+
body: "@bot:matrix.org:\u0001help",
152+
},
153+
{ label: "alternate IPv6 homeserver", body: "hello @bot:[::1]" },
154+
{ label: "extended dotted localpart", body: "hello @bot.extra" },
155+
{ label: "extended plus localpart", body: "hello @bot+evil" },
156+
{ label: "extended hyphenated localpart", body: "hello @bot-evil" },
157+
{ label: "extended slash localpart", body: "hello @bot/evil" },
158+
{ label: "historical exclamation localpart", body: "hello @bot!evil:evil.example" },
159+
{ label: "historical percent localpart", body: "hello @bot%evil:evil.example" },
160+
{ label: "historical ampersand localpart", body: "hello @bot&evil:evil.example" },
161+
{ label: "historical question-mark localpart", body: "hello @bot?evil:evil.example" },
162+
{ label: "historical closing-bracket localpart", body: "hello @bot)evil:evil.example" },
163+
{ label: "historical Markdown localpart", body: "hello @bot**evil:evil.example" },
164+
{ label: "historical exclamation-only localpart", body: "hello @bot!" },
165+
{ label: "historical percent-only localpart", body: "hello @bot%" },
166+
{ label: "historical comma-only localpart", body: "hello @bot," },
167+
{ label: "historical period-only localpart", body: "hello @bot." },
168+
{ label: "historical parenthesis-only localpart", body: "hello @bot)" },
169+
{ label: "historical Markdown-only localpart", body: "hello @bot**" },
170+
{ label: "historical hash-only localpart", body: "hello @bot#" },
171+
{ label: "ambiguous parenthesized shorthand", body: "hello (@bot)" },
172+
{ label: "ambiguous Markdown-wrapped shorthand", body: "hello **@bot**" },
173+
{ label: "ambiguous hash-wrapped shorthand", body: "hello #@bot#" },
174+
{ label: "Matrix room-alias account collision", body: "hello #@bot:matrix.org" },
175+
{ label: "Matrix room-alias colon-command collision", body: "#@bot:matrix.org: help" },
176+
{ label: "Matrix room-ID account collision", body: "hello !@bot:matrix.org" },
177+
{ label: "Matrix event-ID account collision", body: "hello $@bot:matrix.org" },
178+
{ label: "unseparated Unicode punctuation", body: "hello (@bot),thanks" },
179+
{ label: "extended accented localpart", body: "hello @boté" },
180+
{ label: "extended CJK localpart", body: "hello @bot中" },
181+
{ label: "extended combining-mark localpart", body: "hello @bot\u0301" },
182+
{ label: "extended Unicode-numeral localpart", body: "hello @bot\u0661" },
183+
{ label: "extended Unicode-connector localpart", body: "hello @bot\u203fevil" },
184+
{ label: "extended currency-symbol localpart", body: "hello @bot€" },
185+
{ label: "extended ASCII-currency localpart", body: "hello @bot$" },
186+
{ label: "extended mathematical-symbol localpart", body: "hello @bot∑" },
187+
{ label: "extended emoji localpart", body: "hello @bot\u{1f600}" },
188+
{ label: "extended reserved emoji localpart", body: "hello @bot\u{1f02c}" },
189+
{ label: "extended flag-emoji localpart", body: "hello @bot\u{1f1fa}\u{1f1f8}" },
190+
{ label: "extended emoji-modifier localpart", body: "hello @bot\u{1f3fb}" },
191+
{ label: "extended joined-emoji localpart", body: "hello @bot\u200d\u{1f4bb}" },
192+
{ label: "extended Unicode homeserver", body: "hello @bot:matrix.orgé" },
193+
{ label: "embedded email token", body: "hello contact@bot" },
194+
{ label: "embedded opening-punctuation token", body: "hello evil(@bot" },
195+
{ label: "embedded Markdown token", body: "hello evil**@bot" },
196+
{ label: "embedded zero-width prefix", body: "hello \u200b@bot" },
197+
{ label: "embedded BOM prefix", body: "hello \ufeff@bot" },
198+
{ label: "embedded accented token", body: "hello é@bot" },
199+
{ label: "embedded CJK token", body: "hello 中@bot" },
200+
{ label: "embedded combining-mark token", body: "hello \u0301@bot" },
201+
{ label: "embedded Unicode-numeral token", body: "hello \u0661@bot" },
202+
{ label: "embedded Unicode-connector token", body: "hello \u203f@bot" },
203+
{ label: "embedded currency-symbol token", body: "hello €@bot" },
204+
{ label: "embedded mathematical-symbol token", body: "hello ∑@bot" },
205+
{ label: "embedded emoji token", body: "hello \u{1f600}@bot" },
206+
{ label: "embedded flag-emoji token", body: "hello \u{1f1fa}@bot" },
207+
{ label: "embedded emoji-modifier token", body: "hello \u{1f3fb}@bot" },
208+
{ label: "adjacent mention prefix", body: "hello @@bot" },
209+
{ label: "zero-width foreign homeserver", body: "hello @bot\u200b:evil.example" },
210+
{ label: "zero-width domain extension", body: "hello @bot:matrix.org\u200b.evil" },
211+
{ label: "bidirectional foreign homeserver", body: "hello @bot\u202e:evil.example" },
212+
{ label: "BOM foreign homeserver", body: "hello @bot\ufeff:evil.example" },
213+
{ label: "invisible combining grapheme joiner", body: "hello @bot\u034f:evil.example" },
214+
{ label: "invisible variation selector", body: "hello @bot\ufe0f:evil.example" },
215+
{ label: "invisible Hangul filler", body: "hello @bot\u3164:evil.example" },
216+
])("rejects forged native mention metadata for $label", ({ body }) => {
217+
expect(
218+
resolveMentions({
219+
content: {
220+
msgtype: "m.text",
221+
body,
222+
"m.mentions": { user_ids: [userId] },
223+
},
224+
userId,
225+
text: body,
226+
mentionRegexes: [],
227+
}),
228+
).toEqual({ wasMentioned: false, hasExplicitMention: false });
229+
});
230+
231+
it.each([
232+
...Array.from({ length: 94 }, (_, index) => String.fromCharCode(33 + index)).filter(
233+
(character) => character !== ":",
234+
),
235+
"!",
236+
"%",
237+
",",
238+
"。",
239+
"؛",
240+
"‽",
241+
"・",
242+
"、",
243+
"…",
244+
"—",
245+
"(",
246+
")",
247+
"«",
248+
"»",
249+
])("rejects historical-account continuation or prefix %s", (character) => {
250+
for (const body of [
251+
`hello @bot${character}`,
252+
`hello @bot${character}${character}`,
253+
`hello @bot${character}evil:evil.example`,
254+
`hello evil${character}@bot`,
255+
]) {
256+
expect(
257+
resolveMentions({
258+
content: {
259+
msgtype: "m.text",
260+
body,
261+
"m.mentions": { user_ids: [userId] },
262+
},
263+
userId,
264+
text: body,
265+
mentionRegexes: [],
266+
}),
267+
).toEqual({ wasMentioned: false, hasExplicitMention: false });
268+
}
269+
});
270+
271+
it("requires metadata to name the exact account even when that account is visibly mentioned", () => {
272+
const body = "hello @bot:matrix.org";
273+
274+
expect(
275+
resolveMentions({
276+
content: {
277+
msgtype: "m.text",
278+
body,
279+
"m.mentions": { user_ids: ["@bot:evil.example"] },
280+
},
281+
userId,
282+
text: body,
283+
mentionRegexes: [],
284+
}),
285+
).toEqual({ wasMentioned: false, hasExplicitMention: false });
286+
});
287+
38288
it("does not trust m.mentions.user_ids without a visible text or formatted mention", () => {
39289
const result = resolveMentions({
40290
content: {

‎extensions/matrix/src/matrix/monitor/mentions.ts‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,21 @@ function resolveMatrixUserLocalpart(userId: string): string | null {
3838
return trimmed.slice(1, colonIndex).trim() || null;
3939
}
4040

41+
function hasVisibleNativeMatrixUserMention(text: string | undefined, userId: string): boolean {
42+
const localpart = resolveMatrixUserLocalpart(userId);
43+
if (!text || !localpart) {
44+
return false;
45+
}
46+
47+
// Historical localparts can end in any punctuation, so shorthand must stay
48+
// bare; colon plus visible whitespace is safe because localparts forbid colon.
49+
const pattern = new RegExp(
50+
String.raw`(?:^|\p{White_Space})(?:${escapeRegExp(userId)}(?=$|\p{White_Space}|:\p{White_Space}|[,!?;](?=$|\p{White_Space}))|${escapeRegExp(`@${localpart}`)}(?=$|\p{White_Space}|:\p{White_Space}))`,
51+
"u",
52+
);
53+
return pattern.test(text);
54+
}
55+
4156
function resolveMatrixMentionPrefixCandidates(params: {
4257
userId?: string | null;
4358
displayName?: string | null;
@@ -216,13 +231,14 @@ export function resolveMentions(params: {
216231
mentionRegexes: params.mentionRegexes,
217232
})
218233
: false;
219-
// Matrix clients can mention users through m.mentions metadata plus a visible
220-
// Matrix URI label in formatted_body. Keep the visible-mention requirement so
221-
// hidden metadata-only mentions do not trigger the handler.
234+
// Native mentions may use visible plain-text Matrix IDs without HTML. Keep
235+
// exact metadata ownership and visibility so forged mentions stay inert.
222236
const metadataBackedUserMention = Boolean(
223237
params.userId &&
224238
mentionedUsers.has(params.userId) &&
225-
(mentionedInFormattedBody || textMentioned),
239+
(mentionedInFormattedBody ||
240+
textMentioned ||
241+
hasVisibleNativeMatrixUserMention(params.text, params.userId)),
226242
);
227243
const metadataBackedRoomMention = Boolean(mentions?.room) && visibleRoomMention;
228244
const explicitMention =

0 commit comments

Comments
 (0)