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

Commit 7ae5599

Browse files
authored
Fix checking whether a room can be published on creation. (#11392)
If `room_list_publication_rules` was configured with a rule with a non-wildcard alias and a room was created with an alias then an internal server error would have been thrown. This fixes the error and properly applies the publication rules during room creation.
1 parent 4d6d38a commit 7ae5599

File tree

4 files changed

+95
-56
lines changed

4 files changed

+95
-56
lines changed

changelog.d/11392.bugfix

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a bug introduced in v1.13.0 where creating and publishing a room could cause errors if `room_list_publication_rules` is configured.

synapse/config/room_directory.py

Lines changed: 28 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Copyright 2018 New Vector Ltd
2+
# Copyright 2021 Matrix.org Foundation C.I.C.
23
#
34
# Licensed under the Apache License, Version 2.0 (the "License");
45
# you may not use this file except in compliance with the License.
@@ -12,6 +13,9 @@
1213
# See the License for the specific language governing permissions and
1314
# limitations under the License.
1415

16+
from typing import List
17+
18+
from synapse.types import JsonDict
1519
from synapse.util import glob_to_regex
1620

1721
from ._base import Config, ConfigError
@@ -20,7 +24,7 @@
2024
class RoomDirectoryConfig(Config):
2125
section = "roomdirectory"
2226

23-
def read_config(self, config, **kwargs):
27+
def read_config(self, config, **kwargs) -> None:
2428
self.enable_room_list_search = config.get("enable_room_list_search", True)
2529

2630
alias_creation_rules = config.get("alias_creation_rules")
@@ -47,7 +51,7 @@ def read_config(self, config, **kwargs):
4751
_RoomDirectoryRule("room_list_publication_rules", {"action": "allow"})
4852
]
4953

50-
def generate_config_section(self, config_dir_path, server_name, **kwargs):
54+
def generate_config_section(self, config_dir_path, server_name, **kwargs) -> str:
5155
return """
5256
# Uncomment to disable searching the public room list. When disabled
5357
# blocks searching local and remote room lists for local and remote
@@ -113,33 +117,35 @@ def generate_config_section(self, config_dir_path, server_name, **kwargs):
113117
# action: allow
114118
"""
115119

116-
def is_alias_creation_allowed(self, user_id, room_id, alias):
120+
def is_alias_creation_allowed(self, user_id: str, room_id: str, alias: str) -> bool:
117121
"""Checks if the given user is allowed to create the given alias
118122
119123
Args:
120-
user_id (str)
121-
room_id (str)
122-
alias (str)
124+
user_id: The user to check.
125+
room_id: The room ID for the alias.
126+
alias: The alias being created.
123127
124128
Returns:
125-
boolean: True if user is allowed to create the alias
129+
True if user is allowed to create the alias
126130
"""
127131
for rule in self._alias_creation_rules:
128132
if rule.matches(user_id, room_id, [alias]):
129133
return rule.action == "allow"
130134

131135
return False
132136

