ruma_state_res/state_res.rs
1use std::{
2 borrow::Borrow,
3 cmp::{Ordering, Reverse},
4 collections::{BinaryHeap, HashMap, HashSet},
5 hash::Hash,
6 sync::OnceLock,
7};
8
9use ruma_common::{
10 EventId, MilliSecondsSinceUnixEpoch, OwnedUserId,
11 room_version_rules::{AuthorizationRules, StateResolutionV2Rules},
12};
13use ruma_events::{
14 StateEventType, TimelineEventType,
15 room::{member::MembershipState, power_levels::UserPowerLevel},
16};
17use tracing::{debug, info, instrument, trace, warn};
18
19#[cfg(test)]
20mod tests;
21
22use crate::{
23 Error, Event, Result, auth_types_for_event, check_state_dependent_auth_rules,
24 events::{
25 RoomCreateEvent, RoomMemberEvent, RoomPowerLevelsEvent, RoomPowerLevelsIntField,
26 power_levels::RoomPowerLevelsEventOptionExt,
27 },
28 utils::RoomIdExt,
29};
30
31/// A mapping of event type and state_key to some value `T`, usually an `EventId`.
32///
33/// This is the representation of what the Matrix specification calls a "room state" or a "state
34/// map" during [state resolution].
35///
36/// [state resolution]: https://spec.matrix.org/latest/rooms/v2/#state-resolution
37pub type StateMap<T> = HashMap<(StateEventType, String), T>;
38
39/// Apply the [state resolution] algorithm introduced in room version 2 to resolve the state of a
40/// room.
41///
42/// ## Arguments
43///
44/// * `auth_rules` - The authorization rules to apply for the version of the current room.
45///
46/// * `state_res_rules` - The state resolution rules to apply for the version of the current room.
47///
48/// * `state_maps` - The incoming states to resolve. Each `StateMap` represents a possible fork in
49/// the state of a room.
50///
51/// * `auth_chains` - The list of full recursive sets of `auth_events` for each event in the
52/// `state_maps`.
53///
54/// * `fetch_event` - Function to fetch an event in the room given its event ID.
55///
56/// * `fetch_conflicted_state_subgraph` - Function to fetch the conflicted state subgraph for the
57/// given conflicted state set, for state resolution rules that use it. If it is called and
58/// returns `None`, this function will return an error.
59///
60/// ## Invariants
61///
62/// The caller of `resolve` must ensure that all the events are from the same room.
63///
64/// ## Returns
65///
66/// The resolved room state.
67///
68/// [state resolution]: https://spec.matrix.org/latest/rooms/v2/#state-resolution
69#[instrument(skip_all)]
70pub fn resolve<'a, E, MapsIter>(
71 auth_rules: &AuthorizationRules,
72 state_res_rules: &StateResolutionV2Rules,
73 state_maps: impl IntoIterator<IntoIter = MapsIter>,
74 auth_chains: Vec<HashSet<E::Id>>,
75 fetch_event: impl Fn(&EventId) -> Option<E>,
76 fetch_conflicted_state_subgraph: impl Fn(&StateMap<Vec<E::Id>>) -> Option<HashSet<E::Id>>,
77) -> Result<StateMap<E::Id>>
78where
79 E: Event + Clone,
80 E::Id: 'a,
81 MapsIter: Iterator<Item = &'a StateMap<E::Id>> + Clone,
82{
83 info!("state resolution starting");
84
85 // Split the unconflicted state map and the conflicted state set.
86 let (unconflicted_state_map, conflicted_state_set) =
87 split_conflicted_state_set(state_maps.into_iter());
88
89 info!(count = unconflicted_state_map.len(), "unconflicted events");
90 trace!(map = ?unconflicted_state_map, "unconflicted events");
91
92 if conflicted_state_set.is_empty() {
93 info!("no conflicted state found");
94 return Ok(unconflicted_state_map);
95 }
96
97 info!(count = conflicted_state_set.len(), "conflicted events");
98 trace!(map = ?conflicted_state_set, "conflicted events");
99
100 // Since v12, fetch the conflicted state subgraph.
101 let conflicted_state_subgraph = if state_res_rules.consider_conflicted_state_subgraph {
102 let conflicted_state_subgraph = fetch_conflicted_state_subgraph(&conflicted_state_set)
103 .ok_or(Error::FetchConflictedStateSubgraphFailed)?;
104
105 info!(count = conflicted_state_subgraph.len(), "events in conflicted state subgraph");
106 trace!(set = ?conflicted_state_subgraph, "conflicted state subgraph");
107
108 conflicted_state_subgraph
109 } else {
110 HashSet::new()
111 };
112
113 // The full conflicted set is the union of the conflicted state set and the auth difference,
114 // and since v12, the conflicted state subgraph.
115 let full_conflicted_set: HashSet<_> = auth_difference(auth_chains)
116 .chain(conflicted_state_set.into_values().flatten())
117 .chain(conflicted_state_subgraph)
118 // Don't honor events we cannot "verify"
119 .filter(|id| fetch_event(id.borrow()).is_some())
120 .collect();
121
122 info!(count = full_conflicted_set.len(), "full conflicted set");
123 trace!(set = ?full_conflicted_set, "full conflicted set");
124
125 // 1. Select the set X of all power events that appear in the full conflicted set. For each such
126 // power event P, enlarge X by adding the events in the auth chain of P which also belong to
127 // the full conflicted set. Sort X into a list using the reverse topological power ordering.
128 let conflicted_power_events = full_conflicted_set
129 .iter()
130 .filter(|&id| is_power_event_id(id.borrow(), &fetch_event))
131 .cloned()
132 .collect::<Vec<_>>();
133
134 let sorted_power_events =
135 sort_power_events(conflicted_power_events, &full_conflicted_set, auth_rules, &fetch_event)?;
136
137 debug!(count = sorted_power_events.len(), "power events");
138 trace!(list = ?sorted_power_events, "sorted power events");
139
140 // 2. Apply the iterative auth checks algorithm, starting from the unconflicted state map, to
141 // the list of events from the previous step to get a partially resolved state.
142
143 // Since v12, begin the first phase of iterative auth checks with an empty state map.
144 let initial_state_map = if state_res_rules.begin_iterative_auth_checks_with_empty_state_map {
145 HashMap::new()
146 } else {
147 unconflicted_state_map.clone()
148 };
149
150 let partially_resolved_state =
151 iterative_auth_checks(auth_rules, &sorted_power_events, initial_state_map, &fetch_event)?;
152
153 debug!(count = partially_resolved_state.len(), "resolved power events");
154 trace!(map = ?partially_resolved_state, "resolved power events");
155
156 // 3. Take all remaining events that weren’t picked in step 1 and order them by the mainline
157 // ordering based on the power level in the partially resolved state obtained in step 2.
158 let sorted_power_events_set = sorted_power_events.into_iter().collect::<HashSet<_>>();
159 let remaining_events = full_conflicted_set
160 .iter()
161 .filter(|&id| !sorted_power_events_set.contains(id.borrow()))
162 .cloned()
163 .collect::<Vec<_>>();
164
165 debug!(count = remaining_events.len(), "events left to resolve");
166 trace!(list = ?remaining_events, "events left to resolve");
167
168 // This "epochs" power level event
169 let power_event = partially_resolved_state.get(&(StateEventType::RoomPowerLevels, "".into()));
170
171 debug!(event_id = ?power_event, "power event");
172
173 let sorted_remaining_events =
174 mainline_sort(&remaining_events, power_event.cloned(), &fetch_event)?;
175
176 trace!(list = ?sorted_remaining_events, "events left, sorted");
177
178 // 4. Apply the iterative auth checks algorithm on the partial resolved state and the list of
179 // events from the previous step.
180 let mut resolved_state = iterative_auth_checks(
181 auth_rules,
182 &sorted_remaining_events,
183 partially_resolved_state,
184 &fetch_event,
185 )?;
186
187 // 5. Update the result by replacing any event with the event with the same key from the
188 // unconflicted state map, if such an event exists, to get the final resolved state.
189 resolved_state.extend(unconflicted_state_map);
190
191 info!("state resolution finished");
192
193 Ok(resolved_state)
194}
195
196/// Split the unconflicted state map and the conflicted state set.
197///
198/// Definition in the specification:
199///
200/// > If a given key _K_ is present in every _Si_ with the same value _V_ in each state map, then
201/// > the pair (_K_, _V_) belongs to the unconflicted state map. Otherwise, _V_ belongs to the
202/// > conflicted state set.
203///
204/// It means that, for a given (event type, state key) tuple, if all state maps have the same event
205/// ID, it lands in the unconflicted state map, otherwise the event IDs land in the conflicted state
206/// set.
207///
208/// ## Arguments
209///
210/// * `state_maps` - The incoming states to resolve. Each `StateMap` represents a possible fork in
211/// the state of a room.
212///
213/// ## Returns
214///
215/// Returns an `(unconflicted_state_map, conflicted_state_set)` tuple.
216fn split_conflicted_state_set<'a, Id>(
217 state_maps: impl Iterator<Item = &'a StateMap<Id>>,
218) -> (StateMap<Id>, StateMap<Vec<Id>>)
219where
220 Id: Clone + Eq + Hash + 'a,
221{
222 let mut state_set_count = 0_usize;
223 let mut occurrences = HashMap::<_, HashMap<_, _>>::new();
224
225 let state_maps = state_maps.inspect(|_| state_set_count += 1);
226 for (k, v) in state_maps.flatten() {
227 occurrences.entry(k).or_default().entry(v).and_modify(|x| *x += 1).or_insert(1);
228 }
229
230 let mut unconflicted_state_map = StateMap::new();
231 let mut conflicted_state_set = StateMap::new();
232
233 for (k, v) in occurrences {
234 for (id, occurrence_count) in v {
235 if occurrence_count == state_set_count {
236 unconflicted_state_map.insert((k.0.clone(), k.1.clone()), id.clone());
237 } else {
238 conflicted_state_set
239 .entry((k.0.clone(), k.1.clone()))
240 .and_modify(|x: &mut Vec<_>| x.push(id.clone()))
241 .or_insert(vec![id.clone()]);
242 }
243 }
244 }
245
246 (unconflicted_state_map, conflicted_state_set)
247}
248
249/// Get the auth difference for the given auth chains.
250///
251/// Definition in the specification:
252///
253/// > The auth difference is calculated by first calculating the full auth chain for each state
254/// > _Si_, that is the union of the auth chains for each event in _Si_, and then taking every event
255/// > that doesn’t appear in every auth chain. If _Ci_ is the full auth chain of _Si_, then the auth
256/// > difference is ∪_Ci_ − ∩_Ci_.
257///
258/// ## Arguments
259///
260/// * `auth_chains` - The list of full recursive sets of `auth_events`.
261///
262/// ## Returns
263///
264/// Returns an iterator over all the event IDs that are not present in all the auth chains.
265fn auth_difference<Id>(auth_chains: Vec<HashSet<Id>>) -> impl Iterator<Item = Id>
266where
267 Id: Eq + Hash,
268{
269 let num_sets = auth_chains.len();
270
271 let mut id_counts: HashMap<Id, usize> = HashMap::new();
272 for id in auth_chains.into_iter().flatten() {
273 *id_counts.entry(id).or_default() += 1;
274 }
275
276 id_counts.into_iter().filter_map(move |(id, count)| (count < num_sets).then_some(id))
277}
278
279/// Enlarge the given list of conflicted power events by adding the events in their auth chain that
280/// are in the full conflicted set, and sort it using reverse topological power ordering.
281///
282/// ## Arguments
283///
284/// * `conflicted_power_events` - The list of power events in the full conflicted set.
285///
286/// * `full_conflicted_set` - The full conflicted set.
287///
288/// * `rules` - The authorization rules for the current room version.
289///
290/// * `fetch_event` - Function to fetch an event in the room given its event ID.
291///
292/// ## Returns
293///
294/// Returns the ordered list of event IDs from earliest to latest.
295#[instrument(skip_all)]
296fn sort_power_events<E: Event>(
297 conflicted_power_events: Vec<E::Id>,
298 full_conflicted_set: &HashSet<E::Id>,
299 rules: &AuthorizationRules,
300 fetch_event: impl Fn(&EventId) -> Option<E>,
301) -> Result<Vec<E::Id>> {
302 debug!("reverse topological sort of power events");
303
304 // A representation of the DAG, a map of event ID to its list of auth events that are in the
305 // full conflicted set.
306 let mut graph = HashMap::new();
307
308 // Fill the graph.
309 for event_id in conflicted_power_events {
310 add_event_and_auth_chain_to_graph(&mut graph, event_id, full_conflicted_set, &fetch_event);
311
312 // TODO: if these functions are ever made async here
313 // is a good place to yield every once in a while so other
314 // tasks can make progress
315 }
316
317 // The map of event ID to the power level of the sender of the event.
318 let mut event_to_power_level = HashMap::new();
319 // We need to know the creator in case of missing power levels. Given that it's the same for all
320 // the events in the room, we will just load it for the first event and reuse it.
321 let creators_lock = OnceLock::new();
322
323 // Get the power level of the sender of each event in the graph.
324 for event_id in graph.keys() {
325 let sender_power_level =
326 power_level_for_sender(event_id.borrow(), rules, &creators_lock, &fetch_event)
327 .map_err(Error::AuthEvent)?;
328 debug!(
329 event_id = event_id.borrow().as_str(),
330 power_level = ?sender_power_level,
331 "found the power level of an event's sender",
332 );
333
334 event_to_power_level.insert(event_id.clone(), sender_power_level);
335
336 // TODO: if these functions are ever made async here
337 // is a good place to yield every once in a while so other
338 // tasks can make progress
339 }
340
341 reverse_topological_power_sort(&graph, |event_id| {
342 let event = fetch_event(event_id).ok_or_else(|| Error::NotFound(event_id.to_owned()))?;
343 let power_level = *event_to_power_level
344 .get(event_id)
345 .ok_or_else(|| Error::NotFound(event_id.to_owned()))?;
346 Ok((power_level, event.origin_server_ts()))
347 })
348}
349
350/// Sorts the given event graph using reverse topological power ordering.
351///
352/// Definition in the specification:
353///
354/// > The reverse topological power ordering of a set of events is the lexicographically smallest
355/// > topological ordering based on the DAG formed by auth events. The reverse topological power
356/// > ordering is ordered from earliest event to latest. For comparing two topological orderings to
357/// > determine which is the lexicographically smallest, the following comparison relation on events
358/// > is used: for events x and y, x < y if
359/// >
360/// > 1. x’s sender has greater power level than y’s sender, when looking at their respective
361/// > auth_events; or
362/// > 2. the senders have the same power level, but x’s origin_server_ts is less than y’s
363/// > origin_server_ts; or
364/// > 3. the senders have the same power level and the events have the same origin_server_ts, but
365/// > x’s event_id is less than y’s event_id.
366/// >
367/// > The reverse topological power ordering can be found by sorting the events using Kahn’s
368/// > algorithm for topological sorting, and at each step selecting, among all the candidate
369/// > vertices, the smallest vertex using the above comparison relation.
370///
371/// ## Arguments
372///
373/// * `graph` - The graph to sort. A map of event ID to its auth events that are in the full
374/// conflicted set.
375///
376/// * `event_details_fn` - Function to obtain a (power level, origin_server_ts) of an event for
377/// breaking ties.
378///
379/// ## Returns
380///
381/// Returns the ordered list of event IDs from earliest to latest.
382#[instrument(skip_all)]
383pub fn reverse_topological_power_sort<Id, F>(
384 graph: &HashMap<Id, HashSet<Id>>,
385 event_details_fn: F,
386) -> Result<Vec<Id>>
387where
388 F: Fn(&EventId) -> Result<(UserPowerLevel, MilliSecondsSinceUnixEpoch)>,
389 Id: Clone + Eq + Ord + Hash + Borrow<EventId>,
390{
391 #[derive(PartialEq, Eq)]
392 struct TieBreaker<'a, Id> {
393 power_level: UserPowerLevel,
394 origin_server_ts: MilliSecondsSinceUnixEpoch,
395 event_id: &'a Id,
396 }
397
398 impl<Id> Ord for TieBreaker<'_, Id>
399 where
400 Id: Ord,
401 {
402 fn cmp(&self, other: &Self) -> Ordering {
403 // NOTE: the power level comparison is "backwards" intentionally.
404 other
405 .power_level
406 .cmp(&self.power_level)
407 .then(self.origin_server_ts.cmp(&other.origin_server_ts))
408 .then(self.event_id.cmp(other.event_id))
409 }
410 }
411
412 impl<Id> PartialOrd for TieBreaker<'_, Id>
413 where
414 Id: Ord,
415 {
416 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
417 Some(self.cmp(other))
418 }
419 }
420
421 // We consider that the DAG is directed from most recent events to oldest events, so an event is
422 // an incoming edge to its auth events.
423
424 // Map of event to the list of events in its auth events.
425 let mut outgoing_edges_map = graph.clone();
426
427 // Map of event to the list of events that reference it in its auth events.
428 let mut incoming_edges_map: HashMap<_, HashSet<_>> = HashMap::new();
429
430 // Vec of events that have an outdegree of zero (no outgoing edges), i.e. the oldest events.
431 let mut zero_outdegrees = Vec::new();
432
433 // Populate the list of events with an outdegree of zero, and the map of incoming edges.
434 for (event_id, outgoing_edges) in graph {
435 if outgoing_edges.is_empty() {
436 let (power_level, origin_server_ts) = event_details_fn(event_id.borrow())?;
437
438 // `Reverse` because `BinaryHeap` sorts largest -> smallest and we need
439 // smallest -> largest.
440 zero_outdegrees.push(Reverse(TieBreaker { power_level, origin_server_ts, event_id }));
441 }
442
443 incoming_edges_map.entry(event_id).or_default();
444
445 for auth_event_id in outgoing_edges {
446 incoming_edges_map.entry(auth_event_id).or_default().insert(event_id);
447 }
448 }
449
450 // Use a BinaryHeap to keep the events with an outdegree of zero sorted.
451 let mut heap = BinaryHeap::from(zero_outdegrees);
452 let mut sorted = vec![];
453
454 // Apply Kahn's algorithm.
455 // https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm
456 while let Some(Reverse(item)) = heap.pop() {
457 let event_id = item.event_id;
458
459 for &parent_id in incoming_edges_map
460 .get(event_id)
461 .expect("event ID in heap should also be in incoming edges map")
462 {
463 let outgoing_edges = outgoing_edges_map
464 .get_mut(parent_id.borrow())
465 .expect("outgoing edges map should have a key for all event IDs");
466
467 outgoing_edges.remove(event_id.borrow());
468
469 // Push on the heap once all the outgoing edges have been removed.
470 if outgoing_edges.is_empty() {
471 let (power_level, origin_server_ts) = event_details_fn(parent_id.borrow())?;
472 heap.push(Reverse(TieBreaker {
473 power_level,
474 origin_server_ts,
475 event_id: parent_id,
476 }));
477 }
478 }
479
480 sorted.push(event_id.clone());
481 }
482
483 Ok(sorted)
484}
485
486/// Find the power level for the sender of the event of the given event ID or return a default value
487/// of zero.
488///
489/// We find the most recent `m.room.power_levels` by walking backwards in the auth chain of the
490/// event.
491///
492/// Do NOT use this anywhere but topological sort.
493///
494/// ## Arguments
495///
496/// * `event_id` - The event ID of the event to get the power level of the sender of.
497///
498/// * `rules` - The authorization rules for the current room version.
499///
500/// * `creator_lock` - A lock used to cache the user ID of the creator of the room. If it is empty
501/// the creator will be fetched in the auth chain and used to populate the lock.
502///
503/// * `fetch_event` - Function to fetch an event in the room given its event ID.
504///
505/// ## Returns
506///
507/// Returns the power level of the sender of the event or an `Err(_)` if one of the auth events if
508/// malformed.
509fn power_level_for_sender<E: Event>(
510 event_id: &EventId,
511 rules: &AuthorizationRules,
512 creators_lock: &OnceLock<HashSet<OwnedUserId>>,
513 fetch_event: impl Fn(&EventId) -> Option<E>,
514) -> std::result::Result<UserPowerLevel, String> {
515 let event = fetch_event(event_id);
516 let mut room_create_event = None;
517 let mut room_power_levels_event = None;
518
519 if let Some(event) = &event
520 && rules.room_create_event_id_as_room_id
521 && creators_lock.get().is_none()
522 {
523 // The m.room.create event is not in the auth events, we can get its ID via the room ID.
524 room_create_event = event
525 .room_id()
526 .and_then(|room_id| room_id.room_create_event_id().ok())
527 .and_then(|room_create_event_id| fetch_event(&room_create_event_id));
528 }
529
530 for auth_event_id in event.as_ref().map(|pdu| pdu.auth_events()).into_iter().flatten() {
531 if let Some(auth_event) = fetch_event(auth_event_id.borrow()) {
532 if is_type_and_key(&auth_event, &TimelineEventType::RoomPowerLevels, "") {
533 room_power_levels_event = Some(RoomPowerLevelsEvent::new(auth_event));
534 } else if !rules.room_create_event_id_as_room_id
535 && creators_lock.get().is_none()
536 && is_type_and_key(&auth_event, &TimelineEventType::RoomCreate, "")
537 {
538 room_create_event = Some(auth_event);
539 }
540
541 if room_power_levels_event.is_some()
542 && (rules.room_create_event_id_as_room_id
543 || creators_lock.get().is_some()
544 || room_create_event.is_some())
545 {
546 break;
547 }
548 }
549 }
550
551 // TODO: Use OnceLock::try_or_get_init when it is stabilized.
552 let creators = if let Some(creators) = creators_lock.get() {
553 Some(creators)
554 } else if let Some(room_create_event) = room_create_event {
555 let room_create_event = RoomCreateEvent::new(room_create_event);
556 let creators = room_create_event.creators(rules)?;
557 Some(creators_lock.get_or_init(|| creators))
558 } else {
559 None
560 };
561
562 if let Some((event, creators)) = event.zip(creators) {
563 room_power_levels_event.user_power_level(event.sender(), creators, rules)
564 } else {
565 room_power_levels_event
566 .get_as_int_or_default(RoomPowerLevelsIntField::UsersDefault, rules)
567 .map(Into::into)
568 }
569}
570
571/// Perform the iterative auth checks to the given list of events.
572///
573/// Definition in the specification:
574///
575/// > The iterative auth checks algorithm takes as input an initial room state and a sorted list of
576/// > state events, and constructs a new room state by iterating through the event list and applying
577/// > the state event to the room state if the state event is allowed by the authorization rules. If
578/// > the state event is not allowed by the authorization rules, then the event is ignored. If a
579/// > (event_type, state_key) key that is required for checking the authorization rules is not
580/// > present in the state, then the appropriate state event from the event’s auth_events is used if
581/// > the auth event is not rejected.
582///
583/// ## Arguments
584///
585/// * `rules` - The authorization rules for the current room version.
586///
587/// * `events` - The sorted state events to apply to the `partial_state`.
588///
589/// * `state` - The current state that was partially resolved for the room.
590///
591/// * `fetch_event` - Function to fetch an event in the room given its event ID.
592///
593/// ## Returns
594///
595/// Returns the partially resolved state, or an `Err(_)` if one of the state events in the room has
596/// an unexpected format.
597fn iterative_auth_checks<E: Event + Clone>(
598 rules: &AuthorizationRules,
599 events: &[E::Id],
600 mut state: StateMap<E::Id>,
601 fetch_event: impl Fn(&EventId) -> Option<E>,
602) -> Result<StateMap<E::Id>> {
603 debug!("starting iterative auth checks");
604
605 trace!(list = ?events, "events to check");
606
607 for event_id in events {
608 let event = fetch_event(event_id.borrow())
609 .ok_or_else(|| Error::NotFound(event_id.borrow().to_owned()))?;
610 let state_key = event.state_key().ok_or(Error::MissingStateKey)?;
611
612 let mut auth_events = StateMap::new();
613 for auth_event_id in event.auth_events() {
614 if let Some(auth_event) = fetch_event(auth_event_id.borrow()) {
615 if !auth_event.rejected() {
616 auth_events.insert(
617 auth_event
618 .event_type()
619 .with_state_key(auth_event.state_key().ok_or(Error::MissingStateKey)?),
620 auth_event,
621 );
622 }
623 } else {
624 warn!(event_id = %auth_event_id.borrow(), "missing auth event");
625 }
626 }
627
628 // If the `m.room.create` event is not in the auth events, we need to add it, because it's
629 // always part of the state and required in the auth rules.
630 if rules.room_create_event_id_as_room_id
631 && *event.event_type() != TimelineEventType::RoomCreate
632 {
633 if let Some(room_create_event) = event
634 .room_id()
635 .and_then(|room_id| room_id.room_create_event_id().ok())
636 .and_then(|room_create_event_id| fetch_event(&room_create_event_id))
637 {
638 auth_events.insert((StateEventType::RoomCreate, String::new()), room_create_event);
639 } else {
640 warn!("missing m.room.create event");
641 }
642 }
643
644 let auth_types = match auth_types_for_event(
645 event.event_type(),
646 event.sender(),
647 Some(state_key),
648 event.content(),
649 rules,
650 ) {
651 Ok(auth_types) => auth_types,
652 Err(error) => {
653 warn!("failed to get list of required auth events for malformed event: {error}");
654 continue;
655 }
656 };
657
658 for key in auth_types {
659 if let Some(auth_event_id) = state.get(&key) {
660 if let Some(auth_event) = fetch_event(auth_event_id.borrow()) {
661 if !auth_event.rejected() {
662 auth_events.insert(key.to_owned(), auth_event);
663 }
664 } else {
665 warn!(event_id = %auth_event_id.borrow(), "missing auth event");
666 }
667 }
668 }
669
670 match check_state_dependent_auth_rules(rules, &event, |ty, key| {
671 auth_events.get(&ty.with_state_key(key))
672 }) {
673 Ok(()) => {
674 // Add event to the partially resolved state.
675 state.insert(event.event_type().with_state_key(state_key), event_id.clone());
676 }
677 Err(error) => {
678 // Don't add this event to the state.
679 warn!("event failed the authentication check: {error}");
680 }
681 }
682
683 // TODO: if these functions are ever made async here
684 // is a good place to yield every once in a while so other
685 // tasks can make progress
686 }
687
688 Ok(state)
689}
690
691/// Perform mainline ordering of the given events.
692///
693/// Definition in the spec:
694///
695/// > Given mainline positions calculated from P, the mainline ordering based on P of a set of
696/// > events is the ordering, from smallest to largest, using the following comparison relation on
697/// > events: for events x and y, x < y if
698/// >
699/// > 1. the mainline position of x is greater than the mainline position of y (i.e. the auth chain
700/// > of x is based on an earlier event in the mainline than y); or
701/// > 2. the mainline positions of the events are the same, but x’s origin_server_ts is less than
702/// > y’s origin_server_ts; or
703/// > 3. the mainline positions of the events are the same and the events have the same
704/// > origin_server_ts, but x’s event_id is less than y’s event_id.
705///
706/// ## Arguments
707///
708/// * `events` - The list of event IDs to sort.
709///
710/// * `power_level` - The power level event in the current state.
711///
712/// * `fetch_event` - Function to fetch an event in the room given its event ID.
713///
714/// ## Returns
715///
716/// Returns the sorted list of event IDs, or an `Err(_)` if one the event in the room has an
717/// unexpected format.
718fn mainline_sort<E: Event>(
719 events: &[E::Id],
720 mut power_level: Option<E::Id>,
721 fetch_event: impl Fn(&EventId) -> Option<E>,
722) -> Result<Vec<E::Id>> {
723 debug!("mainline sort of events");
724
725 // There are no events to sort, bail.
726 if events.is_empty() {
727 return Ok(vec![]);
728 }
729
730 // Populate the mainline of the power level.
731 let mut mainline = vec![];
732
733 while let Some(power_level_event_id) = power_level {
734 mainline.push(power_level_event_id.clone());
735
736 let power_level_event = fetch_event(power_level_event_id.borrow())
737 .ok_or_else(|| Error::NotFound(power_level_event_id.borrow().to_owned()))?;
738
739 power_level = None;
740
741 for auth_event_id in power_level_event.auth_events() {
742 let auth_event = fetch_event(auth_event_id.borrow())
743 .ok_or_else(|| Error::NotFound(power_level_event_id.borrow().to_owned()))?;
744 if is_type_and_key(&auth_event, &TimelineEventType::RoomPowerLevels, "") {
745 power_level = Some(auth_event_id.to_owned());
746 break;
747 }
748 }
749
750 // TODO: if these functions are ever made async here
751 // is a good place to yield every once in a while so other
752 // tasks can make progress
753 }
754
755 let mainline_map = mainline
756 .iter()
757 .rev()
758 .enumerate()
759 .map(|(idx, event_id)| ((*event_id).clone(), idx))
760 .collect::<HashMap<_, _>>();
761
762 let mut order_map = HashMap::new();
763 for event_id in events.iter() {
764 if let Some(event) = fetch_event(event_id.borrow())
765 && let Ok(position) = mainline_position(event, &mainline_map, &fetch_event)
766 {
767 order_map.insert(
768 event_id,
769 (
770 position,
771 fetch_event(event_id.borrow()).map(|event| event.origin_server_ts()),
772 event_id,
773 ),
774 );
775 }
776
777 // TODO: if these functions are ever made async here
778 // is a good place to yield every once in a while so other
779 // tasks can make progress
780 }
781
782 let mut sorted_event_ids = order_map.keys().map(|&k| k.clone()).collect::<Vec<_>>();
783 sorted_event_ids.sort_by_key(|event_id| order_map.get(event_id).unwrap());
784
785 Ok(sorted_event_ids)
786}
787
788/// Get the mainline position of the given event from the given mainline map.
789///
790/// Definition in the spec:
791///
792/// > Let P = P0 be an m.room.power_levels event. Starting with i = 0, repeatedly fetch Pi+1, the
793/// > m.room.power_levels event in the auth_events of Pi. Increment i and repeat until Pi has no
794/// > m.room.power_levels event in its auth_events. The mainline of P0 is the list of events [P0 ,
795/// > P1, … , Pn], fetched in this way.
796/// >
797/// > Let e = e0 be another event (possibly another m.room.power_levels event). We can compute a
798/// > similar list of events [e1, …, em], where ej+1 is the m.room.power_levels event in the
799/// > auth_events of ej and where em has no m.room.power_levels event in its auth_events. (Note that
800/// > the event we started with, e0, is not included in this list. Also note that it may be empty,
801/// > because e may not cite an m.room.power_levels event in its auth_events at all.)
802/// >
803/// > Now compare these two lists as follows.
804/// >
805/// > * Find the smallest index j ≥ 1 for which ej belongs to the mainline of P.
806/// > * If such a j exists, then ej = Pi for some unique index i ≥ 0. Otherwise set i = ∞, where ∞
807/// > is a sentinel value greater than any integer.
808/// > * In both cases, the mainline position of e is i.
809///
810/// ## Arguments
811///
812/// * `event` - The event to compute the mainline position of.
813///
814/// * `mainline_map` - The mainline map of the m.room.power_levels event.
815///
816/// * `fetch_event` - Function to fetch an event in the room given its event ID.
817///
818/// ## Returns
819///
820/// Returns the mainline position of the event, or an `Err(_)` if one of the events in the auth
821/// chain of the event was not found.
822fn mainline_position<E: Event>(
823 event: E,
824 mainline_map: &HashMap<E::Id, usize>,
825 fetch_event: impl Fn(&EventId) -> Option<E>,
826) -> Result<usize> {
827 let mut current_event = Some(event);
828
829 while let Some(event) = current_event {
830 let event_id = event.event_id();
831 debug!(event_id = event_id.borrow().as_str(), "mainline");
832
833 // If the current event is in the mainline map, return its position.
834 if let Some(position) = mainline_map.get(event_id.borrow()) {
835 return Ok(*position);
836 }
837
838 current_event = None;
839
840 // Look for the power levels event in the auth events.
841 for auth_event_id in event.auth_events() {
842 let auth_event = fetch_event(auth_event_id.borrow())
843 .ok_or_else(|| Error::NotFound(auth_event_id.borrow().to_owned()))?;
844
845 if is_type_and_key(&auth_event, &TimelineEventType::RoomPowerLevels, "") {
846 current_event = Some(auth_event);
847 break;
848 }
849 }
850 }
851
852 // Did not find a power level event so we default to zero.
853 Ok(0)
854}
855
856/// Add the event with the given event ID and all the events in its auth chain that are in the full
857/// conflicted set to the graph.
858fn add_event_and_auth_chain_to_graph<E: Event>(
859 graph: &mut HashMap<E::Id, HashSet<E::Id>>,
860 event_id: E::Id,
861 full_conflicted_set: &HashSet<E::Id>,
862 fetch_event: impl Fn(&EventId) -> Option<E>,
863) {
864 let mut state = vec![event_id];
865
866 // Iterate through the auth chain of the event.
867 while let Some(event_id) = state.pop() {
868 // Add the current event to the graph.
869 graph.entry(event_id.clone()).or_default();
870
871 // Iterate through the auth events of this event.
872 for auth_event_id in fetch_event(event_id.borrow())
873 .as_ref()
874 .map(|event| event.auth_events())
875 .into_iter()
876 .flatten()
877 {
878 // If the auth event ID is in the full conflicted set…
879 if full_conflicted_set.contains(auth_event_id.borrow()) {
880 // If the auth event ID is not in the graph, we need to check its auth events later.
881 if !graph.contains_key(auth_event_id.borrow()) {
882 state.push(auth_event_id.to_owned());
883 }
884
885 // Add the auth event ID to the list of incoming edges.
886 graph.get_mut(event_id.borrow()).unwrap().insert(auth_event_id.to_owned());
887 }
888 }
889 }
890}
891
892/// Whether the given event ID belongs to a power event.
893///
894/// See the docs of `is_power_event()` for the definition of a power event.
895fn is_power_event_id<E: Event>(event_id: &EventId, fetch: impl Fn(&EventId) -> Option<E>) -> bool {
896 match fetch(event_id).as_ref() {
897 Some(state) => is_power_event(state),
898 _ => false,
899 }
900}
901
902fn is_type_and_key(event: impl Event, event_type: &TimelineEventType, state_key: &str) -> bool {
903 event.event_type() == event_type && event.state_key() == Some(state_key)
904}
905
906/// Whether the given event is a power event.
907///
908/// Definition in the spec:
909///
910/// > A power event is a state event with type `m.room.power_levels` or `m.room.join_rules`, or a
911/// > state event with type `m.room.member` where the `membership` is `leave` or `ban` and the
912/// > `sender` does not match the `state_key`. The idea behind this is that power events are events
913/// > that might remove someone’s ability to do something in the room.
914fn is_power_event(event: impl Event) -> bool {
915 match event.event_type() {
916 TimelineEventType::RoomPowerLevels
917 | TimelineEventType::RoomJoinRules
918 | TimelineEventType::RoomCreate => event.state_key() == Some(""),
919 TimelineEventType::RoomMember => {
920 let room_member_event = RoomMemberEvent::new(event);
921 if room_member_event.membership().is_ok_and(|membership| {
922 matches!(membership, MembershipState::Leave | MembershipState::Ban)
923 }) {
924 return Some(room_member_event.sender().as_str()) != room_member_event.state_key();
925 }
926
927 false
928 }
929 _ => false,
930 }
931}
932
933/// Convenience trait for adding event type plus state key to state maps.
934pub(crate) trait EventTypeExt {
935 fn with_state_key(self, state_key: impl Into<String>) -> (StateEventType, String);
936}
937
938impl EventTypeExt for StateEventType {
939 fn with_state_key(self, state_key: impl Into<String>) -> (StateEventType, String) {
940 (self, state_key.into())
941 }
942}
943
944impl EventTypeExt for TimelineEventType {
945 fn with_state_key(self, state_key: impl Into<String>) -> (StateEventType, String) {
946 (self.to_string().into(), state_key.into())
947 }
948}
949
950impl<T> EventTypeExt for &T
951where
952 T: EventTypeExt + Clone,
953{
954 fn with_state_key(self, state_key: impl Into<String>) -> (StateEventType, String) {
955 self.to_owned().with_state_key(state_key)
956 }
957}