Skip to main content

tuwunel_service/membership/
stripped_state.rs

1use std::{
2	borrow::Cow,
3	collections::{HashMap, hash_map::Entry},
4};
5
6use ruma::{
7	CanonicalJsonObject, CanonicalJsonValue, OwnedRoomId, RoomId, RoomVersionId, UserId,
8	api::federation::membership::RawStrippedState,
9	events::{AnyStrippedStateEvent, StateEventType, StateKey},
10	room_version_rules::RoomIdFormatVersion,
11	serde::{JsonObject, Raw},
12};
13use serde::Deserialize;
14use tuwunel_core::{Result, implement};
15use tuwunel_matrix::{Event, PduEvent, event::gen_event_id};
16
17use super::Service;
18
19/// The `(type, state_key)` pair naming one cell of a room's state.
20type StateCell = (StateEventType, StateKey);
21
22/// The chosen entry per cell, and the entries chosen so far in array order.
23type Accumulator = (HashMap<StateCell, usize>, Vec<RawStrippedState>);
24
25/// The cell an entry names, borrowed where its JSON needs no unescaping.
26#[derive(Deserialize)]
27struct Cell<'a> {
28	#[serde(rename = "type", borrow)]
29	kind: Cow<'a, str>,
30
31	#[serde(borrow)]
32	state_key: Cow<'a, str>,
33}
34
35/// MSC4311 verdict for the create event carried in federated stripped state.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum StrippedCreateVerdict {
38	/// A full create PDU bound to the room with valid signatures.
39	Valid,
40
41	/// No `m.room.create` event was present.
42	Missing,
43
44	/// A create event was present only in the legacy stripped form.
45	NotPdu,
46
47	/// A create PDU was present but does not bind to the room.
48	WrongRoom,
49
50	/// A create PDU was present but failed signature or hash checks.
51	BadSignature,
52}
53
54/// Whether a non-`Valid` verdict warrants rejecting an invite or dropping the
55/// event from knock state, given the room version and operator policy.
56#[must_use]
57pub fn enforce_stripped_create(
58	verdict: StrippedCreateVerdict,
59	v12_room_ids: bool,
60	enforce: bool,
61) -> bool {
62	use StrippedCreateVerdict::*;
63
64	match verdict {
65		| Valid => false,
66		// A v12+ room's stripped state must carry a create event, and a full PDU
67		// must bind to this room, even during the migration window (MSC4311).
68		| Missing | WrongRoom => v12_room_ids || enforce,
69		| NotPdu | BadSignature => enforce,
70	}
71}
72
73/// Whether the room version derives room ids from the create event hash
74/// (MSC4291, room version 12 and above), which changes how a create event
75/// binds to its room.
76#[must_use]
77pub fn v12_room_ids(room_version: &RoomVersionId) -> bool {
78	room_version
79		.rules()
80		.is_some_and(|rules| matches!(rules.room_id_format, RoomIdFormatVersion::V2))
81}
82
83/// Collapse a federated stripped-state array to one entry per state cell.
84///
85/// The array is state, so two entries sharing a cell are already malformed, and
86/// which one a consumer obeys is otherwise decided by its own pick strategy
87/// against an ordering the spec never gives.
88///
89/// A cell's first full PDU wins, and only a cell holding no PDU keeps its first
90/// legacy entry. An entry naming no readable cell, missing either half, drops:
91/// it addresses no state, and reading a missing `state_key` as the empty one
92/// would let a non-state event occupy a real cell and displace it.
93#[must_use]
94pub fn dedup_stripped_state(state: Vec<RawStrippedState>) -> Vec<RawStrippedState> {
95	let (_, kept) = state
96		.into_iter()
97		.filter_map(|entry| state_cell(&entry).map(|cell| (cell, entry)))
98		.fold(Accumulator::default(), |(mut chosen, mut kept), (cell, entry)| {
99			match chosen.entry(cell) {
100				| Entry::Vacant(vacant) => {
101					vacant.insert(kept.len());
102					kept.push(entry);
103				},
104				| Entry::Occupied(occupied) => {
105					let held = &mut kept[*occupied.get()];
106
107					if is_legacy(held) && !is_legacy(&entry) {
108						*held = entry;
109					}
110				},
111			}
112
113			(chosen, kept)
114		});
115
116	kept
117}
118
119/// Drop the entries occupying a user's membership cell.
120///
121/// The invite route appends its own copy of that event, whose sender the origin
122/// check bound to the sending server, so a copy the sending server chose is
123/// never the one to serve.
124pub fn without_member(
125	state: Vec<RawStrippedState>,
126	user_id: &UserId,
127) -> impl Iterator<Item = RawStrippedState> {
128	state
129		.into_iter()
130		.filter(move |entry| !occupies_cell(entry, &StateEventType::RoomMember, user_id.as_str()))
131}
132
133fn state_cell(state: &RawStrippedState) -> Option<StateCell> {
134	cell(state).map(|cell| (cell.kind.as_ref().into(), cell.state_key.as_ref().into()))
135}
136
137pub(super) fn occupies_cell(
138	state: &RawStrippedState,
139	kind: &StateEventType,
140	state_key: &str,
141) -> bool {
142	cell(state).is_some_and(|cell| {
143		cell.state_key == state_key && StateEventType::from(cell.kind.as_ref()) == *kind
144	})
145}
146
147/// The cell an entry names, borrowed out of the entry's own JSON.
148///
149/// Borrowing keeps a sender-supplied array off the heap for the comparisons
150/// that only need to read a cell. [`state_cell`] pays for an owned copy, which
151/// only the dedup map needs.
152fn cell(state: &RawStrippedState) -> Option<Cell<'_>> {
153	serde_json::from_str(entry_json(state)).ok()
154}
155
156#[expect(
157	deprecated,
158	reason = "Matrix 1.16 still permits receiving the legacy stripped variant for backwards \
159	          compatibility."
160)]
161fn entry_json(state: &RawStrippedState) -> &str {
162	match state {
163		| RawStrippedState::Stripped(raw) => raw.json().get(),
164		| RawStrippedState::Pdu(raw) => raw.get(),
165	}
166}
167
168#[expect(
169	deprecated,
170	reason = "Matrix 1.16 still permits receiving the legacy stripped variant for backwards \
171	          compatibility."
172)]
173fn is_legacy(state: &RawStrippedState) -> bool { matches!(state, RawStrippedState::Stripped(_)) }
174
175/// Down-convert a federation stripped-state entry to the 4-field client shape,
176/// reducing a full PDU to content, sender, optional state_key, and type.
177#[expect(
178	deprecated,
179	reason = "Matrix 1.16 still permits receiving the legacy stripped variant for backwards \
180	          compatibility."
181)]
182#[must_use]
183pub fn into_client_stripped(
184	room_id: &RoomId,
185	state: RawStrippedState,
186) -> Option<Raw<AnyStrippedStateEvent>> {
187	match state {
188		| RawStrippedState::Stripped(raw) => Some(raw),
189		| RawStrippedState::Pdu(raw) => {
190			let mut event: JsonObject = serde_json::from_str(raw.get()).ok()?;
191
192			// PduEvent requires event_id and room_id; a v12 create PDU federates
193			// with neither, and to_format() drops both from the stripped shape.
194			event.insert("event_id".into(), "$placeholder".into());
195			event
196				.entry("room_id")
197				.or_insert_with(|| room_id.as_str().into());
198
199			let pdu: PduEvent = serde_json::from_value(event.into()).ok()?;
200
201			Some(pdu.to_format())
202		},
203	}
204}
205
206/// Validate the `m.room.create` event in a federated invite's or knock's
207/// stripped state against the stated room (MSC4311). Decision-free: callers map
208/// the verdict to their own reject-or-warn policy.
209#[implement(Service)]
210#[expect(
211	deprecated,
212	reason = "Matrix 1.16 still permits receiving the legacy stripped variant for backwards \
213	          compatibility."
214)]
215#[tracing::instrument(level = "debug", skip_all, fields(%room_id))]
216pub async fn validate_stripped_create(
217	&self,
218	state: &[RawStrippedState],
219	room_id: &RoomId,
220	room_version_id: &RoomVersionId,
221) -> Result<StrippedCreateVerdict> {
222	let create = state.iter().find_map(|event| match event {
223		| RawStrippedState::Pdu(raw) => serde_json::from_str::<CanonicalJsonObject>(raw.get())
224			.ok()
225			.filter(is_create),
226		| RawStrippedState::Stripped(_) => None,
227	});
228
229	let Some(mut create) = create else {
230		let stripped = state.iter().any(|event| match event {
231			| RawStrippedState::Stripped(raw) =>
232				serde_json::from_str::<CanonicalJsonObject>(raw.json().get())
233					.is_ok_and(|json| is_create(&json)),
234			| RawStrippedState::Pdu(_) => false,
235		});
236
237		return Ok(match stripped {
238			| true => StrippedCreateVerdict::NotPdu,
239			| false => StrippedCreateVerdict::Missing,
240		});
241	};
242
243	create.remove("unsigned");
244
245	// Room-id binding: v12+ rooms hash the create event (MSC4291); earlier
246	// versions compare the create event's room_id field.
247	let bound = if v12_room_ids(room_version_id) {
248		gen_event_id(&create, room_version_id)
249			.ok()
250			.and_then(|event_id| OwnedRoomId::from_parts('!', event_id.localpart(), None).ok())
251			.is_some_and(|expected| expected == room_id)
252	} else {
253		create
254			.get("room_id")
255			.and_then(CanonicalJsonValue::as_str)
256			.is_some_and(|id| id == room_id.as_str())
257	};
258
259	if !bound {
260		return Ok(StrippedCreateVerdict::WrongRoom);
261	}
262
263	if self
264		.services
265		.server_keys
266		.verify_event(&create, Some(room_version_id))
267		.await
268		.is_err()
269	{
270		return Ok(StrippedCreateVerdict::BadSignature);
271	}
272
273	Ok(StrippedCreateVerdict::Valid)
274}
275
276fn is_create(json: &CanonicalJsonObject) -> bool {
277	let field = |key| json.get(key).and_then(CanonicalJsonValue::as_str);
278
279	field("type") == Some("m.room.create") && field("state_key") == Some("")
280}
281
282#[cfg(test)]
283#[expect(
284	deprecated,
285	reason = "Matrix 1.16 still permits receiving the legacy stripped variant for backwards \
286	          compatibility."
287)]
288mod tests {
289	use ruma::{
290		api::federation::membership::RawStrippedState, events::StateEventType, serde::Raw,
291		user_id,
292	};
293	use serde_json::{Value as JsonValue, json, value::RawValue as RawJsonValue};
294
295	use super::{
296		StrippedCreateVerdict::{Missing, NotPdu, WrongRoom},
297		dedup_stripped_state, enforce_stripped_create, entry_json, is_legacy, occupies_cell,
298		state_cell, without_member,
299	};
300
301	#[test]
302	fn a_missing_create_rejects_in_v12_rooms_without_enforcement() {
303		assert!(enforce_stripped_create(Missing, true, false));
304		assert!(enforce_stripped_create(WrongRoom, true, false));
305		assert!(!enforce_stripped_create(NotPdu, true, false));
306		assert!(!enforce_stripped_create(Missing, false, false));
307		assert!(enforce_stripped_create(Missing, false, true));
308	}
309
310	#[test]
311	fn a_cells_first_pdu_wins_over_an_earlier_legacy_entry() {
312		let deduped = dedup_stripped_state(vec![
313			legacy(&create("@forged:example.org")),
314			pdu(&create("@genuine:example.org")),
315		]);
316
317		assert_eq!(senders(&deduped), ["@genuine:example.org"]);
318	}
319
320	#[test]
321	fn a_cell_holding_no_pdu_keeps_its_first_legacy_entry() {
322		let deduped = dedup_stripped_state(vec![
323			legacy(&create("@first:example.org")),
324			legacy(&create("@second:example.org")),
325		]);
326
327		assert_eq!(senders(&deduped), ["@first:example.org"]);
328	}
329
330	#[test]
331	fn distinct_cells_all_survive_in_order() {
332		let deduped = dedup_stripped_state(vec![
333			pdu(&create("@creator:example.org")),
334			pdu(&member("@alice:example.org", "@alice:example.org")),
335			pdu(&member("@bob:example.org", "@alice:example.org")),
336		]);
337
338		assert_eq!(deduped.len(), 3);
339		assert_eq!(state_cell(&deduped[0]).expect("a cell").0, StateEventType::RoomCreate);
340	}
341
342	#[test]
343	fn an_entry_without_a_readable_cell_drops() {
344		let deduped = dedup_stripped_state(vec![
345			pdu(&json!({"sender": "@alice:example.org", "content": {}})),
346			pdu(&create("@creator:example.org")),
347		]);
348
349		assert_eq!(senders(&deduped), ["@creator:example.org"]);
350	}
351
352	#[test]
353	fn the_invitees_membership_cell_never_survives() {
354		let state = vec![
355			pdu(&member("@invitee:example.org", "@forged:example.org")),
356			pdu(&member("@other:example.org", "@alice:example.org")),
357			pdu(&create("@creator:example.org")),
358		];
359
360		let kept: Vec<_> = without_member(state, user_id!("@invitee:example.org")).collect();
361
362		assert_eq!(senders(&kept), ["@alice:example.org", "@creator:example.org"]);
363	}
364
365	#[test]
366	fn an_all_legacy_array_survives_with_every_cell_intact() {
367		let name = json!({
368			"type": "m.room.name",
369			"state_key": "",
370			"sender": "@creator:example.org",
371			"content": {"name": "a room"},
372		});
373
374		let deduped = dedup_stripped_state(vec![
375			legacy(&create("@creator:example.org")),
376			legacy(&member("@alice:example.org", "@alice:example.org")),
377			legacy(&name),
378		]);
379
380		assert_eq!(deduped.len(), 3);
381		assert!(deduped.iter().all(is_legacy));
382		assert_eq!(senders(&deduped), [
383			"@creator:example.org",
384			"@alice:example.org",
385			"@creator:example.org"
386		]);
387	}
388
389	#[test]
390	fn a_cell_spelled_with_escapes_still_reads() {
391		// "m.room.member" with an escaped 'm', which a borrowing deserializer
392		// cannot read out of the source buffer.
393		let escaped = raw_pdu(
394			r#"{"type":"m.room.\u006dember","state_key":"@invitee:example.org",
395			   "sender":"@forged:example.org","content":{"membership":"invite"}}"#,
396		);
397
398		let invitee = user_id!("@invitee:example.org");
399
400		assert!(occupies_cell(&escaped, &StateEventType::RoomMember, invitee.as_str()));
401
402		assert!(
403			without_member(vec![escaped], invitee)
404				.next()
405				.is_none()
406		);
407	}
408
409	fn legacy(event: &JsonValue) -> RawStrippedState {
410		RawStrippedState::Stripped(
411			Raw::new(event)
412				.expect("valid json")
413				.cast_unchecked(),
414		)
415	}
416
417	fn raw_pdu(json: &str) -> RawStrippedState {
418		RawStrippedState::Pdu(RawJsonValue::from_string(json.to_owned()).expect("valid json"))
419	}
420
421	fn pdu(event: &JsonValue) -> RawStrippedState {
422		RawStrippedState::Pdu(
423			Raw::<JsonValue>::new(event)
424				.expect("valid json")
425				.into_json(),
426		)
427	}
428
429	fn create(sender: &str) -> JsonValue {
430		json!({"type": "m.room.create", "state_key": "", "sender": sender, "content": {}})
431	}
432
433	fn member(user_id: &str, sender: &str) -> JsonValue {
434		json!({
435			"type": "m.room.member",
436			"state_key": user_id,
437			"sender": sender,
438			"content": {"membership": "invite"},
439		})
440	}
441
442	fn senders(state: &[RawStrippedState]) -> Vec<String> {
443		state
444			.iter()
445			.map(|entry| {
446				let value: JsonValue =
447					serde_json::from_str(entry_json(entry)).expect("valid json");
448
449				value["sender"]
450					.as_str()
451					.expect("a sender")
452					.to_owned()
453			})
454			.collect()
455	}
456}