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

Commit ba2608e

Browse files
authored
Add m.direct filter / validation (#10436)
1 parent e5f06df commit ba2608e

File tree

4 files changed

+266
-14
lines changed

4 files changed

+266
-14
lines changed

src/utils/DMRoomMap.ts

+23-3
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,8 @@ 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+
this.setMDirectFromContent(mDirectRawContent);
4950
}
5051

5152
/**
@@ -84,9 +85,28 @@ export default class DMRoomMap {
8485
this.matrixClient.removeListener(ClientEvent.AccountData, this.onAccountData);
8586
}
8687

88+
/**
89+
* Filter m.direct content to contain only valid data and then sets it.
90+
* Logs if invalid m.direct content occurs.
91+
* {@link filterValidMDirect}
92+
*
93+
* @param content - Raw m.direct content
94+
*/
95+
private setMDirectFromContent(content: unknown): void {
96+
const { valid, filteredContent } = filterValidMDirect(content);
97+
98+
if (!valid) {
99+
logger.warn("Invalid m.direct content occurred", content);
100+
}
101+
102+
this.mDirectEvent = filteredContent;
103+
}
104+
87105
private onAccountData = (ev: MatrixEvent): void => {
106+
console.log("onAccountData");
107+
88108
if (ev.getType() == EventType.Direct) {
89-
this.mDirectEvent = { ...ev.getContent() }; // copy as we will mutate
109+
this.setMDirectFromContent(ev.getContent());
90110
this.userToRooms = null;
91111
this.roomToUser = null;
92112
}

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+
56+
for (const roomId of roomIds) {
57+
if (typeof roomId === "string") {
58+
filteredRoomIds.push(roomId);
59+
} else {
60+
valid = false;
61+
}
62+
}
63+
}
64+
65+
return {
66+
valid,
67+
filteredContent: Object.fromEntries(filteredContent.entries()),
68+
};
69+
};

test/utils/DMRoomMap-test.ts

+97-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 { ClientEvent, 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,106 @@ 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+
dmRoomMap.start();
57+
});
58+
59+
it("getRoomIds should return the room Ids", () => {
60+
expect(dmRoomMap.getRoomIds()).toEqual(new Set([roomId1, roomId2, roomId3, roomId4]));
61+
});
62+
63+
describe("and there is an update with valid data", () => {
64+
beforeEach(() => {
65+
client.emit(
66+
ClientEvent.AccountData,
67+
mkMDirectEvent({
68+
"@user:example.com": [roomId1, roomId3],
69+
}),
70+
);
71+
});
72+
73+
it("getRoomIds should return the new room Ids", () => {
74+
expect(dmRoomMap.getRoomIds()).toEqual(new Set([roomId1, roomId3]));
75+
});
76+
});
77+
78+
describe("and there is an update with invalid data", () => {
79+
const partiallyInvalidContent = {
80+
"@user1:example.com": [roomId1, roomId3],
81+
"@user2:example.com": "room2, room3",
82+
};
83+
84+
beforeEach(() => {
85+
client.emit(ClientEvent.AccountData, mkMDirectEvent(partiallyInvalidContent));
86+
});
87+
88+
it("getRoomIds should return the valid room Ids", () => {
89+
expect(dmRoomMap.getRoomIds()).toEqual(new Set([roomId1, roomId3]));
90+
});
91+
92+
it("should log the invalid content", () => {
93+
expect(logger.warn).toHaveBeenCalledWith("Invalid m.direct content occurred", partiallyInvalidContent);
94+
});
95+
});
96+
});
97+
98+
describe("when m.direct content contains the entire event", () => {
99+
const mDirectContentContent = {
43100
type: EventType.Direct,
44-
user: client.getSafeUserId(),
45-
content: mDirectContent,
101+
content: validMDirectContent,
102+
};
103+
104+
beforeEach(() => {
105+
client.getAccountData.mockReturnValue(mkMDirectEvent(mDirectContentContent));
106+
dmRoomMap = new DMRoomMap(client);
107+
});
108+
109+
it("should log the invalid content", () => {
110+
expect(logger.warn).toHaveBeenCalledWith("Invalid m.direct content occurred", mDirectContentContent);
111+
});
112+
113+
it("getRoomIds should return an empty list", () => {
114+
expect(dmRoomMap.getRoomIds()).toEqual(new Set([]));
46115
});
47-
client.getAccountData.mockReturnValue(mDirectEvent);
48-
dmRoomMap = new DMRoomMap(client);
49116
});
50117

51-
it("getRoomIds should return the room Ids", () => {
52-
expect(dmRoomMap.getRoomIds()).toEqual(new Set([roomId1, roomId2, roomId3, roomId4]));
118+
describe("when partially crap m.direct content appears", () => {
119+
const partiallyCrapContent = {
120+
"hello": 23,
121+
"@user1:example.com": [] as string[],
122+
"@user2:example.com": [roomId1, roomId2],
123+
"@user3:example.com": "room1, room2, room3",
124+
"@user4:example.com": [roomId4],
125+
};
126+
127+
beforeEach(() => {
128+
client.getAccountData.mockReturnValue(mkMDirectEvent(partiallyCrapContent));
129+
dmRoomMap = new DMRoomMap(client);
130+
});
131+
132+
it("should log the invalid content", () => {
133+
expect(logger.warn).toHaveBeenCalledWith("Invalid m.direct content occurred", partiallyCrapContent);
134+
});
135+
136+
it("getRoomIds should only return the valid items", () => {
137+
expect(dmRoomMap.getRoomIds()).toEqual(new Set([roomId1, roomId2, roomId4]));
138+
});
53139
});
54140
});
+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)