Allow guest access for application services proxing /rtc/transports and /rtc/livekit/* (#20299)

This enables guest access on `/rtc/transports` and `/rtc/livekit/*`
(which is only proxied through application services) as per the
MatrixRTC MSCs.

This pull request can be reviewed by commit.

Follow-up to https://github.com/element-hq/synapse/pull/19972


### Dev notes

MSC4512

---------

Co-authored-by: Eric Eastwood <madlittlemods@gmail.com>
This commit is contained in:
Johannes MarbachandEric Eastwood authored and GitHub committed 2026-11-17 09:52:06 -06:00
1 parent cf0b0a9239
commit 77bdc50657
11 files changed
+157 -96

No files matched your search

+1
View File
@@ -0,0 +1 @@
Allow guest user access to `/rtc/transports` and `/rtc/livekit/*`.
+61 -21
View File
@@ -82,6 +82,27 @@ class Namespace:
regex: Pattern[str]
@attr.s(slots=True, frozen=True, auto_attribs=True)
class ProxyPrefix:
"""A path prefix under which requests are proxied to an application service
(MSC4512).
"""
path_prefix: str
"""
The path prefix, applied after the version segment(s) (either /vX/ or
/unstable/foo/):
- /_matrix/client/(unstable/[^/]+|v[^/]+)/{path_prefix}/.*
- /_matrix/federation/(unstable/[^/]+|v[^/]+)/{path_prefix}/.*
Must not end with a slash.
"""
allow_guests: bool
"""
Whether guest users may make proxied Client-Server requests under this prefix.
"""
class ApplicationService:
"""Defines an application service. This definition is mostly what is
provided to the /register AS API.
@@ -97,10 +118,13 @@ class ApplicationService:
# values.
NS_LIST = [NS_USERS, NS_ALIASES, NS_ROOMS]
# Prefixes are applied after the version segment(s) (either /vX/ or /unstable/foo/):
# API prefixes that an application service may claim for proxying. Prefixes
# are applied after the version segment(s) (either /vX/ or /unstable/foo/):
# - /_matrix/client/(unstable/[^/]+|v[^/]+)/{prefix}/.*
# - /_matrix/federation/(unstable/[^/]+|v[^/]+)/{prefix}/.*
ALLOWED_PROXY_PREFIXES = {"rtc/livekit"}
ALLOWED_PROXY_PREFIXES = (
ProxyPrefix(path_prefix="rtc/livekit", allow_guests=True),
)
def __init__(
self,
@@ -125,12 +149,9 @@ class ApplicationService:
self.url = (
url.rstrip("/") if isinstance(url, str) else None
) # url must not end with a slash
self.proxy_url = (
proxy_url.rstrip("/") if isinstance(proxy_url, str) else None
) # proxy_url must not end with a slash
self.proxy_prefix = (
proxy_prefix.rstrip("/") if isinstance(proxy_prefix, str) else None
) # proxy_prefix must not end with a slash
self.proxy_prefix, self.proxy_url = self._parse_proxy_config(
proxy_prefix, proxy_url
)
self.hs_token = hs_token
# The full Matrix ID for this application service's sender.
self.sender = sender
@@ -156,14 +177,6 @@ class ApplicationService:
if "|" in self.id:
raise Exception("application service ID cannot contain '|' character")
if (self.proxy_prefix is None) != (self.proxy_url is None):
raise KeyError("proxy_url and proxy_prefix must always be set together")
if proxy_prefix is not None:
if not proxy_prefix or not self.proxy_url:
raise ValueError("proxy_prefix and proxy_url must be non-empty strings")
if not self._is_proxy_prefix_allowed(proxy_prefix):
raise ValueError(f"cannot claim reserved proxy prefix {proxy_prefix!r}")
# .protocols is a publicly visible field
if protocols:
self.protocols = set(protocols)
@@ -227,11 +240,38 @@ class ApplicationService:
return namespace.exclusive
return False
def _is_proxy_prefix_allowed(self, prefix: str) -> bool:
return any(
prefix == allowed or prefix.startswith(allowed + "/")
for allowed in ApplicationService.ALLOWED_PROXY_PREFIXES
)
@staticmethod
def _parse_proxy_config(
proxy_prefix: str | None, proxy_url: str | None
) -> tuple[ProxyPrefix | None, str | None]:
"""Validates the supplied proxy configuration.
Args:
proxy_prefix: The proxy_prefix value read from the registration file.
proxy_url: The proxy_url value read from the registration file.
Returns:
The matching entry from `ALLOWED_PROXY_PREFIXES` and the proxy URL
without a trailing slash, or `(None, None)` if proxying is not
configured.
Raises:
KeyError: if only one of `proxy_prefix` and `proxy_url` is set.
ValueError: if `proxy_prefix` or `proxy_url` is empty, or if
`proxy_prefix` is not an allowed prefix.
"""
if (proxy_prefix is None) != (proxy_url is None):
raise KeyError("proxy_url and proxy_prefix must always be set together")
if proxy_prefix is None or proxy_url is None:
return None, None
if not proxy_prefix or not proxy_url:
raise ValueError("proxy_prefix and proxy_url must be non-empty strings")
# Strip the trailing slash per TODO (because it makes regex building later easier)
path = proxy_prefix.rstrip("/")
url = proxy_url.rstrip("/") # must not end with a slash
for allowed_proxy_prefix in ApplicationService.ALLOWED_PROXY_PREFIXES:
if allowed_proxy_prefix.path_prefix == path:
return allowed_proxy_prefix, url
raise ValueError(f"cannot claim reserved proxy prefix {proxy_prefix!r}")
@cached(num_args=1, cache_context=True)
async def _matches_user_in_member_list(
+9 -19
View File
@@ -95,16 +95,15 @@ def load_appservices(
)
seen_as_tokens[appservice.token] = config_file
if appservice.proxy_prefix is not None:
for seen_prefix, seen_file in seen_proxy_prefixes.items():
if _proxy_prefixes_overlap(
appservice.proxy_prefix, seen_prefix
):
raise ConfigError(
"io.element.msc4512.proxy_prefix values must not overlap across "
"application services: "
f"{appservice.proxy_prefix} (files: {config_file}, {seen_file})"
)
seen_proxy_prefixes[appservice.proxy_prefix] = config_file
proxy_prefix_path = appservice.proxy_prefix.path_prefix
if proxy_prefix_path in seen_proxy_prefixes:
raise ConfigError(
"io.element.msc4512.proxy_prefix values must be unique across "
"application services: "
f"{proxy_prefix_path} (files: {config_file}, "
f"{seen_proxy_prefixes[proxy_prefix_path]})"
)
seen_proxy_prefixes[proxy_prefix_path] = config_file
logger.info("Loaded application service: %s", appservice)
appservices.append(appservice)
except Exception as e:
@@ -114,15 +113,6 @@ def load_appservices(
return appservices
def _proxy_prefixes_overlap(prefix_a: str, prefix_b: str) -> bool:
"""Returns whether two proxy prefixes overlap by sharing a common path prefix."""
return (
prefix_a == prefix_b
or prefix_a.startswith(prefix_b + "/")
or prefix_b.startswith(prefix_a + "/")
)
def _load_appservice(
hostname: str, as_info: JsonDict, config_filename: str
) -> ApplicationService:
@@ -102,7 +102,7 @@ def register_servlets(
pattern = re.compile(
r"^/_matrix/federation/(?:unstable/[^/]+|v[^/]+)/%s(/.*)?$"
% (re.escape(appservice.proxy_prefix),)
% (re.escape(appservice.proxy_prefix.path_prefix),)
)
callback = _make_proxy_callback(hs, authenticator, ratelimiter, appservice)
+2 -2
View File
@@ -290,11 +290,11 @@ def _check_path_allowed_for_appservice(
)
pattern = re.compile(
r"^/_matrix/federation/(?:unstable/[^/]+|v[^/]+)/%s(/.*)?$"
% (re.escape(appservice.proxy_prefix),)
% (re.escape(appservice.proxy_prefix.path_prefix),)
)
if pattern.match(path) is None:
raise SynapseError(
HTTPStatus.FORBIDDEN,
f"Path must be under /_matrix/federation/<version>/{appservice.proxy_prefix}",
f"Path must be under /_matrix/federation/<version>/{appservice.proxy_prefix.path_prefix}",
Codes.AS_FEDPROXY_PATH_NOT_ALLOWED,
)
+5 -2
View File
@@ -35,7 +35,10 @@ def _make_proxy_callback(
appservice: ApplicationService,
) -> ServletCallback:
async def _proxy(request: SynapseRequest, **kwargs: str) -> None:
requester = await hs.get_auth().get_user_by_req(request)
assert appservice.proxy_prefix is not None
requester = await hs.get_auth().get_user_by_req(
request, allow_guest=appservice.proxy_prefix.allow_guests
)
await ratelimiter.ratelimit(requester)
@@ -69,7 +72,7 @@ def register_servlets(hs: "HomeServer", http_server: HttpServer) -> None:
pattern = re.compile(
r"^/_matrix/client/(?:unstable/[^/]+|v[^/]+)/%s(/.*)?$"
% (re.escape(appservice.proxy_prefix),)
% (re.escape(appservice.proxy_prefix.path_prefix),)
)
callback = _make_proxy_callback(hs, ratelimiter, appservice)
+1 -1
View File
@@ -63,7 +63,7 @@ class UnstableMatrixRTCTransportsRestServlet(RestServlet):
async def on_GET(self, request: SynapseRequest) -> tuple[int, JsonDict]:
# Require authentication for this endpoint.
await self._auth.get_user_by_req(request)
await self._auth.get_user_by_req(request, allow_guest=True)
if self._transports:
return 200, {"rtc_transports": self._transports}
+14 -10
View File
@@ -27,6 +27,7 @@ from twisted.internet import defer
from synapse.appservice import (
ApplicationService,
Namespace,
ProxyPrefix,
Scopes,
)
from synapse.types import UserID
@@ -323,7 +324,10 @@ class ApplicationServiceProxyPrefixTestCase(unittest.TestCase):
proxy_url="http://proxy.example.com",
proxy_prefix="rtc/livekit",
)
self.assertEqual(service.proxy_prefix, "rtc/livekit")
self.assertEqual(
service.proxy_prefix,
ProxyPrefix(path_prefix="rtc/livekit", allow_guests=True),
)
self.assertEqual(service.proxy_url, "http://proxy.example.com")
def test_proxy_url_trailing_slash_is_stripped(self) -> None:
@@ -333,19 +337,18 @@ class ApplicationServiceProxyPrefixTestCase(unittest.TestCase):
)
self.assertEqual(service.proxy_url, "http://proxy.example.com")
def test_nested_proxy_prefix_is_allowed(self) -> None:
service = self._make_service(
proxy_url="http://proxy.example.com",
proxy_prefix="rtc/livekit/foo",
)
self.assertEqual(service.proxy_prefix, "rtc/livekit/foo")
def test_disallowed_proxy_prefix_raises(self) -> None:
with self.assertRaises(ValueError):
self._make_service(
proxy_url="http://proxy.example.com", proxy_prefix="not/allowed"
)
def test_nested_proxy_prefix_raises(self) -> None:
with self.assertRaises(ValueError):
self._make_service(
proxy_url="http://proxy.example.com", proxy_prefix="rtc/livekit/foo"
)
def test_no_proxy_prefix_defaults_to_none(self) -> None:
service = self._make_service()
self.assertIsNone(service.proxy_prefix)
@@ -354,6 +357,7 @@ class ApplicationServiceProxyPrefixTestCase(unittest.TestCase):
def test_trailing_slash_on_proxy_prefix_is_stripped(self) -> None:
service = self._make_service(
proxy_url="http://proxy.example.com",
proxy_prefix="rtc/livekit/foo/",
proxy_prefix="rtc/livekit/",
)
self.assertEqual(service.proxy_prefix, "rtc/livekit/foo")
assert service.proxy_prefix is not None
self.assertEqual(service.proxy_prefix.path_prefix, "rtc/livekit")
+36 -1
View File
@@ -23,7 +23,7 @@ from twisted.internet.testing import MemoryReactor
from twisted.web.http_headers import Headers
from synapse.rest import admin
from synapse.rest.client import appservice_proxy, login
from synapse.rest.client import appservice_proxy, login, register
from synapse.server import HomeServer
from synapse.types import JsonDict
from synapse.util.clock import Clock
@@ -41,6 +41,7 @@ class ApplicationServiceClientProxyTestCase(unittest.HomeserverTestCase):
servlets = [
admin.register_servlets,
login.register_servlets,
register.register_servlets,
appservice_proxy.register_servlets,
]
@@ -67,6 +68,7 @@ class ApplicationServiceClientProxyTestCase(unittest.HomeserverTestCase):
config.setdefault("experimental_features", {}).setdefault(
"msc4512_enabled", True
)
config["allow_guest_access"] = True
return config
def prepare(self, _reactor: MemoryReactor, _clock: Clock, hs: HomeServer) -> None:
@@ -316,6 +318,39 @@ class ApplicationServiceClientProxyTestCase(unittest.HomeserverTestCase):
self.assertEqual(channel.json_body["errcode"], "M_UNKNOWN")
self.agent.request.assert_called()
# TODO: Add a test for an allowed proxy prefix that doesn't allow guest access.
def test_guest_request_is_proxied(self) -> None:
"""Guests may access the LiveKit endpoints under `rtc/livekit` (MSC4195)."""
channel = self.make_request(
"POST", "/_matrix/client/v3/register?kind=guest", b"{}"
)
self.assertEqual(channel.code, 200, channel.json_body)
guest_user_id = channel.json_body["user_id"]
guest_access_token = channel.json_body["access_token"]
self.agent.request = Mock(
return_value=defer.succeed(
FakeResponse.json(code=200, payload={"hello": "guest"})
)
)
channel = self.make_request(
"GET",
f"/_matrix/client/{VERSIONED_PREFIX}/some/path",
shorthand=False,
access_token=guest_access_token,
)
self.assertEqual(channel.code, 200, channel.json_body)
self.assertEqual(channel.json_body, {"hello": "guest"})
(_args, kwargs) = self.agent.request.call_args
headers: Headers = kwargs["headers"]
self.assertEqual(
headers.getRawHeaders(b"X-Matrix-User-Identifier"),
[guest_user_id.encode("ascii")],
)
def test_unauthenticated_get_is_rejected(self) -> None:
self.agent.request = Mock(
return_value=defer.succeed(FakeResponse.json(code=200, payload={}))
+25
View File
@@ -27,6 +27,7 @@ from synapse.config.matrixrtc import TransportConfigModel
from synapse.rest import admin
from synapse.rest.client import login, matrixrtc, register, room, versions
from synapse.server import HomeServer
from synapse.types import JsonDict
from synapse.util.clock import Clock
from tests import unittest
@@ -65,6 +66,11 @@ class MatrixRtcTestCase(HomeserverTestCase):
matrixrtc.register_servlets,
]
def default_config(self) -> JsonDict:
config = super().default_config()
config["allow_guest_access"] = True
return config
def prepare(
self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
) -> None:
@@ -85,6 +91,25 @@ class MatrixRtcTestCase(HomeserverTestCase):
channel = self.make_request("GET", f"{PATH_PREFIX}/rtc/transports")
self.assertEqual(401, channel.code, channel.json_body)
@override_config(
{
"experimental_features": {"msc4143_enabled": True},
"matrix_rtc": {"transports": [RTC_ENDPOINT]},
}
)
def test_matrixrtc_endpoint_allows_guest_access(self) -> None:
channel = self.make_request(
"POST", "/_matrix/client/v3/register?kind=guest", b"{}"
)
self.assertEqual(200, channel.code, channel.json_body)
guest_tok = channel.json_body["access_token"]
channel = self.make_request(
"GET", f"{PATH_PREFIX}/rtc/transports", access_token=guest_tok
)
self.assertEqual(200, channel.code, channel.json_body)
self.assert_dict({"rtc_transports": [RTC_ENDPOINT]}, channel.json_body)
@override_config(
{
"experimental_features": {"msc4143_enabled": True},
+2 -39
View File
@@ -662,7 +662,8 @@ class ApplicationServiceStoreConfigTestCase(unittest.HomeserverTestCase):
self.hs,
)
(appservice,) = store.get_app_services()
self.assertEqual(appservice.proxy_prefix, "rtc/livekit")
assert appservice.proxy_prefix is not None
self.assertEqual(appservice.proxy_prefix.path_prefix, "rtc/livekit")
self.assertEqual(appservice.proxy_url, "http://proxy")
def test_proxy_prefix_requires_proxy_url(self) -> None:
@@ -826,41 +827,3 @@ class ApplicationServiceStoreConfigTestCase(unittest.HomeserverTestCase):
self.assertIn(f1, str(e))
self.assertIn(f2, str(e))
self.assertIn("io.element.msc4512.proxy_prefix", str(e))
def test_overlapping_proxy_prefix(self) -> None:
f1 = self._write_config(
suffix="1",
**{
"io.element.msc4512.proxy_prefix": "rtc/livekit",
"io.element.msc4512.proxy_url": "http://proxy",
},
)
f2 = self._write_config(
suffix="2",
**{
"io.element.msc4512.proxy_prefix": "rtc/livekit/foobar",
"io.element.msc4512.proxy_url": "http://proxy2",
},
)
self.hs.config.appservice.app_service_config_files = [f1, f2]
self.hs.config.caches.event_cache_size = 1
with self.assertRaises(ConfigError) as cm:
server_name = self.hs.hostname
database = self.hs.get_datastores().databases[0]
ApplicationServiceStore(
database,
make_conn(
db_config=database._database_config,
engine=database.engine,
default_txn_name="test",
server_name=server_name,
),
self.hs,
)
e = cm.exception
self.assertIn(f1, str(e))
self.assertIn(f2, str(e))
self.assertIn("io.element.msc4512.proxy_prefix", str(e))