Skip to main content

tuwunel_service/fetcher/
validate.rs

1//! Two-tier response validation for fetched federation data.
2//!
3//! A cheap conformance check can cover every operation, followed by an opt-in
4//! deep PDU pass only for event and auth-event fetches. When either cryptographic
5//! flag is enabled, the deep pass invokes event verification, but currently
6//! ignores its `Verified` status and therefore does not reject a content-hash
7//! mismatch by itself.
8
9use ruma::{CanonicalJsonObject, RoomVersionId};
10use serde::de::IgnoredAny;
11use tuwunel_core::{Err, Result, err, implement};
12use tuwunel_matrix::event::gen_event_id;
13
14use super::{Op, Opts};
15
16/// Applies poison detection before a fetched response is accepted.
17///
18/// When `check_conforms` is enabled, malformed JSON rolls over to the next
19/// candidate; Backfill also rejects an empty batch while MissingEvents accepts
20/// one. Deep validation is limited to event and auth-event operations.
21#[implement(super::Service)]
22#[tracing::instrument(name = "validate", level = "trace", skip_all)]
23pub(super) async fn validate(&self, opts: &Opts, bytes: &[u8]) -> Result {
24	if opts.check_conforms {
25		match opts.op {
26			| Op::Backfill => serde_json::from_slice(bytes)
27				.map(|pdus: Vec<IgnoredAny>| !pdus.is_empty())
28				.map_err(|e| err!(BadServerResponse("malformed federation response: {e}")))
29				.and_then(|populated| {
30					populated
31						.then_some(())
32						.ok_or_else(|| err!(BadServerResponse("empty backfill response")))
33				}),
34			| _ => serde_json::from_slice(bytes)
35				.map(|_: IgnoredAny| ())
36				.map_err(|e| err!(BadServerResponse("malformed federation response: {e}"))),
37		}?;
38	}
39
40	let deep = opts.check_event_id || opts.check_hashes || opts.check_signature;
41	if matches!(opts.op, Op::Event | Op::AuthEvent) && deep {
42		self.verify_pdu(opts, bytes).await?;
43	}
44
45	Ok(())
46}
47
48/// Applies enabled event-ID and cryptographic checks to one PDU response.
49///
50/// Event verification errors are propagated, but its `Verified` classification
51/// is currently discarded, so `check_hashes` does not enforce a hash match.
52#[implement(super::Service)]
53#[tracing::instrument(level = "trace", skip_all)]
54async fn verify_pdu(&self, opts: &Opts, bytes: &[u8]) -> Result {
55	let value: CanonicalJsonObject = serde_json::from_slice(bytes)
56		.map_err(|e| err!(BadServerResponse("PDU is not a canonical JSON object: {e}")))?;
57
58	let v11 = RoomVersionId::V11;
59	let room_version = opts.room_version.as_ref().unwrap_or(&v11);
60
61	if opts.check_event_id
62		&& let Some(expected) = opts.event_id.as_ref()
63	{
64		let calculated = gen_event_id(&value, room_version)?;
65		if calculated != *expected {
66			return Err!(BadServerResponse("server returned the wrong event id"));
67		}
68	}
69
70	if opts.check_signature || opts.check_hashes {
71		self.services
72			.server_keys
73			.verify_event(&value, Some(room_version))
74			.await?;
75	}
76
77	Ok(())
78}