1use std::{
2 collections::BTreeMap,
3 time::{Duration, SystemTime, UNIX_EPOCH},
4};
5
6use http::StatusCode;
7use ruma::{
8 CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedServerName, RoomId, RoomVersionId,
9 ServerName, SigningKeyAlgorithm,
10 api::{
11 error::{ErrorKind, RetryAfter},
12 federation::policy::sign_event::v1 as sign_event,
13 },
14 events::{
15 StateEventType,
16 room::policy::{POLICY_SERVER_ED25519_SIGNING_KEY_ID, RoomPolicyEventContent},
17 },
18 serde::Base64,
19 signatures::{to_canonical_json_string_for_signing, verify_canonical_json_bytes},
20};
21use serde::{Deserialize, Serialize};
22use serde_json::value::to_raw_value;
23use tuwunel_core::{
24 Err, Result, at, debug, implement, trace,
25 utils::{BoolExt as _, time::now_secs},
26 warn,
27};
28use tuwunel_database::{Cbor, Deserialized};
29use tuwunel_matrix::{
30 Event, pdu::into_outgoing_federation, room_version::rules as room_version_rules,
31};
32
33#[cfg(test)]
34mod tests;
35
36const UNSTABLE_POLICY_TYPE: &str = "org.matrix.msc4284.policy";
41const POLICY_REFUSAL_TTL: Duration = Duration::from_hours(24);
42
43#[derive(Clone, Copy, Debug)]
45pub enum PolicyCheck {
46 NotApplicable,
50
51 Pass,
53
54 Missing,
57
58 Invalid,
61}
62
63#[derive(Debug)]
65enum FetchOutcome {
66 Signed(String),
68
69 FailOpen,
71
72 Refused {
78 status: StatusCode,
79 errcode: Option<ErrorKind>,
80 },
81
82 RateLimited {
86 until_secs: u64,
87 },
88}
89
90#[derive(Debug, Serialize, Deserialize)]
93enum PolicySigState {
94 Refused {
98 until_secs: u64,
99 },
100
101 BackoffUntil {
104 until_secs: u64,
105 },
106}
107
108#[derive(Deserialize)]
112struct UnstablePolicyContent {
113 via: OwnedServerName,
114
115 #[serde(default)]
116 public_keys: BTreeMap<SigningKeyAlgorithm, Base64>,
117
118 #[serde(default)]
119 public_key: Option<Base64>,
120}
121
122#[implement(UnstablePolicyContent)]
123fn into_stable(
124 Self { via, mut public_keys, public_key }: Self,
125) -> Option<RoomPolicyEventContent> {
126 if let Some(key) = public_key {
127 public_keys
128 .entry(SigningKeyAlgorithm::Ed25519)
129 .or_insert(key);
130 }
131
132 let ed25519 = public_keys.remove(&SigningKeyAlgorithm::Ed25519)?;
133
134 Some(RoomPolicyEventContent::new(via, ed25519))
135}
136
137#[implement(super::Service)]
141pub fn clear_policy_signature_state(&self, event_id: &EventId) {
142 self.db.eventid_policysigstate.remove(event_id);
143}
144
145#[implement(super::Service)]
146fn cache_policy_refused(&self, event_id: &EventId) {
147 let until_secs = now_secs().saturating_add(POLICY_REFUSAL_TTL.as_secs());
148
149 self.db
150 .eventid_policysigstate
151 .raw_put(event_id.as_str(), Cbor(&PolicySigState::Refused { until_secs }));
152}
153
154#[implement(super::Service)]
155fn cache_policy_backoff(&self, event_id: &EventId, until_secs: u64) {
156 self.db
157 .eventid_policysigstate
158 .raw_put(event_id.as_str(), Cbor(&PolicySigState::BackoffUntil { until_secs }));
159}
160
161#[implement(super::Service)]
162async fn cached_policy_state(&self, event_id: &EventId) -> Option<PolicySigState> {
163 let state = self
164 .db
165 .eventid_policysigstate
166 .get(event_id.as_str())
167 .await
168 .deserialized::<Cbor<_>>();
169
170 current_policy_state(state, now_secs())
171}
172
173fn current_policy_state(
174 state: Result<Cbor<PolicySigState>>,
175 current_secs: u64,
176) -> Option<PolicySigState> {
177 state
178 .map(at!(0))
179 .ok()
180 .filter(|state| match state {
181 | PolicySigState::Refused { until_secs }
182 | PolicySigState::BackoffUntil { until_secs } => *until_secs > current_secs,
183 })
184}
185
186#[implement(super::Service)]
194pub async fn lookup_policy_server(&self, room_id: &RoomId) -> Option<RoomPolicyEventContent> {
195 let read = async |event_type: &StateEventType| {
196 self.services
197 .state_accessor
198 .room_state_get_content::<UnstablePolicyContent>(room_id, event_type, "")
199 .await
200 .ok()
201 .and_then(UnstablePolicyContent::into_stable)
202 };
203
204 let content = match read(&StateEventType::RoomPolicy).await {
205 | Some(content) => content,
206 | None => read(&StateEventType::from(UNSTABLE_POLICY_TYPE.to_owned())).await?,
207 };
208
209 self.services
210 .state_cache
211 .server_in_room(&content.via, room_id)
212 .await
213 .then_some(content)
214}
215
216#[implement(super::Service)]
222#[tracing::instrument(name = "policy_sign", level = "debug", skip_all)]
223pub async fn sign_outgoing_pdu<E>(&self, pdu_json: &mut CanonicalJsonObject, pdu: &E) -> Result
224where
225 E: Event,
226{
227 if self
228 .services
229 .server
230 .config
231 .rooms
232 .policy_server
233 .enable
234 .is_false()
235 {
236 return Ok(());
237 }
238
239 if is_policy_state_event(pdu) {
240 return Ok(());
241 }
242
243 let Ok(room_version) = self
244 .services
245 .state
246 .get_room_version(pdu.room_id())
247 .await
248 else {
249 return Ok(());
250 };
251
252 let Some(policy) = self.lookup_policy_server(pdu.room_id()).await else {
253 trace!(room_id = %pdu.room_id(), "no policy server configured");
254 return Ok(());
255 };
256
257 let event_id = pdu.event_id();
258 match self.cached_policy_state(event_id).await {
259 | Some(PolicySigState::Refused { .. }) =>
260 return Err!(Request(Forbidden("Event was rejected by the room's policy server."))),
261
262 | Some(PolicySigState::BackoffUntil { until_secs }) if until_secs > now_secs() => {
263 debug!(via = %policy.via, until_secs, "skipping outbound /sign during policy backoff");
264 return Ok(());
265 },
266 | _ => {},
267 }
268
269 match self
270 .fetch_policy_signature(&policy, pdu_json, &room_version)
271 .await
272 {
273 | FetchOutcome::Signed(signature) => {
274 insert_policy_signature(pdu_json, &policy.via, &signature);
275 debug!(via = %policy.via, event_id = %event_id, "folded policy server signature");
276 },
277 | FetchOutcome::Refused { status, errcode } => {
278 warn!(
279 via = %policy.via,
280 event_id = %event_id,
281 room_id = %pdu.room_id(),
282 status = status.as_u16(),
283 ?errcode,
284 "policy server refused to sign outbound PDU"
285 );
286
287 self.cache_policy_refused(event_id);
288 return Err!(Request(Forbidden("Event was rejected by the room's policy server.")));
289 },
290 | FetchOutcome::RateLimited { until_secs } => {
291 self.cache_policy_backoff(event_id, until_secs);
292 },
293 | FetchOutcome::FailOpen => {},
294 }
295
296 Ok(())
297}
298
299#[implement(super::Service)]
303#[tracing::instrument(
304 name = "policy_fetch",
305 level = "debug",
306 skip_all,
307 fields(via = %policy.via)
308)]
309async fn fetch_policy_signature(
310 &self,
311 policy: &RoomPolicyEventContent,
312 pdu_json: &CanonicalJsonObject,
313 room_version: &RoomVersionId,
314) -> FetchOutcome {
315 let outgoing = into_outgoing_federation(pdu_json.clone(), room_version);
316 let Ok(raw) = to_raw_value(&outgoing) else {
317 warn!(via = %policy.via, "failed to serialize PDU for policy /sign; failing open");
318 return FetchOutcome::FailOpen;
319 };
320
321 let timeout_secs = self
322 .services
323 .server
324 .config
325 .rooms
326 .policy_server
327 .request_timeout;
328
329 let timeout = Duration::from_secs(timeout_secs);
330
331 let response = match tokio::time::timeout(
332 timeout,
333 self.services
334 .federation
335 .execute(&policy.via, sign_event::Request::new(raw)),
336 )
337 .await
338 {
339 | Ok(Ok(response)) => response,
340 | Ok(Err(error)) => {
341 let status = error.status_code();
342 let errcode = error.kind();
343 let outcome = classify_fetch_error(status, &errcode, parse_rate_limit(&error));
344
345 if let FetchOutcome::RateLimited { until_secs } = &outcome {
346 warn!(
347 via = %policy.via,
348 status = status.as_u16(),
349 ?errcode,
350 until_secs,
351 "policy server /sign rate-limited"
352 );
353 }
354
355 if matches!(&outcome, FetchOutcome::FailOpen) {
356 let expected_not_found = status == StatusCode::NOT_FOUND
357 && (errcode == ErrorKind::NotFound || errcode == ErrorKind::Unrecognized);
358
359 if expected_not_found {
360 debug!(
361 via = %policy.via,
362 status = status.as_u16(),
363 ?errcode,
364 %error,
365 "policy server does not support /sign; failing open"
366 );
367 } else {
368 warn!(
369 via = %policy.via,
370 status = status.as_u16(),
371 ?errcode,
372 %error,
373 "policy server /sign failed; failing open"
374 );
375 }
376 }
377
378 return outcome;
379 },
380 | Err(elapsed) => {
381 warn!(via = %policy.via, %elapsed, "policy server /sign timed out; failing open");
382 return FetchOutcome::FailOpen;
383 },
384 };
385
386 response
388 .ed25519_signature(&policy.via)
389 .map(ToOwned::to_owned)
390 .map_or(
391 FetchOutcome::Refused { status: StatusCode::OK, errcode: None },
392 FetchOutcome::Signed,
393 )
394}
395
396fn classify_fetch_error(
397 status: StatusCode,
398 errcode: &ErrorKind,
399 rate_limit_until: Option<u64>,
400) -> FetchOutcome {
401 match rate_limit_until {
402 | Some(until_secs) => FetchOutcome::RateLimited { until_secs },
403 | None if status == StatusCode::BAD_REQUEST && errcode == &ErrorKind::Forbidden =>
404 FetchOutcome::Refused { status, errcode: Some(errcode.clone()) },
405 | None => FetchOutcome::FailOpen,
406 }
407}
408
409fn parse_rate_limit(error: &tuwunel_core::Error) -> Option<u64> {
410 let ErrorKind::LimitExceeded(data) = error.kind() else {
411 return None;
412 };
413
414 let until = match data.retry_after.as_ref()? {
415 | RetryAfter::Delay(d) => SystemTime::now().checked_add(*d)?,
416 | RetryAfter::DateTime(t) => *t,
417 };
418
419 until
420 .duration_since(UNIX_EPOCH)
421 .ok()
422 .map(|d| d.as_secs())
423}
424
425#[implement(super::Service)]
430#[tracing::instrument(name = "policy_verify_or_fetch", level = "debug", skip_all)]
431pub async fn verify_or_fetch_inbound_policy_signature<E>(
432 &self,
433 pdu_json: &mut CanonicalJsonObject,
434 pdu: &E,
435) -> PolicyCheck
436where
437 E: Event,
438{
439 match self
440 .check_inbound_policy_signature(pdu_json, pdu)
441 .await
442 {
443 | PolicyCheck::Missing | PolicyCheck::Invalid =>
444 self.fetch_inbound_policy_signature(pdu_json, pdu)
445 .await,
446 | other => other,
447 }
448}
449
450#[implement(super::Service)]
455#[tracing::instrument(name = "policy_fetch_inbound", level = "debug", skip_all)]
456async fn fetch_inbound_policy_signature<E>(
457 &self,
458 pdu_json: &mut CanonicalJsonObject,
459 pdu: &E,
460) -> PolicyCheck
461where
462 E: Event,
463{
464 let Some(policy) = self.lookup_policy_server(pdu.room_id()).await else {
465 return PolicyCheck::NotApplicable;
466 };
467
468 let Ok(room_version) = self
469 .services
470 .state
471 .get_room_version(pdu.room_id())
472 .await
473 else {
474 return PolicyCheck::NotApplicable;
475 };
476
477 let event_id = pdu.event_id();
478 match self.cached_policy_state(event_id).await {
479 | Some(PolicySigState::Refused { .. }) => return PolicyCheck::Invalid,
480 | Some(PolicySigState::BackoffUntil { until_secs }) if until_secs > now_secs() => {
481 debug!(
482 until_secs,
483 via = %policy.via,
484 "policy server in backoff; failing open"
485 );
486
487 return PolicyCheck::Pass;
488 },
489 | _ => {},
490 }
491
492 match self
493 .fetch_policy_signature(&policy, pdu_json, &room_version)
494 .await
495 {
496 | FetchOutcome::Signed(signature) => {
497 debug!(
498 via = %policy.via,
499 event_id = %event_id,
500 "folded inbound policy server signature"
501 );
502
503 insert_policy_signature(pdu_json, &policy.via, &signature);
504 PolicyCheck::Pass
505 },
506 | FetchOutcome::Refused { status, errcode } => {
507 warn!(
508 via = %policy.via,
509 event_id = %event_id,
510 room_id = %pdu.room_id(),
511 status = status.as_u16(),
512 ?errcode,
513 "policy server refused to sign inbound PDU; soft-failing"
514 );
515
516 self.cache_policy_refused(event_id);
517 PolicyCheck::Invalid
518 },
519 | FetchOutcome::RateLimited { until_secs } => {
520 self.cache_policy_backoff(event_id, until_secs);
521 PolicyCheck::Pass
522 },
523 | FetchOutcome::FailOpen => PolicyCheck::Pass,
524 }
525}
526
527#[implement(super::Service)]
533#[tracing::instrument(name = "policy_verify", level = "debug", skip_all)]
534pub async fn check_inbound_policy_signature<E>(
535 &self,
536 pdu_json: &CanonicalJsonObject,
537 pdu: &E,
538) -> PolicyCheck
539where
540 E: Event,
541{
542 if self
543 .services
544 .server
545 .config
546 .rooms
547 .policy_server
548 .enable
549 .is_false()
550 {
551 return PolicyCheck::NotApplicable;
552 }
553
554 if is_policy_state_event(pdu) {
555 return PolicyCheck::NotApplicable;
556 }
557
558 let Some(policy) = self.lookup_policy_server(pdu.room_id()).await else {
559 return PolicyCheck::NotApplicable;
560 };
561
562 let Ok(room_version) = self
563 .services
564 .state
565 .get_room_version(pdu.room_id())
566 .await
567 else {
568 return PolicyCheck::NotApplicable;
569 };
570
571 let Some(public_key) = policy
573 .public_keys
574 .get(&SigningKeyAlgorithm::Ed25519)
575 else {
576 return PolicyCheck::NotApplicable;
577 };
578
579 check_policy_signature(pdu_json, &room_version, &policy.via, public_key)
580}
581
582fn check_policy_signature(
583 pdu_json: &CanonicalJsonObject,
584 room_version: &RoomVersionId,
585 via: &ServerName,
586 public_key: &Base64,
587) -> PolicyCheck {
588 let Ok(rules) = room_version_rules(room_version) else {
589 return PolicyCheck::NotApplicable;
590 };
591
592 let Some(signature_b64) = extract_policy_signature(pdu_json, via) else {
593 return PolicyCheck::Missing;
594 };
595
596 let Ok(signature) = Base64::<ruma::serde::base64::Standard>::parse(signature_b64) else {
597 return PolicyCheck::Invalid;
598 };
599
600 let Ok(redacted) = ruma::canonical_json::redact(pdu_json.clone(), &rules.redaction, None)
601 else {
602 return PolicyCheck::Invalid;
603 };
604
605 let Ok(canonical) = to_canonical_json_string_for_signing(&redacted) else {
606 return PolicyCheck::Invalid;
607 };
608
609 verify_canonical_json_bytes(
610 &SigningKeyAlgorithm::Ed25519,
611 public_key.as_bytes(),
612 signature.as_bytes(),
613 canonical.as_bytes(),
614 )
615 .map(|()| PolicyCheck::Pass)
616 .unwrap_or_else(|error| {
617 debug!(%via, %error, "policy server signature failed verification");
618 PolicyCheck::Invalid
619 })
620}
621
622fn is_policy_state_event<E: Event>(pdu: &E) -> bool {
623 if pdu.state_key() != Some("") {
624 return false;
625 }
626
627 let kind = pdu.kind().to_cow_str();
628
629 kind == "m.room.policy" || kind == UNSTABLE_POLICY_TYPE
630}
631
632fn extract_policy_signature<'a>(
633 pdu_json: &'a CanonicalJsonObject,
634 via: &ServerName,
635) -> Option<&'a str> {
636 let CanonicalJsonValue::Object(server_map) = pdu_json.get("signatures")? else {
637 return None;
638 };
639
640 let CanonicalJsonValue::Object(key_map) = server_map.get(via.as_str())? else {
641 return None;
642 };
643
644 let CanonicalJsonValue::String(signature) =
645 key_map.get(POLICY_SERVER_ED25519_SIGNING_KEY_ID)?
646 else {
647 return None;
648 };
649
650 Some(signature.as_str())
651}
652
653fn insert_policy_signature(
654 pdu_json: &mut CanonicalJsonObject,
655 via: &ServerName,
656 signature: &str,
657) {
658 let signatures = pdu_json
659 .entry("signatures".into())
660 .or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::new()));
661
662 let CanonicalJsonValue::Object(server_map) = signatures else {
663 return;
664 };
665
666 let entry = server_map
667 .entry(via.as_str().into())
668 .or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::new()));
669
670 if let CanonicalJsonValue::Object(key_map) = entry {
671 key_map.insert(
672 POLICY_SERVER_ED25519_SIGNING_KEY_ID.into(),
673 CanonicalJsonValue::String(signature.to_owned()),
674 );
675 }
676}