133-
def is_publishing_room_allowed(self, user_id, room_id, aliases):
137+
def is_publishing_room_allowed(
138+
self, user_id: str, room_id: str, aliases: List[str]
139+
) -> bool:
134140
"""Checks if the given user is allowed to publish the room
135141
136142
Args:
137-
user_id (str)
138-
room_id (str)
139-
aliases (list[str]): any local aliases associated with the room
143+
user_id: The user ID publishing the room.
144+
room_id: The room being published.
145+
aliases: any local aliases associated with the room
140146
141147
Returns:
142-
boolean: True if user can publish room
148+
True if user can publish room
143149
"""
144150
for rule in self._room_list_publication_rules:
145151
if rule.matches(user_id, room_id, aliases):
@@ -153,11 +159,11 @@ class _RoomDirectoryRule:
153159
creating an alias or publishing a room.
154160
"""
155161

156-
def __init__(self, option_name, rule):
162+
def __init__(self, option_name: str, rule: JsonDict):
157163
"""
158164
Args:
159-
option_name (str): Name of the config option this rule belongs to
160-
rule (dict): The rule as specified in the config
165+
option_name: Name of the config option this rule belongs to
166+
rule: The rule as specified in the config
161167
"""
162168

163169
action = rule["action"]
@@ -181,18 +187,18 @@ def __init__(self, option_name, rule):
181187
except Exception as e:
182188
raise ConfigError("Failed to parse glob into regex") from e
183189

184-
def matches(self, user_id, room_id, aliases):
190+
def matches(self, user_id: str, room_id: str, aliases: List[str]) -> bool:
185191
"""Tests if this rule matches the given user_id, room_id and aliases.
186192
187193
Args:
188-
user_id (str)
189-
room_id (str)
190-
aliases (list[str]): The associated aliases to the room. Will be a
191-
single element for testing alias creation, and can be empty for
192-
testing room publishing.
194+
user_id: The user ID to check.
195+
room_id: The room ID to check.
196+
aliases: The associated aliases to the room. Will be a single element
197+
for testing alias creation, and can be empty for testing room
198+
publishing.
193199
194200
Returns:
195-
boolean
201+
True if the rule matches.
196202
"""
197203

198204
# Note: The regexes are anchored at both ends

synapse/handlers/room.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -775,8 +775,11 @@ async def create_room(
775775
raise SynapseError(403, "Room visibility value not allowed.")
776776

777777
if is_public:
778+
room_aliases = []
779+
if room_alias:
780+
room_aliases.append(room_alias.to_string())
778781
if not self.config.roomdirectory.is_publishing_room_allowed(
779-
user_id, room_id, room_alias
782+
user_id, room_id, room_aliases
780783
):
781784
# Let's just return a generic message, as there may be all sorts of
782785
# reasons why we said no. TODO: Allow configurable error messages

tests/handlers/test_directory.py

Lines changed: 62 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Copyright 2014-2016 OpenMarket Ltd
2+
# Copyright 2021 Matrix.org Foundation C.I.C.
23
#
34
# Licensed under the Apache License, Version 2.0 (the "License");
45
# you may not use this file except in compliance with the License.
@@ -12,13 +13,11 @@
1213
# See the License for the specific language governing permissions and
1314
# limitations under the License.
1415

15-
1616
from unittest.mock import Mock
1717

1818
import synapse.api.errors
1919
import synapse.rest.admin
2020
from synapse.api.constants import EventTypes
21-
from synapse.config.room_directory import RoomDirectoryConfig
2221
from synapse.rest.client import directory, login, room
2322
from synapse.types import RoomAlias, create_requester
2423

@@ -394,30 +393,23 @@ class TestCreateAliasACL(unittest.HomeserverTestCase):
394393

395394
servlets = [directory.register_servlets, room.register_servlets]
396395

397-
def prepare(self, reactor, clock, hs):
398-
# We cheekily override the config to add custom alias creation rules
399-
config = {}
396+
def default_config(self):
397+
config = super().default_config()
398+
399+
# Add custom alias creation rules to the config.
400400
config["alias_creation_rules"] = [
401401
{"user_id": "*", "alias": "#unofficial_*", "action": "allow"}
402402
]
403-
config["room_list_publication_rules"] = []
404403

405-
rd_config = RoomDirectoryConfig()
406-
rd_config.read_config(config)
407-
408-
self.hs.config.roomdirectory.is_alias_creation_allowed = (
409-
rd_config.is_alias_creation_allowed
410-
)
411-
412-
return hs
404+
return config
413405

414406
def test_denied(self):
415407
room_id = self.helper.create_room_as(self.user_id)
416408

417409
channel = self.make_request(
418410
"PUT",
419411
b"directory/room/%23test%3Atest",
420-
('{"room_id":"%s"}' % (room_id,)).encode("ascii"),
412+
{"room_id": room_id},
421413
)
422414
self.assertEquals(403, channel.code, channel.result)
423415

@@ -427,14 +419,35 @@ def test_allowed(self):
427419
channel = self.make_request(
428420
"PUT",
429421
b"directory/room/%23unofficial_test%3Atest",
430-
('{"room_id":"%s"}' % (room_id,)).encode("ascii"),
422+
{"room_id": room_id},
431423
)
432424
self.assertEquals(200, channel.code, channel.result)
433425

426+
def test_denied_during_creation(self):
427+
"""A room alias that is not allowed should be rejected during creation."""
428+
# Invalid room alias.
429+
self.helper.create_room_as(
430+
self.user_id,
431+
expect_code=403,
432+
extra_content={"room_alias_name": "foo"},
433+
)
434434

435-
class TestCreatePublishedRoomACL(unittest.HomeserverTestCase):
436-
data = {"room_alias_name": "unofficial_test"}
435+
def test_allowed_during_creation(self):
436+
"""A valid room alias should be allowed during creation."""
437+
room_id = self.helper.create_room_as(
438+
self.user_id,
439+
extra_content={"room_alias_name": "unofficial_test"},
440+
)
437441

442+
channel = self.make_request(
443+
"GET",
444+
b"directory/room/%23unofficial_test%3Atest",
445+
)
446+
self.assertEquals(200, channel.code, channel.result)
447+
self.assertEquals(channel.json_body["room_id"], room_id)
448+
449+
450+
class TestCreatePublishedRoomACL(unittest.HomeserverTestCase):
438451
servlets = [
439452
synapse.rest.admin.register_servlets_for_client_rest_resource,
440453
login.register_servlets,
@@ -443,27 +456,30 @@ class TestCreatePublishedRoomACL(unittest.HomeserverTestCase):
443456
]
444457
hijack_auth = False
445458

446-
def prepare(self, reactor, clock, hs):
447-
self.allowed_user_id = self.register_user("allowed", "pass")
448-
self.allowed_access_token = self.login("allowed", "pass")
459+
data = {"room_alias_name": "unofficial_test"}
460+
allowed_localpart = "allowed"
449461

450-
self.denied_user_id = self.register_user("denied", "pass")
451-
self.denied_access_token = self.login("denied", "pass")
462+
def default_config(self):
463+
config = super().default_config()
452464

453-
# This time we add custom room list publication rules
454-
config = {}
455-
config["alias_creation_rules"] = []
465+
# Add custom room list publication rules to the config.
456466
config["room_list_publication_rules"] = [
467+
{
468+
"user_id": "@" + self.allowed_localpart + "*",
469+
"alias": "#unofficial_*",
470+
"action": "allow",
471+
},
457472
{"user_id": "*", "alias": "*", "action": "deny"},
458-
{"user_id": self.allowed_user_id, "alias": "*", "action": "allow"},
459473
]
460474

461-
rd_config = RoomDirectoryConfig()
462-
rd_config.read_config(config)
475+
return config
463476

464-
self.hs.config.roomdirectory.is_publishing_room_allowed = (
465-
rd_config.is_publishing_room_allowed
466-
)
477+
def prepare(self, reactor, clock, hs):
478+
self.allowed_user_id = self.register_user(self.allowed_localpart, "pass")
479+
self.allowed_access_token = self.login(self.allowed_localpart, "pass")
480+
481+
self.denied_user_id = self.register_user("denied", "pass")
482+
self.denied_access_token = self.login("denied", "pass")
467483

468484
return hs
469485

@@ -505,10 +521,23 @@ def test_allowed_with_publication_permission(self):
505521
self.allowed_user_id,
506522
tok=self.allowed_access_token,
507523
extra_content=self.data,
508-
is_public=False,
524+
is_public=True,
509525
expect_code=200,
510526
)
511527

528+
def test_denied_publication_with_invalid_alias(self):
529+
"""
530+
Try to create a room, register an alias for it, and publish it,
531+
as a user WITH permission to publish rooms.
532+
"""
533+
self.helper.create_room_as(
534+
self.allowed_user_id,
535+
tok=self.allowed_access_token,
536+
extra_content={"room_alias_name": "foo"},
537+
is_public=True,
538+
expect_code=403,
539+
)
540+
512541
def test_can_create_as_private_room_after_rejection(self):
513542
"""
514543
After failing to publish a room with an alias as a user without publish permission,

0 commit comments

Comments
 (0)