Skip to main content

tuwunel_service/server_keys/
verify.rs

1//! Event-ID derivation and federation signature verification.
2//!
3//! Verification resolves required signing keys through the server-key service
4//! and applies room-version signature rules. The local-keys validator returns
5//! an event in the form this server stores it, redacted when its content hash
6//! does not match.
7
8use ruma::{
9	CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, RoomVersionId,
10	canonical_json::redact,
11	room_version_rules::RoomVersionRules,
12	signatures::{Verified, verify_event},
13};
14use serde_json::value::RawValue as RawJsonValue;
15use tuwunel_core::{Err, Result, err, implement};
16use tuwunel_matrix::{event::gen_event_id_canonical_json, room_version};
17
18/// An event's derived ID, its stored form, and how it verified.
19///
20/// The stored form of a [`Verified::Signatures`] event is its redaction.
21type Validated = (OwnedEventId, CanonicalJsonObject, Verified);
22
23/// Derives and checks an event using only keys already in local storage.
24///
25/// The method rejects the event before verification when any required key is
26/// absent. The stored form drops the sender's `unsigned` data and is redacted
27/// when the content hash does not match, as for any other received event; newer
28/// room versions then receive the derived `event_id`.
29#[implement(super::Service)]
30pub async fn validate_and_add_event_id_no_fetch(
31	&self,
32	pdu: &RawJsonValue,
33	room_version_id: &RoomVersionId,
34) -> Result<Validated> {
35	let (event_id, value) = gen_event_id_canonical_json(pdu, room_version_id)?;
36	let room_version_rules = room_version::rules(room_version_id)?;
37
38	if !self
39		.required_keys_exist(&value, &room_version_rules)
40		.await
41	{
42		return Err!(BadServerResponse(debug_warn!(
43			"Event {event_id} cannot be verified: missing keys."
44		)));
45	}
46
47	let verified = self
48		.verify_event(&value, Some(room_version_id))
49		.await
50		.map_err(|error| {
51			err!(BadServerResponse(debug_error!(%event_id, ?error, "Event failed verification")))
52		})?;
53
54	stored_form(value, &event_id, &verified, &room_version_rules)
55		.map(|value| (event_id, value, verified))
56}
57
58/// Verifies an event and returns ruma's verification classification.
59///
60/// Required keys are loaded or fetched through [`Self::get_event_keys`]. When
61/// no room version is supplied, version 11 rules are used. Callers must inspect
62/// [`Verified`] to distinguish complete verification from signatures only.
63#[implement(super::Service)]
64pub async fn verify_event(
65	&self,
66	event: &CanonicalJsonObject,
67	room_version_id: Option<&RoomVersionId>,
68) -> Result<Verified> {
69	let room_version_id = room_version_id.unwrap_or(&RoomVersionId::V11);
70	let room_version_rules = room_version::rules(room_version_id)?;
71
72	let event_keys = self
73		.get_event_keys(event, &room_version_rules)
74		.await?;
75
76	verify_event(&event_keys, event, &room_version_rules).map_err(Into::into)
77}
78
79/// Verifies signatures on a canonical JSON object.
80///
81/// Unlike [`Self::verify_event`], this does not verify an event content hash.
82/// Version 11 signature rules are used when no room version is supplied.
83#[implement(super::Service)]
84pub async fn verify_json(
85	&self,
86	event: &CanonicalJsonObject,
87	room_version_id: Option<&RoomVersionId>,
88) -> Result {
89	let room_version_id = room_version_id.unwrap_or(&RoomVersionId::V11);
90	let room_version_rules = room_version::rules(room_version_id)?;
91
92	let event_keys = self
93		.get_event_keys(event, &room_version_rules)
94		.await?;
95
96	ruma::signatures::verify_json(&event_keys, event).map_err(Into::into)
97}
98
99/// Builds the stored form of a verified event from the received one.
100///
101/// The event ID was derived from the received form, so nothing done here can
102/// change it.
103fn stored_form(
104	mut value: CanonicalJsonObject,
105	event_id: &EventId,
106	verified: &Verified,
107	room_version_rules: &RoomVersionRules,
108) -> Result<CanonicalJsonObject> {
109	value.remove("unsigned");
110
111	if *verified == Verified::Signatures {
112		value = redact(value, &room_version_rules.redaction, None).map_err(|error| {
113			err!(BadServerResponse(
114				debug_error!(%event_id, %error, "Event could not be redacted")
115			))
116		})?;
117	}
118
119	// For v3+ rooms we add the event_id, but for v1/v2 rooms it's already present.
120	if !room_version_rules.event_format.require_event_id {
121		value.insert("event_id".into(), CanonicalJsonValue::String(event_id.as_str().into()));
122	}
123
124	Ok(value)
125}