Skip to main content

tuwunel_service/rooms/timeline/
build.rs

1//! Builds and appends locally authored room events.
2//!
3//! Event construction, authorization, signing, state advancement, and timeline
4//! insertion are coordinated under the caller's room state guard. Successfully
5//! persisted events are then queued for federation to participating servers.
6
7use std::{collections::HashSet, iter::once, time::Duration};
8
9use futures::{FutureExt, StreamExt};
10use ruma::{
11	CanonicalJsonObject, CanonicalJsonValue, MilliSecondsSinceUnixEpoch, OwnedEventId,
12	OwnedServerName, RoomId, UserId,
13	events::{
14		TimelineEventType,
15		room::member::{MembershipState, RoomMemberEventContent},
16	},
17	room_id,
18	serde::Raw,
19};
20use tuwunel_core::{
21	Err, Result, err, implement,
22	utils::{BoolExt, IterStream, random_string, result::NotFound, time::now},
23};
24use tuwunel_matrix::{
25	StateKey,
26	event::Event,
27	pdu::{PduBuilder, PduEvent},
28};
29
30use super::RoomMutexGuard;
31
32const NONCE_KEY: &str = "uwu.woof";
33
34const NONCE_LENGTH: usize = 8;
35
36// A create sets the room's old-event cutoff, so one dated ahead drops gapped federated events.
37const CREATE_TIMESTAMP_SKEW: Duration = Duration::from_mins(1);
38
39/// What a hashed-ID create does when its room ID is already taken.
40///
41/// The choice follows who fixed the inputs the hash is taken over: a room ID
42/// the client predicted is refused, one the server chose is rehashed.
43#[derive(Clone, Copy, Debug)]
44pub enum Collision<'a> {
45	/// The server chose the inputs, so the event is rehashed once with a nonce
46	/// key in its content, which MSC4291 allows.
47	Retry,
48
49	/// A client fixed the inputs to predict the room ID, so the create is
50	/// refused, as is a hash that misses the ID the client expects.
51	Refuse(Option<&'a str>),
52}
53
54struct CreateInputs<'a> {
55	room_id: &'a RoomId,
56	sender: &'a UserId,
57	timestamp: Option<MilliSecondsSinceUnixEpoch>,
58	state_lock: &'a RoomMutexGuard,
59}
60
61/// Builds, signs, validates, and persists a locally authored room event.
62///
63/// The caller's state guard serializes state derivation and advancement while
64/// the event is inserted into the accepted timeline. Federation enqueue occurs
65/// after persistence, so its failure can be returned after the event and room
66/// state have already been stored.
67#[implement(super::Service)]
68pub fn build_and_append_pdu<'a>(
69	&'a self,
70	pdu_builder: PduBuilder,
71	sender: &'a UserId,
72	room_id: &'a RoomId,
73	state_lock: &'a RoomMutexGuard,
74) -> impl Future<Output = Result<OwnedEventId>> + Send + 'a {
75	self.build_and_store_pdu(pdu_builder, sender, room_id, state_lock)
76		.map(|stored| stored.and_then(|(event_id, appended)| appended.map(|()| event_id)))
77}
78
79/// Builds and persists a locally authored room event, telling a failure after
80/// storage apart from one before it.
81///
82/// An outer error means no timeline row for the event could be found after the
83/// failure. An inner error comes from work done after the event entered the
84/// timeline, such as its side effects or federation enqueue, so the event
85/// exists under the returned ID.
86#[implement(super::Service)]
87#[tracing::instrument(
88	name = "build_and_append"
89	level = "debug",
90	skip(self, state_lock),
91	ret,
92)]
93pub async fn build_and_store_pdu(
94	&self,
95	pdu_builder: PduBuilder,
96	sender: &UserId,
97	room_id: &RoomId,
98	state_lock: &RoomMutexGuard,
99) -> Result<(OwnedEventId, Result)> {
100	let pdu_builder = if pdu_builder.event_type == TimelineEventType::RoomMember {
101		self.sanitize_member_authorisation(pdu_builder, room_id)
102			.boxed() // size firewall
103			.await?
104	} else {
105		pdu_builder
106	};
107
108	let (pdu, pdu_json) = self
109		.create_hash_and_sign_event(pdu_builder, sender, room_id, state_lock)
110		.boxed() // query-depth firewall
111		.await?;
112
113	let event_id = pdu.event_id().to_owned();
114	let appended = self
115		.append_signed_pdu(pdu, pdu_json, sender, state_lock)
116		.boxed() // size firewall
117		.await;
118
119	let Err(error) = appended else {
120		return Ok((event_id, Ok(())));
121	};
122
123	match self.non_outlier_pdu_exists(&event_id).await {
124		| Ok(()) => Ok((event_id, Err(error))),
125		| Err(_) => Err(error),
126	}
127}
128
129/// Builds, signs, and persists a room's create event under the placeholder
130/// room lock every hashed-ID create takes.
131///
132/// A client that fixed the timestamp or named the room ID it expects has
133/// predicted the hash, so a collision is refused. A collision on a
134/// server-chosen timestamp is retried once with a nonce key in the content.
135#[implement(super::Service)]
136pub async fn build_and_append_create_pdu(
137	&self,
138	content: CanonicalJsonObject,
139	sender: &UserId,
140	timestamp: Option<MilliSecondsSinceUnixEpoch>,
141	expected_room_id: Option<&str>,
142) -> Result<OwnedEventId> {
143	let collision = match (timestamp, expected_room_id) {
144		| (None, None) => Collision::Retry,
145		| (_, expected) => Collision::Refuse(expected),
146	};
147
148	self.build_and_append_create_pdu_with(content, sender, timestamp, collision)
149		.await
150}
151
152/// Builds, signs, and persists a room's create event as
153/// `build_and_append_create_pdu` does, under an explicit collision policy.
154///
155/// A `timestamp` of `None` takes the server's clock, and one more than a
156/// minute ahead of it is refused. `collision` decides what a room ID an
157/// earlier create already took does to this one.
158#[implement(super::Service)]
159#[tracing::instrument(
160	name = "build_and_append_create"
161	level = "debug",
162	skip(self, content),
163	ret,
164)]
165pub async fn build_and_append_create_pdu_with(
166	&self,
167	content: CanonicalJsonObject,
168	sender: &UserId,
169	timestamp: Option<MilliSecondsSinceUnixEpoch>,
170	collision: Collision<'_>,
171) -> Result<OwnedEventId> {
172	if timestamp.is_some_and(ahead_of_clock) {
173		return Err!(Request(InvalidParam(
174			"The create event's timestamp is too far in the future."
175		)));
176	}
177
178	let room_id = room_id!("!thiswillbereplaced");
179	let state_lock = self.services.state.mutex.lock(room_id).await;
180	let inputs = CreateInputs {
181		room_id,
182		sender,
183		timestamp,
184		state_lock: &state_lock,
185	};
186
187	let (pdu, pdu_json) = self
188		.hash_create_unique(&inputs, content, collision)
189		.boxed() // query-depth firewall
190		.await?;
191
192	self.append_signed_pdu(pdu, pdu_json, sender, &state_lock)
193		.boxed() // size firewall
194		.await
195}
196
197fn ahead_of_clock(timestamp: MilliSecondsSinceUnixEpoch) -> bool {
198	let at = Duration::from_millis(timestamp.get().into());
199
200	at > now().saturating_add(CREATE_TIMESTAMP_SKEW)
201}
202
203#[implement(super::Service)]
204async fn hash_create_unique(
205	&self,
206	inputs: &CreateInputs<'_>,
207	content: CanonicalJsonObject,
208	collision: Collision<'_>,
209) -> Result<(PduEvent, CanonicalJsonObject)> {
210	let (pdu, pdu_json) = self.hash_create_content(inputs, &content).await?;
211
212	if let Collision::Refuse(Some(expected)) = collision
213		&& pdu.room_id.as_str() != expected
214	{
215		return Err!(Request(InvalidParam(
216			"The create event hashes to a different room ID than expected."
217		)));
218	}
219
220	let collided =
221		matches!(collision, Collision::Retry) && self.room_id_taken(&pdu.room_id).await?;
222
223	if !collided {
224		return Ok((pdu, pdu_json));
225	}
226
227	let content = with_nonce(content);
228
229	self.hash_create_content(inputs, &content).await
230}
231
232#[implement(super::Service)]
233async fn hash_create_content(
234	&self,
235	CreateInputs { room_id, sender, timestamp, state_lock }: &CreateInputs<'_>,
236	content: &CanonicalJsonObject,
237) -> Result<(PduEvent, CanonicalJsonObject)> {
238	let pdu_builder = PduBuilder {
239		event_type: TimelineEventType::RoomCreate,
240		content: Raw::new(content)?,
241		state_key: Some(StateKey::new()),
242		timestamp: *timestamp,
243		..Default::default()
244	};
245
246	self.create_hash_and_sign_event(pdu_builder, sender, room_id, state_lock)
247		.await
248}
249
250fn with_nonce(mut content: CanonicalJsonObject) -> CanonicalJsonObject {
251	let nonce = CanonicalJsonValue::String(random_string(NONCE_LENGTH));
252
253	content.insert(NONCE_KEY.into(), nonce);
254	content
255}
256
257/// Validates and persists an event built by `create_hash_and_sign_event`
258/// under the state guard it was built under.
259///
260/// The event is checked, signed by the room's policy server, and stored before
261/// it is queued for federation, so a queueing failure is returned for an event
262/// already in the room.
263#[implement(super::Service)]
264#[tracing::instrument(
265	name = "append_signed"
266	level = "debug",
267	skip(self, pdu_json, state_lock),
268	ret,
269)]
270async fn append_signed_pdu(
271	&self,
272	pdu: PduEvent,
273	pdu_json: CanonicalJsonObject,
274	sender: &UserId,
275	state_lock: &RoomMutexGuard,
276) -> Result<OwnedEventId> {
277	if self
278		.services
279		.admin
280		.is_admin_room(pdu.room_id())
281		.await
282	{
283		self.check_pdu_for_admin_room(&pdu, sender)
284			.boxed() // cold arm: admin room
285			.await?;
286	}
287
288	if *pdu.kind() == TimelineEventType::RoomRedaction {
289		self.check_redaction_authorized(&pdu)
290			.boxed() // query-depth firewall
291			.await?;
292	}
293
294	let pdu_json = self.with_policy_signature(pdu_json, &pdu).await?;
295
296	//TODO: Use proper room version here
297	if *pdu.kind() == TimelineEventType::RoomCreate && pdu.room_id().server_name().is_none() {
298		self.reserve_room_id(pdu.room_id()).await?;
299	}
300
301	// Store the event snapshot first; append_pdu installs current state after
302	// the timeline row exists and before publishing its stream count.
303	let statehashid = self.services.state.append_to_state(&pdu).await?;
304
305	let pdu_id = self
306		.append_pdu(
307			&pdu,
308			pdu_json,
309			// Since this PDU references all pdu_leaves we can update the leaves
310			// of the room
311			once(pdu.event_id()),
312			Some(statehashid),
313			state_lock,
314		)
315		.boxed() // size firewall
316		.await?;
317
318	let mut servers: HashSet<OwnedServerName> = self
319		.services
320		.state_cache
321		.room_servers(pdu.room_id())
322		.map(ToOwned::to_owned)
323		.collect()
324		.await;
325
326	// In case we are kicking or banning a user, we need to inform their server of
327	// the change
328	if *pdu.kind() == TimelineEventType::RoomMember
329		&& let Some(state_key_uid) = &pdu
330			.state_key
331			.as_ref()
332			.and_then(|state_key| UserId::parse(state_key.as_str()).ok())
333	{
334		servers.insert(state_key_uid.server_name().to_owned());
335	}
336
337	// Remove our server from the server list since it will be added to it by
338	// room_servers() and/or the if statement above
339	servers.remove(self.services.globals.server_name());
340
341	self.services
342		.sending
343		.send_pdu_servers(servers.iter().map(AsRef::as_ref).stream(), &pdu_id)
344		.await?;
345
346	Ok(pdu.event_id().to_owned())
347}
348
349/// Has the room's policy server, if any, sign an event before it is federated.
350///
351/// Per [MSC4284](https://github.com/matrix-org/matrix-spec-proposals/pull/4284)
352/// a refusal is an error, while a transport failure lets the event go out
353/// unsigned.
354#[implement(super::Service)]
355#[tracing::instrument(skip_all, level = "debug")]
356async fn with_policy_signature(
357	&self,
358	mut pdu_json: CanonicalJsonObject,
359	pdu: &PduEvent,
360) -> Result<CanonicalJsonObject> {
361	self.services
362		.event_handler
363		.sign_outgoing_pdu(&mut pdu_json, pdu)
364		.boxed() // size firewall
365		.await?;
366
367	Ok(pdu_json)
368}
369
370/// Allocates the short ID of a room named by its create event's hash.
371///
372/// A short ID already present belongs to an earlier create event with the
373/// same hash, so the new room is refused rather than merged into it.
374#[implement(super::Service)]
375#[tracing::instrument(skip(self), level = "debug")]
376async fn reserve_room_id(&self, room_id: &RoomId) -> Result {
377	if self.room_id_taken(room_id).await? {
378		return Err!(Request(RoomInUse("A room with this create event already exists.")));
379	}
380
381	self.services
382		.short
383		.get_or_create_shortroomid(room_id)
384		.await;
385
386	Ok(())
387}
388
389#[implement(super::Service)]
390#[tracing::instrument(skip(self), level = "debug", ret)]
391async fn room_id_taken(&self, room_id: &RoomId) -> Result<bool> {
392	self.services
393		.short
394		.get_shortroomid(room_id)
395		.await
396		.optional()
397		.map(|short| short.is_some())
398}
399
400#[implement(super::Service)]
401#[tracing::instrument(skip_all, level = "debug")]
402async fn sanitize_member_authorisation(
403	&self,
404	pdu_builder: PduBuilder,
405	room_id: &RoomId,
406) -> Result<PduBuilder> {
407	let content: RoomMemberEventContent = pdu_builder.content.deserialize_as_unchecked()?;
408
409	let Some(authorising_user) = &content.join_authorized_via_users_server else {
410		return Ok(pdu_builder);
411	};
412
413	if content.membership != MembershipState::Join {
414		return Err!(Request(BadJson(
415			"join_authorised_via_users_server is only for member joins"
416		)));
417	}
418
419	// Already joined or invited: strip the inapplicable authorising user.
420	if let Some(target) = pdu_builder
421		.state_key
422		.as_deref()
423		.and_then(|key| UserId::parse(key).ok())
424		&& self
425			.services
426			.state_cache
427			.user_membership(&target, room_id)
428			.await
429			.is_some_and(|m| matches!(m, MembershipState::Join | MembershipState::Invite))
430	{
431		let object: CanonicalJsonObject = pdu_builder
432			.content
433			.deserialize()?
434			.into_iter()
435			.filter(|(key, _)| key != "join_authorised_via_users_server")
436			.collect();
437
438		let content = Raw::new(&object)?;
439
440		return Ok(PduBuilder { content, ..pdu_builder });
441	}
442
443	if !self
444		.services
445		.globals
446		.user_is_local(authorising_user)
447	{
448		return Err!(Request(InvalidParam(
449			"Authorising user does not belong to this homeserver"
450		)));
451	}
452
453	Ok(pdu_builder)
454}
455
456#[implement(super::Service)]
457#[tracing::instrument(skip_all, level = "debug")]
458async fn check_pdu_for_admin_room<Pdu>(&self, pdu: &Pdu, sender: &UserId) -> Result
459where
460	Pdu: Event,
461{
462	match pdu.kind() {
463		| TimelineEventType::RoomEncryption => {
464			return Err!(Request(Forbidden(error!("Encryption not supported in admins room."))));
465		},
466		| TimelineEventType::RoomMember => {
467			self.check_admin_room_member(pdu, sender).await?;
468		},
469		| _ => {},
470	}
471
472	Ok(())
473}
474
475/// Refuses a leave or ban that would take the server user, or the last active
476/// admin, out of the admins room.
477///
478/// Deactivation runs the same last-admin check under this room's state lock;
479/// see `lock_admin_room`.
480#[implement(super::Service)]
481async fn check_admin_room_member<Pdu>(&self, pdu: &Pdu, sender: &UserId) -> Result
482where
483	Pdu: Event,
484{
485	let content: RoomMemberEventContent = pdu.get_content()?;
486
487	let (server_user_refusal, last_admin_refusal) = match content.membership {
488		| MembershipState::Leave => (
489			"Server user cannot leave the admins room.",
490			"Last admin cannot leave the admins room.",
491		),
492		| MembershipState::Ban if pdu.state_key().is_some() => (
493			"Server cannot be banned from admins room.",
494			"Last admin cannot be banned from admins room.",
495		),
496		| _ => return Ok(()),
497	};
498
499	// A key that is no user ID names no admin; the auth rules refuse it later.
500	let Ok(target) = pdu
501		.state_key()
502		.filter(|v| v.starts_with('@'))
503		.map_or(Ok(sender), TryInto::try_into)
504	else {
505		return Ok(());
506	};
507
508	if target == self.services.globals.server_user {
509		return Err!(Request(Forbidden(error!("{server_user_refusal}"))));
510	}
511
512	if self
513		.services
514		.admin
515		.user_is_last_admin(target)
516		.boxed() // cold arm: admin membership check
517		.await
518	{
519		return Err!(Request(Forbidden(error!("{last_admin_refusal}"))));
520	}
521
522	Ok(())
523}
524
525#[implement(super::Service)]
526#[tracing::instrument(skip_all, level = "debug")]
527async fn check_redaction_authorized<Pdu>(&self, pdu: &Pdu) -> Result
528where
529	Pdu: Event,
530{
531	let room_rules = self
532		.services
533		.state
534		.get_room_version_rules(pdu.room_id())
535		.await?;
536
537	let Some(redacts_id) = pdu.redacts_id(&room_rules) else {
538		return Ok(());
539	};
540
541	self.services
542		.state_accessor
543		.user_can_redact(&redacts_id, pdu.sender(), pdu.room_id(), false)
544		.await?
545		.into_option()
546		.ok_or_else(|| err!(Request(Forbidden("User cannot redact this event."))))
547}