Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit 15bf93e

Browse files
committed
Validate and filter m.direct before use
1 parent e4dfb21 commit 15bf93e

File tree

4 files changed

+217
-13
lines changed

4 files changed

+217
-13
lines changed

Diff for: src/utils/DMRoomMap.ts

+9-2
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import { MatrixEvent } from "matrix-js-sdk/src/models/event";
2323
import { Optional } from "matrix-events-sdk";
2424

2525
import { MatrixClientPeg } from "../MatrixClientPeg";
26+
import { filterValidMDirect } from "./dm/filterValidMDirect";
2627

2728
/**
2829
* Class that takes a Matrix Client and flips the m.direct map
@@ -44,8 +45,14 @@ export default class DMRoomMap {
4445
// see onAccountData
4546
this.hasSentOutPatchDirectAccountDataPatch = false;
4647

47-
const mDirectEvent = matrixClient.getAccountData(EventType.Direct)?.getContent() ?? {};
48-
this.mDirectEvent = { ...mDirectEvent }; // copy as we will mutate
48+
const mDirectRawContent = matrixClient.getAccountData(EventType.Direct)?.getContent() ?? {};
49+
const { valid, filteredContent } = filterValidMDirect(mDirectRawContent);
50+
51+
if (!valid) {
52+
logger.warn("Invalid m.direct content occurred", mDirectRawContent);
53+
}
54+
55+
this.mDirectEvent = filteredContent;
4956
}
5057

5158
/**

Diff for: src/utils/dm/filterValidMDirect.ts

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
Copyright 2023 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
interface FilterValidMDirectResult {
18+
/** Whether the entire content is valid */
19+
valid: boolean;
20+
/** Filtered content with only the valid parts */
21+
filteredContent: Record<string, string[]>;
22+
}
23+
24+
/**
25+
* Filter m.direct content to be compliant to https://spec.matrix.org/v1.6/client-server-api/#mdirect.
26+
*
27+
* @param content - Raw event content to be filerted
28+
* @returns value as a flag whether to content was valid.
29+
* filteredContent with only values from the content that are spec compliant.
30+
*/
31+
export const filterValidMDirect = (content: unknown): FilterValidMDirectResult => {
32+
if (content === null || typeof content !== "object") {
33+
return {
34+
valid: false,
35+
filteredContent: {},
36+
};
37+
}
38+
39+
const filteredContent = new Map();
40+
let valid = true;
41+
42+
for (const [userId, roomIds] of Object.entries(content)) {
43+
if (typeof userId !== "string") {
44+
valid = false;
45+
continue;
46+
}
47+
48+
if (!Array.isArray(roomIds)) {
49+
valid = false;
50+
continue;
51+
}
52+
53+
const filteredRoomIds: string[] = [];
54+
filteredContent.set(userId, filteredRoomIds);
55+
roomIds.forEach((roomId: unknown) => {
56+
if (typeof roomId === "string") {
57+
filteredRoomIds.push(roomId);
58+
return;
59+
}
60+
61+
valid = false;
62+
});
63+
}
64+
65+
return {
66+
valid,
67+
filteredContent: Object.fromEntries(filteredContent.entries()),
68+
};
69+
};

Diff for: test/utils/DMRoomMap-test.ts

+62-11
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,18 @@ limitations under the License.
1515
*/
1616

1717
import { mocked, Mocked } from "jest-mock";
18-
import { EventType, IContent, MatrixClient } from "matrix-js-sdk/src/matrix";
18+
import { logger } from "matrix-js-sdk/src/logger";
19+
import { EventType, IContent, MatrixClient, MatrixEvent } from "matrix-js-sdk/src/matrix";
1920

