test_utils.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the 'License');
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an 'AS IS' BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import unittest as stdlib_unittest
  15. from typing import Any, List, Mapping, Optional
  16. from synapse.api.constants import EventContentFields
  17. from synapse.api.room_versions import RoomVersions
  18. from synapse.events import EventBase, make_event_from_dict
  19. from synapse.events.utils import (
  20. PowerLevelsContent,
  21. SerializeEventConfig,
  22. copy_and_fixup_power_levels_contents,
  23. maybe_upsert_event_field,
  24. prune_event,
  25. serialize_event,
  26. )
  27. from synapse.types import JsonDict
  28. from synapse.util.frozenutils import freeze
  29. def MockEvent(**kwargs: Any) -> EventBase:
  30. if "event_id" not in kwargs:
  31. kwargs["event_id"] = "fake_event_id"
  32. if "type" not in kwargs:
  33. kwargs["type"] = "fake_type"
  34. if "content" not in kwargs:
  35. kwargs["content"] = {}
  36. return make_event_from_dict(kwargs)
  37. class TestMaybeUpsertEventField(stdlib_unittest.TestCase):
  38. def test_update_okay(self) -> None:
  39. event = make_event_from_dict({"event_id": "$1234"})
  40. success = maybe_upsert_event_field(event, event.unsigned, "key", "value")
  41. self.assertTrue(success)
  42. self.assertEqual(event.unsigned["key"], "value")
  43. def test_update_not_okay(self) -> None:
  44. event = make_event_from_dict({"event_id": "$1234"})
  45. LARGE_STRING = "a" * 100_000
  46. success = maybe_upsert_event_field(event, event.unsigned, "key", LARGE_STRING)
  47. self.assertFalse(success)
  48. self.assertNotIn("key", event.unsigned)
  49. def test_update_not_okay_leaves_original_value(self) -> None:
  50. event = make_event_from_dict(
  51. {"event_id": "$1234", "unsigned": {"key": "value"}}
  52. )
  53. LARGE_STRING = "a" * 100_000
  54. success = maybe_upsert_event_field(event, event.unsigned, "key", LARGE_STRING)
  55. self.assertFalse(success)
  56. self.assertEqual(event.unsigned["key"], "value")
  57. class PruneEventTestCase(stdlib_unittest.TestCase):
  58. def run_test(self, evdict: JsonDict, matchdict: JsonDict, **kwargs: Any) -> None:
  59. """
  60. Asserts that a new event constructed with `evdict` will look like
  61. `matchdict` when it is redacted.
  62. Args:
  63. evdict: The dictionary to build the event from.
  64. matchdict: The expected resulting dictionary.
  65. kwargs: Additional keyword arguments used to create the event.
  66. """
  67. self.assertEqual(
  68. prune_event(make_event_from_dict(evdict, **kwargs)).get_dict(), matchdict
  69. )
  70. def test_minimal(self) -> None:
  71. self.run_test(
  72. {"type": "A", "event_id": "$test:domain"},
  73. {
  74. "type": "A",
  75. "event_id": "$test:domain",
  76. "content": {},
  77. "signatures": {},
  78. "unsigned": {},
  79. },
  80. )
  81. def test_basic_keys(self) -> None:
  82. """Ensure that the keys that should be untouched are kept."""
  83. # Note that some of the values below don't really make sense, but the
  84. # pruning of events doesn't worry about the values of any fields (with
  85. # the exception of the content field).
  86. self.run_test(
  87. {
  88. "event_id": "$3:domain",
  89. "type": "A",
  90. "room_id": "!1:domain",
  91. "sender": "@2:domain",
  92. "state_key": "B",
  93. "content": {"other_key": "foo"},
  94. "hashes": "hashes",
  95. "signatures": {"domain": {"algo:1": "sigs"}},
  96. "depth": 4,
  97. "prev_events": "prev_events",
  98. "prev_state": "prev_state",
  99. "auth_events": "auth_events",
  100. "origin": "domain",
  101. "origin_server_ts": 1234,
  102. "membership": "join",
  103. # Also include a key that should be removed.
  104. "other_key": "foo",
  105. },
  106. {
  107. "event_id": "$3:domain",
  108. "type": "A",
  109. "room_id": "!1:domain",
  110. "sender": "@2:domain",
  111. "state_key": "B",
  112. "hashes": "hashes",
  113. "depth": 4,
  114. "prev_events": "prev_events",
  115. "prev_state": "prev_state",
  116. "auth_events": "auth_events",
  117. "origin": "domain",
  118. "origin_server_ts": 1234,
  119. "membership": "join",
  120. "content": {},
  121. "signatures": {"domain": {"algo:1": "sigs"}},
  122. "unsigned": {},
  123. },
  124. )
  125. # As of MSC2176 we now redact the membership and prev_states keys.
  126. self.run_test(
  127. {"type": "A", "prev_state": "prev_state", "membership": "join"},
  128. {"type": "A", "content": {}, "signatures": {}, "unsigned": {}},
  129. room_version=RoomVersions.MSC2176,
  130. )
  131. def test_unsigned(self) -> None:
  132. """Ensure that unsigned properties get stripped (except age_ts and replaces_state)."""
  133. self.run_test(
  134. {
  135. "type": "B",
  136. "event_id": "$test:domain",
  137. "unsigned": {
  138. "age_ts": 20,
  139. "replaces_state": "$test2:domain",
  140. "other_key": "foo",
  141. },
  142. },
  143. {
  144. "type": "B",
  145. "event_id": "$test:domain",
  146. "content": {},
  147. "signatures": {},
  148. "unsigned": {"age_ts": 20, "replaces_state": "$test2:domain"},
  149. },
  150. )
  151. def test_content(self) -> None:
  152. """The content dictionary should be stripped in most cases."""
  153. self.run_test(
  154. {"type": "C", "event_id": "$test:domain", "content": {"things": "here"}},
  155. {
  156. "type": "C",
  157. "event_id": "$test:domain",
  158. "content": {},
  159. "signatures": {},
  160. "unsigned": {},
  161. },
  162. )
  163. # Some events keep a single content key/value.
  164. EVENT_KEEP_CONTENT_KEYS = [
  165. ("member", "membership", "join"),
  166. ("join_rules", "join_rule", "invite"),
  167. ("history_visibility", "history_visibility", "shared"),
  168. ]
  169. for event_type, key, value in EVENT_KEEP_CONTENT_KEYS:
  170. self.run_test(
  171. {
  172. "type": "m.room." + event_type,
  173. "event_id": "$test:domain",
  174. "content": {key: value, "other_key": "foo"},
  175. },
  176. {
  177. "type": "m.room." + event_type,
  178. "event_id": "$test:domain",
  179. "content": {key: value},
  180. "signatures": {},
  181. "unsigned": {},
  182. },
  183. )
  184. def test_create(self) -> None:
  185. """Create events are partially redacted until MSC2176."""
  186. self.run_test(
  187. {
  188. "type": "m.room.create",
  189. "event_id": "$test:domain",
  190. "content": {"creator": "@2:domain", "other_key": "foo"},
  191. },
  192. {
  193. "type": "m.room.create",
  194. "event_id": "$test:domain",
  195. "content": {"creator": "@2:domain"},
  196. "signatures": {},
  197. "unsigned": {},
  198. },
  199. )
  200. # After MSC2176, create events get nothing redacted.
  201. self.run_test(
  202. {"type": "m.room.create", "content": {"not_a_real_key": True}},
  203. {
  204. "type": "m.room.create",
  205. "content": {"not_a_real_key": True},
  206. "signatures": {},
  207. "unsigned": {},
  208. },
  209. room_version=RoomVersions.MSC2176,
  210. )
  211. def test_power_levels(self) -> None:
  212. """Power level events keep a variety of content keys."""
  213. self.run_test(
  214. {
  215. "type": "m.room.power_levels",
  216. "event_id": "$test:domain",
  217. "content": {
  218. "ban": 1,
  219. "events": {"m.room.name": 100},
  220. "events_default": 2,
  221. "invite": 3,
  222. "kick": 4,
  223. "redact": 5,
  224. "state_default": 6,
  225. "users": {"@admin:domain": 100},
  226. "users_default": 7,
  227. "other_key": 8,
  228. },
  229. },
  230. {
  231. "type": "m.room.power_levels",
  232. "event_id": "$test:domain",
  233. "content": {
  234. "ban": 1,
  235. "events": {"m.room.name": 100},
  236. "events_default": 2,
  237. # Note that invite is not here.
  238. "kick": 4,
  239. "redact": 5,
  240. "state_default": 6,
  241. "users": {"@admin:domain": 100},
  242. "users_default": 7,
  243. },
  244. "signatures": {},
  245. "unsigned": {},
  246. },
  247. )
  248. # After MSC2176, power levels events keep the invite key.
  249. self.run_test(
  250. {"type": "m.room.power_levels", "content": {"invite": 75}},
  251. {
  252. "type": "m.room.power_levels",
  253. "content": {"invite": 75},
  254. "signatures": {},
  255. "unsigned": {},
  256. },
  257. room_version=RoomVersions.MSC2176,
  258. )
  259. def test_alias_event(self) -> None:
  260. """Alias events have special behavior up through room version 6."""
  261. self.run_test(
  262. {
  263. "type": "m.room.aliases",
  264. "event_id": "$test:domain",
  265. "content": {"aliases": ["test"]},
  266. },
  267. {
  268. "type": "m.room.aliases",
  269. "event_id": "$test:domain",
  270. "content": {"aliases": ["test"]},
  271. "signatures": {},
  272. "unsigned": {},
  273. },
  274. )
  275. # After MSC2432, alias events have no special behavior.
  276. self.run_test(
  277. {"type": "m.room.aliases", "content": {"aliases": ["test"]}},
  278. {
  279. "type": "m.room.aliases",
  280. "content": {},
  281. "signatures": {},
  282. "unsigned": {},
  283. },
  284. room_version=RoomVersions.V6,
  285. )
  286. def test_redacts(self) -> None:
  287. """Redaction events have no special behaviour until MSC2174/MSC2176."""
  288. self.run_test(
  289. {"type": "m.room.redaction", "content": {"redacts": "$test2:domain"}},
  290. {
  291. "type": "m.room.redaction",
  292. "content": {},
  293. "signatures": {},
  294. "unsigned": {},
  295. },
  296. room_version=RoomVersions.V6,
  297. )
  298. # After MSC2174, redaction events keep the redacts content key.
  299. self.run_test(
  300. {"type": "m.room.redaction", "content": {"redacts": "$test2:domain"}},
  301. {
  302. "type": "m.room.redaction",
  303. "content": {"redacts": "$test2:domain"},
  304. "signatures": {},
  305. "unsigned": {},
  306. },
  307. room_version=RoomVersions.MSC2176,
  308. )
  309. def test_join_rules(self) -> None:
  310. """Join rules events have changed behavior starting with MSC3083."""
  311. self.run_test(
  312. {
  313. "type": "m.room.join_rules",
  314. "event_id": "$test:domain",
  315. "content": {
  316. "join_rule": "invite",
  317. "allow": [],
  318. "other_key": "stripped",
  319. },
  320. },
  321. {
  322. "type": "m.room.join_rules",
  323. "event_id": "$test:domain",
  324. "content": {"join_rule": "invite"},
  325. "signatures": {},
  326. "unsigned": {},
  327. },
  328. )
  329. # After MSC3083, the allow key is protected from redaction.
  330. self.run_test(
  331. {
  332. "type": "m.room.join_rules",
  333. "content": {
  334. "join_rule": "invite",
  335. "allow": [],
  336. "other_key": "stripped",
  337. },
  338. },
  339. {
  340. "type": "m.room.join_rules",
  341. "content": {
  342. "join_rule": "invite",
  343. "allow": [],
  344. },
  345. "signatures": {},
  346. "unsigned": {},
  347. },
  348. room_version=RoomVersions.V8,
  349. )
  350. def test_member(self) -> None:
  351. """Member events have changed behavior starting with MSC3375."""
  352. self.run_test(
  353. {
  354. "type": "m.room.member",
  355. "event_id": "$test:domain",
  356. "content": {
  357. "membership": "join",
  358. EventContentFields.AUTHORISING_USER: "@user:domain",
  359. "other_key": "stripped",
  360. },
  361. },
  362. {
  363. "type": "m.room.member",
  364. "event_id": "$test:domain",
  365. "content": {"membership": "join"},
  366. "signatures": {},
  367. "unsigned": {},
  368. },
  369. )
  370. # After MSC3375, the join_authorised_via_users_server key is protected
  371. # from redaction.
  372. self.run_test(
  373. {
  374. "type": "m.room.member",
  375. "content": {
  376. "membership": "join",
  377. EventContentFields.AUTHORISING_USER: "@user:domain",
  378. "other_key": "stripped",
  379. },
  380. },
  381. {
  382. "type": "m.room.member",
  383. "content": {
  384. "membership": "join",
  385. EventContentFields.AUTHORISING_USER: "@user:domain",
  386. },
  387. "signatures": {},
  388. "unsigned": {},
  389. },
  390. room_version=RoomVersions.V9,
  391. )
  392. class SerializeEventTestCase(stdlib_unittest.TestCase):
  393. def serialize(self, ev: EventBase, fields: Optional[List[str]]) -> JsonDict:
  394. return serialize_event(
  395. ev, 1479807801915, config=SerializeEventConfig(only_event_fields=fields)
  396. )
  397. def test_event_fields_works_with_keys(self) -> None:
  398. self.assertEqual(
  399. self.serialize(
  400. MockEvent(sender="@alice:localhost", room_id="!foo:bar"), ["room_id"]
  401. ),
  402. {"room_id": "!foo:bar"},
  403. )
  404. def test_event_fields_works_with_nested_keys(self) -> None:
  405. self.assertEqual(
  406. self.serialize(
  407. MockEvent(
  408. sender="@alice:localhost",
  409. room_id="!foo:bar",
  410. content={"body": "A message"},
  411. ),
  412. ["content.body"],
  413. ),
  414. {"content": {"body": "A message"}},
  415. )
  416. def test_event_fields_works_with_dot_keys(self) -> None:
  417. self.assertEqual(
  418. self.serialize(
  419. MockEvent(
  420. sender="@alice:localhost",
  421. room_id="!foo:bar",
  422. content={"key.with.dots": {}},
  423. ),
  424. [r"content.key\.with\.dots"],
  425. ),
  426. {"content": {"key.with.dots": {}}},
  427. )
  428. def test_event_fields_works_with_nested_dot_keys(self) -> None:
  429. self.assertEqual(
  430. self.serialize(
  431. MockEvent(
  432. sender="@alice:localhost",
  433. room_id="!foo:bar",
  434. content={
  435. "not_me": 1,
  436. "nested.dot.key": {"leaf.key": 42, "not_me_either": 1},
  437. },
  438. ),
  439. [r"content.nested\.dot\.key.leaf\.key"],
  440. ),
  441. {"content": {"nested.dot.key": {"leaf.key": 42}}},
  442. )
  443. def test_event_fields_nops_with_unknown_keys(self) -> None:
  444. self.assertEqual(
  445. self.serialize(
  446. MockEvent(
  447. sender="@alice:localhost",
  448. room_id="!foo:bar",
  449. content={"foo": "bar"},
  450. ),
  451. ["content.foo", "content.notexists"],
  452. ),
  453. {"content": {"foo": "bar"}},
  454. )
  455. def test_event_fields_nops_with_non_dict_keys(self) -> None:
  456. self.assertEqual(
  457. self.serialize(
  458. MockEvent(
  459. sender="@alice:localhost",
  460. room_id="!foo:bar",
  461. content={"foo": ["I", "am", "an", "array"]},
  462. ),
  463. ["content.foo.am"],
  464. ),
  465. {},
  466. )
  467. def test_event_fields_nops_with_array_keys(self) -> None:
  468. self.assertEqual(
  469. self.serialize(
  470. MockEvent(
  471. sender="@alice:localhost",
  472. room_id="!foo:bar",
  473. content={"foo": ["I", "am", "an", "array"]},
  474. ),
  475. ["content.foo.1"],
  476. ),
  477. {},
  478. )
  479. def test_event_fields_all_fields_if_empty(self) -> None:
  480. self.assertEqual(
  481. self.serialize(
  482. MockEvent(
  483. type="foo",
  484. event_id="test",
  485. room_id="!foo:bar",
  486. content={"foo": "bar"},
  487. ),
  488. [],
  489. ),
  490. {
  491. "type": "foo",
  492. "event_id": "test",
  493. "room_id": "!foo:bar",
  494. "content": {"foo": "bar"},
  495. "unsigned": {},
  496. },
  497. )
  498. def test_event_fields_fail_if_fields_not_str(self) -> None:
  499. with self.assertRaises(TypeError):
  500. self.serialize(
  501. MockEvent(room_id="!foo:bar", content={"foo": "bar"}), ["room_id", 4] # type: ignore[list-item]
  502. )
  503. class CopyPowerLevelsContentTestCase(stdlib_unittest.TestCase):
  504. def setUp(self) -> None:
  505. self.test_content: PowerLevelsContent = {
  506. "ban": 50,
  507. "events": {"m.room.name": 100, "m.room.power_levels": 100},
  508. "events_default": 0,
  509. "invite": 50,
  510. "kick": 50,
  511. "notifications": {"room": 20},
  512. "redact": 50,
  513. "state_default": 50,
  514. "users": {"@example:localhost": 100},
  515. "users_default": 0,
  516. }
  517. def _test(self, input: PowerLevelsContent) -> None:
  518. a = copy_and_fixup_power_levels_contents(input)
  519. self.assertEqual(a["ban"], 50)
  520. assert isinstance(a["events"], Mapping)
  521. self.assertEqual(a["events"]["m.room.name"], 100)
  522. # make sure that changing the copy changes the copy and not the orig
  523. a["ban"] = 10
  524. a["events"]["m.room.power_levels"] = 20
  525. self.assertEqual(input["ban"], 50)
  526. assert isinstance(input["events"], Mapping)
  527. self.assertEqual(input["events"]["m.room.power_levels"], 100)
  528. def test_unfrozen(self) -> None:
  529. self._test(self.test_content)
  530. def test_frozen(self) -> None:
  531. input = freeze(self.test_content)
  532. self._test(input)
  533. def test_stringy_integers(self) -> None:
  534. """String representations of decimal integers are converted to integers."""
  535. input: PowerLevelsContent = {
  536. "a": "100",
  537. "b": {
  538. "foo": 99,
  539. "bar": "-98",
  540. },
  541. "d": "0999",
  542. }
  543. output = copy_and_fixup_power_levels_contents(input)
  544. expected_output = {
  545. "a": 100,
  546. "b": {
  547. "foo": 99,
  548. "bar": -98,
  549. },
  550. "d": 999,
  551. }
  552. self.assertEqual(output, expected_output)
  553. def test_strings_that_dont_represent_decimal_integers(self) -> None:
  554. """Should raise when given inputs `s` for which `int(s, base=10)` raises."""
  555. for invalid_string in ["0x123", "123.0", "123.45", "hello", "0b1", "0o777"]:
  556. with self.assertRaises(TypeError):
  557. copy_and_fixup_power_levels_contents({"a": invalid_string})
  558. def test_invalid_types_raise_type_error(self) -> None:
  559. with self.assertRaises(TypeError):
  560. copy_and_fixup_power_levels_contents({"a": ["hello", "grandma"]}) # type: ignore[dict-item]
  561. copy_and_fixup_power_levels_contents({"a": None}) # type: ignore[dict-item]
  562. def test_invalid_nesting_raises_type_error(self) -> None:
  563. with self.assertRaises(TypeError):
  564. copy_and_fixup_power_levels_contents({"a": {"b": {"c": 1}}}) # type: ignore[dict-item]