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 room_version_rules::{AuthorizationRules, StateResolutionV2Rules},
11 EventId, MilliSecondsSinceUnixEpoch, OwnedUserId,
12};
13use ruma_events::{
14 room::{member::MembershipState, power_levels::UserPowerLevel},
15 StateEventType, TimelineEventType,
16};
17use tracing::{debug, info, instrument, trace, warn};
18
19#[cfg(test)]
20mod tests;
21
22use crate::{
23 auth_types_for_event, check_state_dependent_auth_rules,
24 events::{
25 power_levels::RoomPowerLevelsEventOptionExt, RoomCreateEvent, RoomMemberEvent,
26 RoomPowerLevelsEvent, RoomPowerLevelsIntField,
27 },
28 utils::RoomIdExt,
29 Error, Event, Result,
30};
31
32/// A mapping of event type and state_key to some value `T`, usually an `EventId`.
33///
34/// This is the representation of what the Matrix specification calls a "room state" or a "state
35/// map" during [state resolution].
36///
37/// [state resolution]: https://spec.matrix.org/latest/rooms/v2/#state-resolution
38pub type StateMap<T> = HashMap<(StateEventType, String), T>;
39
40/// Apply the [state resolution] algorithm introduced in room version 2 to resolve the state of a
41/// room.
42///
43/// ## Arguments
44///
45/// * `auth_rules` - The authorization rules to apply for the version of the current room.
46///
47/// * `state_res_rules` - The state resolution rules to apply for the version of the current room.
48///
49/// * `state_maps` - The incoming states to resolve. Each `StateMap` represents a possible fork in
50/// the state of a room.
51///
52/// * `auth_chains` - The list of full recursive sets of `auth_events` for each event in the
53/// `state_maps`.
54///
55/// * `fetch_event` - Function to fetch an event in the room given its event ID.
56///
57/// * `fetch_conflicted_state_subgraph` - Function to fetch the conflicted state subgraph for the
58/// given conflicted state set, for state resolution rules that use it. If it is called and
59/// returns `None`, this function will return an error.
60///
61/// ## Invariants
62///
63/// The caller of `resolve` must ensure that all the events are from the same room.
64///
65/// ## Returns
66///
67/// The resolved room state.
68///
69/// [state resolution]: https://spec.matrix.org/latest/rooms/v2/#state-resolution
70#[instrument(skip_all)]
71pub fn resolve<'a, E, MapsIter>(
72 auth_rules: &AuthorizationRules,
73 state_res_rules: &StateResolutionV2Rules,
74 state_maps: impl IntoIterator<IntoIter = MapsIter>,
75 auth_chains: Vec<HashSet<E::Id>>,
76 fetch_event: impl Fn(&EventId) -> Option<E>,
77 fetch_conflicted_state_subgraph: impl Fn(&StateMap<Vec<E::Id>>) -> Option<HashSet<E::Id>>,
78) -> Result<StateMap<E::Id>>
79where
80 E: Event + Clone,
81 E::Id: 'a,
82 MapsIter: Iterator<Item = &'a StateMap<E::Id>> + Clone,
83{
84 info!("state resolution starting");
85
86 // Split the unconflicted state map and the conflicted state set.
87 let (unconflicted_state_map, conflicted_state_set) =
88 split_conflicted_state_set(state_maps.into_iter());
89
90 info!(count = unconflicted_state_map.len(), "unconflicted events");
91 trace!(map = ?unconflicted_state_map, "unconflicted events");
92
93 if conflicted_state_set.is_empty() {
94 info!("no conflicted state found");
95 return Ok(unconflicted_state_map);
96 }
97
98 info!(count = conflicted_state_set.len(), "conflicted events");
99 trace!(map = ?conflicted_state_set, "conflicted events");
100
101 // Since v12, fetch the conflicted state subgraph.
102 let conflicted_state_subgraph = if state_res_rules.consider_conflicted_state_subgraph {
103 let conflicted_state_subgraph = fetch_conflicted_state_subgraph(&conflicted_state_set)
104 .ok_or(Error::FetchConflictedStateSubgraphFailed)?;
105
106 info!(count = conflicted_state_subgraph.len(), "events in conflicted state subgraph");
107 trace!(set = ?conflicted_state_subgraph, "conflicted state subgraph");
108
109 conflicted_state_subgraph
110 } else {
111 HashSet::new()
112 };
113
114 // The full conflicted set is the union of the conflicted state set and the auth difference,
115 // and since v12, the conflicted state subgraph.
116 let full_conflicted_set: HashSet<_> = auth_difference(auth_chains)
117 .chain(conflicted_state_set.into_values().flatten())
118 .chain(conflicted_state_subgraph)
119 // Don't honor events we cannot "verify"
120 .filter(|id| fetch_event(id.borrow()).is_some())
121 .collect();
122
123 info!(count = full_conflicted_set.len(), "full conflicted set");
124 trace!(set = ?full_conflicted_set, "full conflicted set");
125
126 // 1. Select the set X of all power events that appear in the full conflicted set. For each such
127 // power event P, enlarge X by adding the events in the auth chain of P which also belong to
128 // the full conflicted set. Sort X into a list using the reverse topological power ordering.
129 let conflicted_power_events = full_conflicted_set
130 .iter()
131 .filter(|&id| is_power_event_id(id.borrow(), &fetch_event))
132 .cloned()
133 .collect::<Vec<_>>();
134
135 let sorted_power_events =
136 sort_power_events(conflicted_power_events, &full_conflicted_set, auth_rules, &fetch_event)?;
137
138 debug!(count = sorted_power_events.len(), "power events");
139 trace!(list = ?sorted_power_events, "sorted power events");
140
141 // 2. Apply the iterative auth checks algorithm, starting from the unconflicted state map, to
142 // the list of events from the previous step to get a partially resolved state.
143
144 // Since v12, begin the first phase of iterative auth checks with an empty state map.
145 let initial_state_map = if state_res_rules.begin_iterative_auth_checks_with_empty_state_map {
146 HashMap::new()
147 } else {
148 unconflicted_state_map.clone()
149 };
150
151 let partially_resolved_state =
152 iterative_auth_checks(auth_rules, &sorted_power_events, initial_state_map, &fetch_event)?;
153
154 debug!(count = partially_resolved_state.len(), "resolved power events");
155 trace!(map = ?partially_resolved_state, "resolved power events");
156
157 // 3. Take all remaining events that weren’t picked in step 1 and order them by the mainline
158 // ordering based on the power level in the partially resolved state obtained in step 2.
159 let sorted_power_events_set = sorted_power_events.into_iter().collect::<HashSet<_>>();
160 let remaining_events = full_conflicted_set
161 .iter()
162 .filter(|&id| !sorted_power_events_set.contains(id.borrow()))
163 .cloned()
164 .collect::<Vec<_>>();
165
166 debug!(count = remaining_events.len(), "events left to resolve");
167 trace!(list = ?remaining_events, "events left to resolve");
168
169 // This "epochs" power level event
170 let power_event = partially_resolved_state.get(&(StateEventType::RoomPowerLevels, "".into()));
171
172 debug!(event_id = ?power_event, "power event");
173
174 let sorted_remaining_events =
175 mainline_sort(&remaining_events, power_event.cloned(), &fetch_event)?;
176
177 trace!(list = ?sorted_remaining_events, "events left, sorted");
178
179 // 4. Apply the iterative auth checks algorithm on the partial resolved state and the list of
180 // events from the previous step.
181 let mut resolved_state = iterative_auth_checks(
182 auth_rules,
183 &sorted_remaining_events,
184 partially_resolved_state,
185 &fetch_event,
186 )?;
187
188 // 5. Update the result by replacing any event with the event with the same key from the
189 // unconflicted state map, if such an event exists, to get the final resolved state.
190 resolved_state.extend(unconflicted_state_map);
191
192 info!("state resolution finished");
193
194 Ok(resolved_state)
195}
196
197/// Split the unconflicted state map and the conflicted state set.
198///
199/// Definition in the specification:
200///
201/// > If a given key _K_ is present in every _Si_ with the same value _V_ in each state map, then
202/// > the pair (_K_, _V_) belongs to the unconflicted state map. Otherwise, _V_ belongs to the
203/// > conflicted state set.
204///
205/// It means that, for a given (event type, state key) tuple, if all state maps have the same event
206/// ID, it lands in the unconflicted state map, otherwise the event IDs land in the conflicted state
207/// set.
208///
209/// ## Arguments
210///
211/// * `state_maps` - The incoming states to resolve. Each `StateMap` represents a possible fork in
212/// the state of a room.
213///
214/// ## Returns
215///
216/// Returns an `(unconflicted_state_map, conflicted_state_set)` tuple.
217fn split_conflicted_state_set<'a, Id>(
218 state_maps: impl Iterator<Item = &'a StateMap<Id>>,
219) -> (StateMap<Id>, StateMap<Vec<Id>>)
220where
221 Id: Clone + Eq + Hash + 'a,
222{
223 let mut state_set_count = 0_usize;
224 let mut occurrences = HashMap::<_, HashMap<_, _>>::new();
225
226 let state_maps = state_maps.inspect(|_| state_set_count += 1);
227 for (k, v) in state_maps.flatten() {
228 occurrences.entry(k).or_default().entry(v).and_modify(|x| *x += 1).or_insert(1);
229 }
230
231 let mut unconflicted_state_map = StateMap::new();
232 let mut conflicted_state_set = StateMap::new();
233
234 for (k, v) in occurrences {
235 for (id, occurrence_count) in v {
236 if occurrence_count == state_set_count {
237 unconflicted_state_map.insert((k.0.clone(), k.1.clone()), id.clone());
238 } else {
239 conflicted_state_set
240 .entry((k.0.clone(), k.1.clone()))
241 .and_modify(|x: &mut Vec<_>| x.push(id.clone()))
242 .or_insert(vec![id.clone()]);
243 }
244 }
245 }
246
247 (unconflicted_state_map, conflicted_state_set)
248}
249
250/// Get the auth difference for the given auth chains.
251///
252/// Definition in the specification:
253///
254/// > The auth difference is calculated by first calculating the full auth chain for each state
255/// > _Si_, that is the union of the auth chains for each event in _Si_, and then taking every event
256/// > that doesn’t appear in every auth chain. If _Ci_ is the full auth chain of _Si_, then the auth
257/// > difference is ∪_Ci_ − ∩_Ci_.
258///
259/// ## Arguments
260///
261/// * `auth_chains` - The list of full recursive sets of `auth_events`.
262///
263/// ## Returns
264///
265/// Returns an iterator over all the event IDs that are not present in all the auth chains.
266fn auth_difference<Id>(auth_chains: Vec<HashSet<Id>>) -> impl Iterator<Item = Id>
267where
268 Id: Eq + Hash,
269{
270 let num_sets = auth_chains.len();
271
272 let mut id_counts: HashMap<Id, usize> = HashMap::new();
273 for id in auth_chains.into_iter().flatten() {
274 *id_counts.entry(id).or_default() += 1;
275 }
276
277 id_counts.into_iter().filter_map(move |(id, count)| (count < num_sets).then_some(id))
278}
279
280/// Enlarge the given list of conflicted power events by adding the events in their auth chain that
281/// are in the full conflicted set, and sort it using reverse topological power ordering.
282///
283/// ## Arguments
284///
285/// * `conflicted_power_events` - The list of power events in the full conflicted set.
286///
287/// * `full_conflicted_set` - The full conflicted set.
288///
289/// * `rules` - The authorization rules for the current room version.
290///
291/// * `fetch_event` - Function to fetch an event in the room given its event ID.
292///
293/// ## Returns
294///
295/// Returns the ordered list of event IDs from earliest to latest.
296#[instrument(skip_all)]
297fn sort_power_events<E: Event>(
298 conflicted_power_events: Vec<E::Id>,
299 full_conflicted_set: &HashSet<E::Id>,
300 rules: &AuthorizationRules,
301 fetch_event: impl Fn(&EventId) -> Option<E>,
302) -> Result<Vec<E::Id>> {
303 debug!("reverse topological sort of power events");
304
305 // A representation of the DAG, a map of event ID to its list of auth events that are in the
306 // full conflicted set.
307 let mut graph = HashMap::new();
308
309 // Fill the graph.
310 for event_id in conflicted_power_events {
311 add_event_and_auth_chain_to_graph(&mut graph, event_id, full_conflicted_set, &fetch_event);
312
313 // TODO: if these functions are ever made async here
314 // is a good place to yield every once in a while so other
315 // tasks can make progress
316 }
317
318 // The map of event ID to the power level of the sender of the event.
319 let mut event_to_power_level = HashMap::new();
320 // We need to know the creator in case of missing power levels. Given that it's the same for all
321 // the events in the room, we will just load it for the first event and reuse it.
322 let creators_lock = OnceLock::new();
323
324 // Get the power level of the sender of each event in the graph.
325 for event_id in graph.keys() {
326 let sender_power_level =
327 power_level_for_sender(event_id.borrow(), rules, &creators_lock, &fetch_event)
328 .map_err(Error::AuthEvent)?;
329 debug!(
330 event_id = event_id.borrow().as_str(),
331 power_level = ?sender_power_level,
332 "found the power level of an event's sender",
333 );
334
335 event_to_power_level.insert(event_id.clone(), sender_power_level);
336
337 // TODO: if these functions are ever made async here
338 // is a good place to yield every once in a while so other
339 // tasks can make progress
340 }
341
342 reverse_topological_power_sort(&graph, |event_id| {
343 let event = fetch_event(event_id).ok_or_else(|| Error::NotFound(event_id.to_owned()))?;
344 let power_level = *event_to_power_level
345 .get(event_id)
346 .ok_or_else(|| Error::NotFound(event_id.to_owned()))?;
347 Ok((power_level, event.origin_server_ts()))
348 })
349}
350
351/// Sorts the given event graph using reverse topological power ordering.
352///
353/// Definition in the specification:
354///
355/// > The reverse topological power ordering of a set of events is the lexicographically smallest
356/// > topological ordering based on the DAG formed by auth events. The reverse topological power
357/// > ordering is ordered from earliest event to latest. For comparing two topological orderings to
358/// > determine which is the lexicographically smallest, the following comparison relation on events
359/// > is used: for events x and y, x < y if
360/// >
361/// > 1. x’s sender has greater power level than y’s sender, when looking at their respective
362/// > auth_events; or
363/// > 2. the senders have the same power level, but x’s origin_server_ts is less than y’s
364/// > origin_server_ts; or
365/// > 3. the senders have the same power level and the events have the same origin_server_ts, but
366/// > x’s event_id is less than y’s event_id.
367/// >
368/// > The reverse topological power ordering can be found by sorting the events using Kahn’s
369/// > algorithm for topological sorting, and at each step selecting, among all the candidate
370/// > vertices, the smallest vertex using the above comparison relation.
371///
372/// ## Arguments
373///
374/// * `graph` - The graph to sort. A map of event ID to its auth events that are in the full
375/// conflicted set.
376///
377/// * `event_details_fn` - Function to obtain a (power level, origin_server_ts) of an event for
378/// breaking ties.
379///
380/// ## Returns
381///
382/// Returns the ordered list of event IDs from earliest to latest.
383#[instrument(skip_all)]
384pub fn reverse_topological_power_sort<Id, F>(
385 graph: &HashMap<Id, HashSet<Id>>,
386 event_details_fn: F,
387) -> Result<Vec<Id>>
388where
389 F: Fn(&EventId) -> Result<(UserPowerLevel, MilliSecondsSinceUnixEpoch)>,
390 Id: Clone + Eq + Ord + Hash + Borrow<EventId>,
391{
392 #[derive(PartialEq, Eq)]
393 struct TieBreaker<'a, Id> {
394 power_level: UserPowerLevel,
395 origin_server_ts: MilliSecondsSinceUnixEpoch,
396 event_id: &'a Id,
397 }
398
399 impl<Id> Ord for TieBreaker<'_, Id>
400 where
401 Id: Ord,
402 {
403 fn cmp(&self, other: &Self) -> Ordering {
404 // NOTE: the power level comparison is "backwards" intentionally.
405 other
406 .power_level
407 .cmp(&self.power_level)
408 .then(self.origin_server_ts.cmp(&other.origin_server_ts))
409 .then(self.event_id.cmp(other.event_id))
410 }
411 }
412
413 impl<Id> PartialOrd for TieBreaker<'_, Id>
414 where
415 Id: Ord,
416 {
417 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
418 Some(self.cmp(other))
419 }
420 }
421
422 // We consider that the DAG is directed from most recent events to oldest events, so an event is
423 // an incoming edge to its auth events.
424
425 // Map of event to the list of events in its auth events.
426 let mut outgoing_edges_map = graph.clone();
427
428 // Map of event to the list of events that reference it in its auth events.
429 let mut incoming_edges_map: HashMap<_, HashSet<_>> = HashMap::new();
430
431 // Vec of events that have an outdegree of zero (no outgoing edges), i.e. the oldest events.
432 let mut zero_outdegrees = Vec::new();
433
434 // Populate the list of events with an outdegree of zero, and the map of incoming edges.
435 for (event_id, outgoing_edges) in graph {
436 if outgoing_edges.is_empty() {
437 let (power_level, origin_server_ts) = event_details_fn(event_id.borrow())?;
438
439 // `Reverse` because `BinaryHeap` sorts largest -> smallest and we need
440 // smallest -> largest.
441 zero_outdegrees.push(Reverse(TieBreaker { power_level, origin_server_ts, event_id }));
442 }
443
444 incoming_edges_map.entry(event_id).or_default();
445
446 for auth_event_id in outgoing_edges {
447 incoming_edges_map.entry(auth_event_id).or_default().insert(event_id);
448 }
449 }
450
451 // Use a BinaryHeap to keep the events with an outdegree of zero sorted.
452 let mut heap = BinaryHeap::from(zero_outdegrees);
453 let mut sorted = vec![];
454
455 // Apply Kahn's algorithm.
456 // https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm
457 while let Some(Reverse(item)) = heap.pop() {
458 let event_id = item.event_id;
459
460 for &parent_id in incoming_edges_map
461 .get(event_id)
462 .expect("event ID in heap should also be in incoming edges map")
463 {
464 let outgoing_edges = outgoing_edges_map
465 .get_mut(parent_id.borrow())
466 .expect("outgoing edges map should have a key for all event IDs");
467
468 outgoing_edges.remove(event_id.borrow());
469
470 // Push on the heap once all the outgoing edges have been removed.
471 if outgoing_edges.is_empty() {
472 let (power_level, origin_server_ts) = event_details_fn(parent_id.borrow())?;
473 heap.push(Reverse(TieBreaker {
474 power_level,
475 origin_server_ts,
476 event_id: parent_id,
477 }));
478 }
479 }
480
481 sorted.push(event_id.clone());
482 }
483
484 Ok(sorted)
485}
486
487/// Find the power level for the sender of the event of the given event ID or return a default value
488/// of zero.
489///
490/// We find the most recent `m.room.power_levels` by walking backwards in the auth chain of the
491/// event.
492///
493/// Do NOT use this anywhere but topological sort.
494///
495/// ## Arguments
496///
497/// * `event_id` - The event ID of the event to get the power level of the sender of.
498///
499/// * `rules` - The authorization rules for the current room version.
500///
501/// * `creator_lock` - A lock used to cache the user ID of the creator of the room. If it is empty
502/// the creator will be fetched in the auth chain and used to populate the lock.
503///
504/// * `fetch_event` - Function to fetch an event in the room given its event ID.
505///
506/// ## Returns
507///
508/// Returns the power level of the sender of the event or an `Err(_)` if one of the auth events if
509/// malformed.
510fn power_level_for_sender<E: Event>(
511 event_id: &EventId,
512 rules: &AuthorizationRules,
513 creators_lock: &OnceLock<HashSet<OwnedUserId>>,
514 fetch_event: impl Fn(&EventId) -> Option<E>,
515) -> std::result::Result<UserPowerLevel, String> {
516 let event = fetch_event(event_id);
517 let mut room_create_event = None;
518 let mut room_power_levels_event = None;
519
520 if let Some(event) = &event {
521 if rules.room_create_event_id_as_room_id && creators_lock.get().is_none() {
522 // The m.room.create event is not in the auth events, we can get its ID via the room ID.
523 room_create_event = event
524 .room_id()
525 .and_then(|room_id| room_id.room_create_event_id().ok())
526 .and_then(|room_create_event_id| fetch_event(&room_create_event_id));
527 }
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 if let Ok(position) = mainline_position(event, &mainline_map, &fetch_event) {
766 order_map.insert(
767 event_id,
768 (
769 position,
770 fetch_event(event_id.borrow()).map(|event| event.origin_server_ts()),
771 event_id,
772 ),
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}