2021
import DMRoomMap from "../../src/utils/DMRoomMap";
2122
import { mkEvent, stubClient } from "../test-utils";
22-
2323
describe("DMRoomMap", () => {
2424
const roomId1 = "!room1:example.com";
2525
const roomId2 = "!room2:example.com";
2626
const roomId3 = "!room3:example.com";
2727
const roomId4 = "!room4:example.com";
2828

29-
const mDirectContent = {
29+
const validMDirectContent = {
3030
"[email protected]": [roomId1, roomId2],
3131
"@user:example.com": [roomId1, roomId3, roomId4],
3232
"@user2:example.com": [] as string[],
@@ -35,20 +35,71 @@ describe("DMRoomMap", () => {
3535
let client: Mocked<MatrixClient>;
3636
let dmRoomMap: DMRoomMap;
3737

38+
const mkMDirectEvent = (content: any): MatrixEvent => {
39+
return mkEvent({
40+
event: true,
41+
type: EventType.Direct,
42+
user: client.getSafeUserId(),
43+
content: content,
44+
});
45+
};
46+
3847
beforeEach(() => {
3948
client = mocked(stubClient());
49+
jest.spyOn(logger, "warn");
50+
});
4051

41-
const mDirectEvent = mkEvent({
42-
event: true,
52+
describe("when m.direct has valid content", () => {
53+
beforeEach(() => {
54+
client.getAccountData.mockReturnValue(mkMDirectEvent(validMDirectContent));
55+
dmRoomMap = new DMRoomMap(client);
56+
});
57+
58+
it("getRoomIds should return the room Ids", () => {
59+
expect(dmRoomMap.getRoomIds()).toEqual(new Set([roomId1, roomId2, roomId3, roomId4]));
60+
});
61+
});
62+
63+
describe("when m.direct content contains the entire event", () => {
64+
const mDirectContentContent = {
4365
type: EventType.Direct,
44-
user: client.getSafeUserId(),
45-
content: mDirectContent,
66+
content: validMDirectContent,
67+
};
68+
69+
beforeEach(() => {
70+
client.getAccountData.mockReturnValue(mkMDirectEvent(mDirectContentContent));
71+
dmRoomMap = new DMRoomMap(client);
72+
});
73+
74+
it("should log the invalid content", () => {
75+
expect(logger.warn).toHaveBeenCalledWith("Invalid m.direct content occurred", mDirectContentContent);
76+
});
77+
78+
it("getRoomIds should return an empty list", () => {
79+
expect(dmRoomMap.getRoomIds()).toEqual(new Set([]));
4680
});
47-
client.getAccountData.mockReturnValue(mDirectEvent);
48-
dmRoomMap = new DMRoomMap(client);
4981
});
5082

51-
it("getRoomIds should return the room Ids", () => {
52-
expect(dmRoomMap.getRoomIds()).toEqual(new Set([roomId1, roomId2, roomId3, roomId4]));
83+
describe("when partially crap m.direct content appears", () => {
84+
const partiallyCrapContent = {
85+
"hello": 23,
86+
"@user1:example.com": [] as string[],
87+
"@user2:example.com": [roomId1, roomId2],
88+
"@user3:example.com": "room1, room2, room3",
89+
"@user4:example.com": [roomId4],
90+
};
91+
92+
beforeEach(() => {
93+
client.getAccountData.mockReturnValue(mkMDirectEvent(partiallyCrapContent));
94+
dmRoomMap = new DMRoomMap(client);
95+
});
96+
97+
it("should log the invalid content", () => {
98+
expect(logger.warn).toHaveBeenCalledWith("Invalid m.direct content occurred", partiallyCrapContent);
99+
});
100+
101+
it("getRoomIds should only return the valid items", () => {
102+
expect(dmRoomMap.getRoomIds()).toEqual(new Set([roomId1, roomId2, roomId4]));
103+
});
53104
});
54105
});

Diff for: test/utils/dm/filterValidMDirect-test.ts

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*
2+
Copyright 2023 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import { filterValidMDirect } from "../../../src/utils/dm/filterValidMDirect";
18+
19+
const roomId1 = "!room1:example.com";
20+
const roomId2 = "!room2:example.com";
21+
const userId1 = "@user1:example.com";
22+
const userId2 = "@user2:example.com";
23+
const userId3 = "@user3:example.com";
24+
25+
describe("filterValidMDirect", () => {
26+
it("should return an empty object as valid content", () => {
27+
expect(filterValidMDirect({})).toEqual({
28+
valid: true,
29+
filteredContent: {},
30+
});
31+
});
32+
33+
it("should return valid content", () => {
34+
expect(
35+
filterValidMDirect({
36+
[userId1]: [roomId1, roomId2],
37+
[userId2]: [roomId1],
38+
}),
39+
).toEqual({
40+
valid: true,
41+
filteredContent: {
42+
[userId1]: [roomId1, roomId2],
43+
[userId2]: [roomId1],
44+
},
45+
});
46+
});
47+
48+
it("should return an empy object for null", () => {
49+
expect(filterValidMDirect(null)).toEqual({
50+
valid: false,
51+
filteredContent: {},
52+
});
53+
});
54+
55+
it("should return an empy object for a non-object", () => {
56+
expect(filterValidMDirect(23)).toEqual({
57+
valid: false,
58+
filteredContent: {},
59+
});
60+
});
61+
62+
it("should only return valid content", () => {
63+
const invalidContent = {
64+
[userId1]: [23],
65+
[userId2]: [roomId2],
66+
[userId3]: "room1",
67+
};
68+
69+
expect(filterValidMDirect(invalidContent)).toEqual({
70+
valid: false,
71+
filteredContent: {
72+
[userId1]: [],
73+
[userId2]: [roomId2],
74+
},
75+
});
76+
});
77+
});

0 commit comments

Comments
 (0)