Skip to main content

tuwunel_service/appservice/
registration_info.rs

1use ruma::{OwnedUserId, ServerName, UserId, api::appservice::Registration};
2use tuwunel_core::{Err, Result, err, implement, utils::url::strip_trailing_slash};
3use url::Url;
4
5use super::{NamespaceRegex, destination, socket_path};
6
7/// MSC4502: the scope granting the targeted room membership query.
8///
9/// An appservice whose registration requests it may ask whether any user or
10/// server is joined to any room this server is in.
11pub const IS_JOINED_SCOPE: &str = "urn:matrix:client:io.element.msc4502:rooms:is_joined";
12
13/// MSC4512: the path prefixes an appservice may claim for proxying.
14///
15/// A claim must equal one of them. The proxy also lets the appservice send
16/// federation requests as this server under its prefix, so the list stays
17/// closed.
18pub const PROXY_PREFIXES: [&str; 1] = ["rtc/livekit"];
19
20/// Appservice registration combined with its compiled regular expressions.
21#[derive(Clone, Debug)]
22pub struct RegistrationInfo {
23	pub aliases: NamespaceRegex,
24	pub users: NamespaceRegex,
25	pub rooms: NamespaceRegex,
26	pub sender: OwnedUserId,
27
28	/// MSC4512: the allowed prefix the registration validly claims.
29	///
30	/// `None` for no claim, an invalid one, or one another appservice holds.
31	pub proxy_prefix: Option<&'static str>,
32
33	pub registration: Registration,
34}
35
36impl RegistrationInfo {
37	/// Validates an application service registration.
38	///
39	/// Checks its URL and sender, and compiles its namespace expressions. An
40	/// invalid proxy claim is left out rather than refused; [`proxy_claim`]
41	/// reports why.
42	pub fn new(registration: Registration, server_name: &ServerName) -> Result<Self> {
43		if socket_path(registration.url.as_deref().unwrap_or_default())?.is_some()
44			&& cfg!(not(unix))
45		{
46			return Err!("Unix sockets are not supported on this platform");
47		}
48
49		Ok(Self {
50			aliases: NamespaceRegex::new(false, registration.namespaces.aliases.iter())?,
51			users: NamespaceRegex::new(false, registration.namespaces.users.iter())?,
52			rooms: NamespaceRegex::new(true, registration.namespaces.rooms.iter())?,
53			sender: OwnedUserId::from_parts(
54				'@',
55				registration.sender_localpart.as_ref(),
56				server_name.as_str().into(),
57			)?,
58			proxy_prefix: proxy_claim(&registration).unwrap_or_default(),
59
60			registration,
61		})
62	}
63
64	/// MSC3905: the `users` regex matches local users only.
65	#[inline]
66	#[must_use]
67	pub fn is_user_match(&self, user_id: &UserId) -> bool {
68		user_id == self.sender
69			|| (self.users.is_match(user_id.as_str())
70				&& user_id.server_name() == self.sender.server_name())
71	}
72
73	/// MSC3905: the `users` regex matches local users only.
74	#[inline]
75	#[must_use]
76	pub fn is_exclusive_user_match(&self, user_id: &UserId) -> bool {
77		user_id == self.sender
78			|| (self.users.is_exclusive_match(user_id.as_str())
79				&& user_id.server_name() == self.sender.server_name())
80	}
81
82	/// MSC4502: whether the registration requested `scope`.
83	///
84	/// The match is exact, against the registration's own scope list.
85	#[inline]
86	#[must_use]
87	pub fn has_scope(&self, scope: &str) -> bool {
88		self.registration
89			.scopes
90			.iter()
91			.any(|requested| requested == scope)
92	}
93
94	/// Whether the registration names a URL to deliver traffic to.
95	///
96	/// A registration without one asked for no traffic, so nothing is queued
97	/// for it.
98	#[inline]
99	#[must_use]
100	pub fn has_destination(&self) -> bool { destination(&self.registration).is_some() }
101}
102
103/// MSC4512: whether the valid proxy claim covers a proxied path.
104///
105/// `remainder` is the path after its version segments; the claim covers its
106/// prefix itself and every path beneath it.
107#[implement(RegistrationInfo)]
108#[must_use]
109pub fn proxy_covers(&self, remainder: &str) -> bool {
110	self.proxy_prefix
111		.and_then(|prefix| remainder.strip_prefix(prefix))
112		.is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
113}
114
115/// MSC4512: the URL proxied requests are forwarded to.
116///
117/// Present only with a valid claim, without its trailing slash.
118#[implement(RegistrationInfo)]
119#[must_use]
120pub fn proxy_url(&self) -> Option<&str> {
121	self.proxy_prefix
122		.and(self.registration.proxy_url.as_deref())
123		.map(strip_trailing_slash)
124}
125
126/// MSC4512: the registration without its proxy claim.
127///
128/// The registration's own keys stay as given, so its stored copy is
129/// unchanged; only the claim this server honors is cleared.
130#[implement(RegistrationInfo)]
131#[must_use]
132pub fn without_proxy_claim(self) -> Self { Self { proxy_prefix: None, ..self } }
133
134/// MSC4512: the allowed prefix a registration claims, if it claims one.
135///
136/// Both keys are given or neither. One trailing slash is dropped from each;
137/// the prefix must then equal an allowed one, and the URL must be an http or
138/// https URL, or a Unix socket where this platform has them.
139pub fn proxy_claim(registration: &Registration) -> Result<Option<&'static str>> {
140	let (prefix, url) =
141		match (registration.proxy_prefix.as_deref(), registration.proxy_url.as_deref()) {
142			| (None, None) => return Ok(None),
143			| (Some(prefix), Some(url)) =>
144				(strip_trailing_slash(prefix), strip_trailing_slash(url)),
145			| _ => return Err!("proxy_prefix and proxy_url must be given together"),
146		};
147
148	let usable = match socket_path(url)? {
149		| Some(_) => cfg!(unix),
150		| None => Url::parse(url).is_ok_and(|url| matches!(url.scheme(), "http" | "https")),
151	};
152
153	if !usable {
154		return Err!("proxy_url {url:?} is not an http, https or Unix socket URL");
155	}
156
157	PROXY_PREFIXES
158		.into_iter()
159		.find(|allowed| *allowed == prefix)
160		.map(Some)
161		.ok_or_else(|| err!("proxy_prefix {prefix:?} is not one this server allows"))
162}