Skip to main content

tuwunel_core/config/
federation.rs

1//! Configures federation access and local state derivation.
2//!
3//! Transport, key lookup, history recovery, and bounded fanouts have
4//! dedicated settings. Access controls apply to remote server
5//! communication.
6
7use regex::RegexSet;
8use ruma::OwnedServerName;
9use serde::Deserialize;
10use tuwunel_macros::config_example_generator;
11
12use super::true_fn;
13use crate::matrix::MAX_PREV_EVENTS;
14
15/// Federation with other homeservers
16///
17/// Controls whether this server federates and which remote servers it
18/// accepts. Federation is on by default and open to every server not
19/// matched by `forbidden_remote_server_names`. The subsections tune signing
20/// key lookup (`[global.federation.keys]`), the federation client
21/// (`[global.federation.transport]`), history recovery
22/// (`[global.federation.history]`) and multi-server queries
23/// (`[global.federation.fanout]`).
24///
25/// To run a closed server, set `enable = false` and restart. Local users and
26/// rooms keep working; the federation and key endpoints answer
27/// `403 M_FORBIDDEN`, and requests to other servers are refused.
28///
29/// Tips:
30/// - Rooms created while federation is off are not marked local-only unless
31///   `rooms.federate_by_default` is also false, so they federate once it is
32///   back on.
33/// - Server name lists are regular expressions: an unescaped dot matches any
34///   character, and a plain dotted name logs a startup warning. Put escaped
35///   patterns in single quotes, since TOML rejects `\.` inside double
36///   quotes: `forbidden_remote_server_names = ['^evil\.example$']`.
37#[expect(rustdoc::broken_intra_doc_links, rustdoc::bare_urls)]
38#[derive(Clone, Debug, Deserialize)]
39#[config_example_generator(
40	filename = "tuwunel-example.toml",
41	section = "global.federation",
42	group = "true",
43	ignore = "fanout history keys transport",
44	hidden = "resolve_state_locally_shadow"
45)]
46pub struct Federation {
47	/// Allows federation with other servers.
48	///
49	/// Disabling this after installation risks federation breakage and is not
50	/// recommended, although the setting is not permanent.
51	///
52	/// legacy: allow_federation
53	#[serde(default = "true_fn")]
54	pub enable: bool,
55
56	/// Derives incoming federation event state from locally held unresolved
57	/// ancestry.
58	///
59	/// When previous events are stored but unresolved, we derive state locally
60	/// instead of requesting `/state_ids` from the origin server. This
61	/// requires the entire unresolved local ancestry to be present; every
62	/// other case falls back to a federation state fetch. Disabling this
63	/// restores the previous behavior of always fetching.
64	///
65	/// reloadable: yes
66	/// legacy: resolve_state_locally
67	#[serde(default = "true_fn")]
68	pub resolve_state_locally: bool,
69
70	/// Limits unresolved local events visited by one local state derivation
71	/// before falling back to federation.
72	///
73	/// This bounds worst-case memory and latency in rooms with a large
74	/// unresolved backlog. A value of 0 disables local derivation entirely.
75	///
76	/// reloadable: yes
77	/// default: 256
78	/// legacy: resolve_state_locally_max
79	#[serde(default = "default_resolve_state_locally_max")]
80	pub resolve_state_locally_max: usize,
81
82	/// Retains the legacy compatibility switch for local state derivation.
83	///
84	/// A configured value of true disables local derivation and its memo
85	/// shortcut. Use `federation.resolve_state_locally = false` in new
86	/// configurations.
87	///
88	/// reloadable: yes
89	/// display: hidden
90	/// legacy: resolve_state_locally_shadow
91	#[serde(default)]
92	pub resolve_state_locally_shadow: bool,
93
94	/// Allows federation requests to this server itself.
95	///
96	/// This exists mainly for development. Requests to ourselves are
97	/// unintended in ordinary operation and very likely indicate a bug.
98	///
99	/// reloadable: yes
100	/// legacy: federation_loopback
101	#[serde(default)]
102	pub loopback: bool,
103
104	/// Blocks server names matching listed regular expressions from incoming
105	/// and outgoing federation and client joins or remote invites.
106	///
107	/// These global access controls check room IDs, room aliases, sender
108	/// server names, sender users' server names, inbound federation X-Matrix
109	/// origins, and the outbound federation handler. This server's own name is
110	/// always permitted and exempt from the list.
111	///
112	/// reloadable: yes
113	/// example: ['badserver\.tld$', 'badphrase', '19dollarfortnitecards']
114	///
115	/// default: []
116	/// legacy: forbidden_remote_server_names
117	#[serde(default, with = "serde_regex")]
118	pub forbidden_remote_server_names: RegexSet,
119
120	/// Experimentally permits only server names matching listed regular
121	/// expressions.
122	///
123	/// The behavior will change and the `_experimental` suffix will be removed
124	/// in an upcoming release; the matching details otherwise follow
125	/// `federation.forbidden_remote_server_names`. The list is empty and
126	/// inactive by default; any entry activates it and denies nonmatches,
127	/// while this server's own name is always permitted. The denylist still
128	/// applies afterward, allowing a broad match such as
129	/// `'^([^.]+\.)+example\.com$'` here and an exclusion such as
130	/// `'^bad\.example\.com$'` there.
131	///
132	/// reloadable: yes
133	/// example: ['badserver\.tld$', 'badphrase', '19dollarfortnitecards']
134	///
135	/// default: []
136	/// legacy: allowed_remote_server_names_experimental
137	#[serde(default, with = "serde_regex")]
138	pub allowed_remote_server_names_experimental: RegexSet,
139
140	/// Enforces
141	/// [MSC4311](https://github.com/matrix-org/matrix-spec-proposals/pull/4311)
142	/// create-event validation in federated invite and knock stripped state.
143	///
144	/// When enabled, an invite is rejected if its `m.room.create` event is
145	/// missing, not a full PDU, bound to a different room, or fails signature
146	/// checks, and such events are dropped from knock stripped state. When
147	/// disabled, as by default, failures are logged but tolerated for
148	/// ecosystem interoperability, except that for room versions 12 and later
149	/// a missing create event, or a full PDU bound cryptographically to a
150	/// different room, is always rejected. A full PDU in knock stripped state
151	/// that fails validation is always omitted, so this setting governs only
152	/// legacy stripped creates for knocks.
153	///
154	/// reloadable: yes
155	/// legacy: enforce_stripped_state_pdu_validation
156	#[serde(default)]
157	pub enforce_stripped_state_pdu_validation: bool,
158
159	/// Settings for federation fanout.
160	///
161	/// display: section
162	#[serde(default)]
163	pub fanout: Fanout,
164
165	/// Settings for federation history.
166	///
167	/// display: section
168	#[serde(default)]
169	pub history: History,
170
171	/// Settings for federation keys.
172	///
173	/// display: section
174	#[serde(default)]
175	pub keys: Keys,
176
177	/// Settings for federation transport.
178	///
179	/// display: section
180	#[serde(default)]
181	pub transport: Transport,
182}
183
184/// Federation fanout limits
185///
186/// Bounds requests sent to many homeservers at once: `!admin query feds`
187/// surveys, room summary and space hierarchy lookups, and remote device-key
188/// queries. `destination_limit` guards only the admin survey, and device-key
189/// queries take `max_width` but time out after `transport.keys_timeout`
190/// rather than `timeout`. All three settings apply on reload.
191#[expect(rustdoc::broken_intra_doc_links, rustdoc::bare_urls)]
192#[derive(Clone, Copy, Debug, Deserialize)]
193#[config_example_generator(
194	filename = "tuwunel-example.toml",
195	section = "global.federation.fanout",
196	group = "true"
197)]
198pub struct Fanout {
199	/// Sets the timeout in seconds for each bounded federation fanout request.
200	///
201	/// This applies to admin surveys and migrated room fanouts. A server that
202	/// exceeds the deadline is reported as timed out while other destinations
203	/// continue. Keep this below `federation.transport.timeout` and above
204	/// `federation.transport.keys_timeout`.
205	///
206	/// reloadable: yes
207	/// default: 15
208	/// legacy: feds_timeout
209	#[serde(default = "default_feds_timeout")]
210	pub timeout: u64,
211
212	/// Limits concurrency for bounded federation fanouts.
213	///
214	/// This caps admin surveys and migrated room and key fanouts. Lower values
215	/// trade sweep latency for load without dropping destinations. 0 selects
216	/// the built-in bounded default.
217	///
218	/// reloadable: yes
219	/// default: 0
220	/// legacy: feds_max_width
221	#[serde(default)]
222	pub max_width: usize,
223
224	/// Limits destinations contacted by an admin feds survey without
225	/// confirmation.
226	///
227	/// A room exceeding this requires the command's confirmation flag. Higher
228	/// values permit longer diagnostic commands on the serial admin worker.
229	///
230	/// reloadable: yes
231	/// default: 2048
232	/// legacy: feds_destination_limit
233	#[serde(default = "default_destination_limit")]
234	pub destination_limit: usize,
235}
236
237/// Federation history recovery
238///
239/// Limits the work spent filling gaps when an incoming event refers to
240/// earlier events this server does not hold and, with
241/// `fetch_unreceived_contexts`, when a client asks for context around an
242/// event it never received. All settings apply on reload.
243///
244/// Tips:
245/// - `prev_events_concurrency = 0` is refused at startup and on reload.
246#[expect(rustdoc::broken_intra_doc_links, rustdoc::bare_urls)]
247#[derive(Clone, Copy, Debug, Deserialize)]
248#[config_example_generator(
249	filename = "tuwunel-example.toml",
250	section = "global.federation.history",
251	group = "true"
252)]
253pub struct History {
254	/// Limits prior events visited by one recovery traversal.
255	///
256	/// reloadable: yes
257	/// default: 1024
258	///
259	/// Raising this limit increases recovery work; it is not a count of network
260	/// requests.
261	/// legacy: max_fetch_prev_events
262	#[serde(default = "default_max_fetch_prev_events")]
263	pub max_fetch_prev_events: u16,
264
265	/// Limits simultaneous backward-extremity upgrades during incoming-event
266	/// recovery.
267	///
268	/// Lower values reduce recovery load at the cost of latency. This does not
269	/// change the protocol `prev_events` bound or
270	/// `federation.history.max_fetch_prev_events`.
271	///
272	/// reloadable: yes
273	/// default: 20
274	/// legacy: prev_events_concurrency
275	#[serde(default = "default_prev_events_concurrency")]
276	pub prev_events_concurrency: u16,
277
278	/// Limits how many milliseconds an incoming timeline event waits for
279	/// missing previous events before federation fetching.
280	///
281	/// A gap closing within this window skips the fetch. The event-driven wait
282	/// wakes as soon as those events arrive, so the limit is a ceiling on
283	/// added latency rather than a fixed cost. Set to 0 to fetch immediately.
284	///
285	/// reloadable: yes
286	/// default: 750
287	/// legacy: fetch_prev_wait_ms
288	#[serde(default = "default_fetch_prev_wait_ms")]
289	pub fetch_prev_wait_ms: u64,
290
291	/// Enables experimental federation fetching of missing base events for
292	/// room context requests.
293	///
294	/// For `/_matrix/client/v3/rooms/{roomId}/context/{eventId}` requests
295	/// whose event is not held locally, we fetch it from a room peer and
296	/// persist it before responding instead of returning a 404. This requires
297	/// `federation.enable` and has no effect when federation is disabled.
298	/// Other on-demand federation fetch sites are gated separately.
299	///
300	/// reloadable: yes
301	/// default: false
302	/// legacy: fetch_unreceived_contexts_over_federation
303	#[serde(default)]
304	pub fetch_unreceived_contexts: bool,
305
306	/// Limits concurrent server contacts per round of a federation event
307	/// fetch.
308	///
309	/// This tightens the built-in fanout profile of every fetch kind and never
310	/// widens one. A value of 0 leaves the profiles unchanged.
311	///
312	/// reloadable: yes
313	/// default: 0
314	/// legacy: fetch_fanout_max_width
315	#[serde(default)]
316	pub fetch_fanout_max_width: usize,
317
318	/// Limits staged rounds attempted by a federation event fetch before
319	/// giving up.
320	///
321	/// This tightens the built-in round count of every fetch kind and never
322	/// raises one. A value of 0 leaves the profiles unchanged.
323	///
324	/// reloadable: yes
325	/// default: 0
326	/// legacy: fetch_fanout_rounds
327	#[serde(default)]
328	pub fetch_fanout_rounds: usize,
329}
330
331/// Federation signing keys
332///
333/// Verifying events from other homeservers needs their public signing keys.
334/// The server asks the origin server first and falls back to the notaries
335/// in `trusted_servers` (`matrix.org` by default); for joins and knocks it
336/// asks the notaries first by default. Fetched keys are cached, and every
337/// setting here applies on reload.
338///
339/// Tips:
340/// - With `trusted_servers = []`, keys come only from their origin. A server
341///   that is offline or unreachable cannot supply keys not already cached,
342///   so its events cannot be verified, and joins of large rooms can slow
343///   down.
344/// - `only_query_trusted_servers` with an empty `trusted_servers` leaves no
345///   source at all for keys not already cached.
346#[expect(rustdoc::broken_intra_doc_links, rustdoc::bare_urls)]
347#[derive(Clone, Debug, Deserialize)]
348#[config_example_generator(
349	filename = "tuwunel-example.toml",
350	section = "global.federation.keys",
351	group = "true"
352)]
353pub struct Keys {
354	#[expect(clippy::doc_link_with_quotes)]
355	/// Selects trusted notary servers used to gather other servers' public
356	/// keys.
357	///
358	/// We do not currently support inbound batched key requests, so this list
359	/// should contain only Synapse servers.
360	///
361	/// reloadable: yes
362	/// example: ["matrix.org", "tchncs.de"]
363	///
364	/// default: ["matrix.org"]
365	/// legacy: trusted_servers
366	#[serde(default = "default_trusted_servers")]
367	pub trusted_servers: Vec<OwnedServerName>,
368
369	/// Queries configured trusted key servers before the origin when enabled.
370	///
371	/// Querying the origin first offers the best security by reducing exposure
372	/// to a compromised trusted server. Enabling this can maximize federation
373	/// and join performance, but evaluate the other settings that query
374	/// trusted servers first only under specific high-load conditions before
375	/// enabling it globally.
376	///
377	/// reloadable: yes
378	/// legacy: query_trusted_key_servers_first
379	#[serde(default)]
380	pub query_trusted_servers_first: bool,
381
382	/// Queries configured trusted key servers before origins specifically
383	/// during room joins.
384	///
385	/// This limits exposure to compromised trusted servers to joins, whose
386	/// many origin-key lookups can cause significant delays; it defaults to
387	/// true to mitigate unexpected delays. Set to false when minimizing that
388	/// exposure matters more than latency. This setting is ignored when
389	/// `federation.keys.query_trusted_servers_first` is true.
390	///
391	/// reloadable: yes
392	/// legacy: query_trusted_key_servers_first_on_join
393	#[serde(default = "true_fn")]
394	pub query_trusted_servers_first_on_join: bool,
395
396	/// Queries only trusted key servers and never the origin.
397	///
398	/// This is intended for clusters or custom deployments using
399	/// `federation.keys.trusted_servers` as forwarding agents to cache and
400	/// deduplicate requests. Notary servers do not act as forwarding agents by
401	/// default, so enable this only with a full understanding of the
402	/// deployment.
403	///
404	/// reloadable: yes
405	/// legacy: only_query_trusted_key_servers
406	#[serde(default)]
407	pub only_query_trusted_servers: bool,
408
409	/// Limits keys requested in each trusted-server batch query.
410	///
411	/// reloadable: yes
412	/// default: 192
413	/// legacy: trusted_server_batch_size
414	#[serde(default = "default_trusted_server_batch_size")]
415	pub trusted_server_batch_size: usize,
416
417	/// Limits simultaneous request batches when querying a trusted server.
418	///
419	/// reloadable: yes
420	/// default: 2
421	/// legacy: trusted_server_batch_concurrency
422	#[serde(default = "default_trusted_server_batch_concurrency")]
423	pub trusted_server_batch_concurrency: usize,
424}
425
426/// Federation client transport
427///
428/// Timeouts and connection reuse for requests this server sends to other
429/// homeservers, such as event, state and key fetches, joins, and remote
430/// device-key queries. Outgoing transactions (`/send`) use the client in
431/// `[global.sending]` instead, and connect and whole-request limits come
432/// from `[global.network.http]`.
433#[expect(rustdoc::broken_intra_doc_links, rustdoc::bare_urls)]
434#[derive(Clone, Copy, Debug, Deserialize)]
435#[config_example_generator(
436	filename = "tuwunel-example.toml",
437	section = "global.federation.transport",
438	group = "true"
439)]
440pub struct Transport {
441	/// Sets the federation client read timeout in seconds.
442	///
443	/// This applies to each read from a remote server rather than the whole
444	/// request, which remains bounded by `network.http.total_timeout`.
445	///
446	/// default: 25
447	/// legacy: federation_timeout
448	#[serde(default = "default_timeout")]
449	pub timeout: u64,
450
451	/// Sets the timeout in seconds for client-initiated federation key
452	/// lookups.
453	///
454	/// This covers `/keys/query` and `/keys/claim` against remote servers and
455	/// should be well below `federation.transport.timeout`, so an unresponsive
456	/// server does not outlast the requesting client's send deadline.
457	/// Exceeding this bound records a transient federation failure for the
458	/// remote server, making subsequent lookups back off instead of blocking
459	/// again.
460	///
461	/// default: 8
462	/// legacy: federation_keys_timeout
463	#[serde(default = "default_keys_timeout")]
464	pub keys_timeout: u64,
465
466	/// Sets the federation client idle connection pool timeout (seconds).
467	///
468	/// default: 25
469	/// legacy: federation_idle_timeout
470	#[serde(default = "default_idle_timeout")]
471	pub idle_timeout: u64,
472
473	/// Limits idle federation client connections per host, defaulting to one
474	/// because an open connection can generally be reused.
475	///
476	/// default: 1
477	/// legacy: federation_idle_per_host
478	#[serde(default = "default_idle_per_host")]
479	pub idle_per_host: u16,
480}
481
482impl Default for Federation {
483	fn default() -> Self {
484		Self {
485			enable: true_fn(),
486			resolve_state_locally: true_fn(),
487			resolve_state_locally_max: default_resolve_state_locally_max(),
488			resolve_state_locally_shadow: Default::default(),
489			loopback: Default::default(),
490			forbidden_remote_server_names: Default::default(),
491			allowed_remote_server_names_experimental: Default::default(),
492			enforce_stripped_state_pdu_validation: Default::default(),
493			fanout: Fanout::default(),
494			history: History::default(),
495			keys: Keys::default(),
496			transport: Transport::default(),
497		}
498	}
499}
500
501impl Default for Fanout {
502	fn default() -> Self {
503		Self {
504			timeout: default_feds_timeout(),
505			max_width: Default::default(),
506			destination_limit: default_destination_limit(),
507		}
508	}
509}
510
511impl Default for History {
512	fn default() -> Self {
513		Self {
514			max_fetch_prev_events: default_max_fetch_prev_events(),
515			prev_events_concurrency: default_prev_events_concurrency(),
516			fetch_prev_wait_ms: default_fetch_prev_wait_ms(),
517			fetch_unreceived_contexts: Default::default(),
518			fetch_fanout_max_width: Default::default(),
519			fetch_fanout_rounds: Default::default(),
520		}
521	}
522}
523
524impl Default for Keys {
525	fn default() -> Self {
526		Self {
527			trusted_servers: default_trusted_servers(),
528			query_trusted_servers_first: Default::default(),
529			query_trusted_servers_first_on_join: true_fn(),
530			only_query_trusted_servers: Default::default(),
531			trusted_server_batch_size: default_trusted_server_batch_size(),
532			trusted_server_batch_concurrency: default_trusted_server_batch_concurrency(),
533		}
534	}
535}
536
537impl Default for Transport {
538	fn default() -> Self {
539		Self {
540			timeout: default_timeout(),
541			keys_timeout: default_keys_timeout(),
542			idle_timeout: default_idle_timeout(),
543			idle_per_host: default_idle_per_host(),
544		}
545	}
546}
547
548fn default_resolve_state_locally_max() -> usize { 256 }
549
550fn default_feds_timeout() -> u64 { 15 }
551
552fn default_destination_limit() -> usize { 2048 }
553
554fn default_max_fetch_prev_events() -> u16 { 1024_u16 }
555
556fn default_prev_events_concurrency() -> u16 {
557	u16::try_from(MAX_PREV_EVENTS).expect("MAX_PREV_EVENTS exceeds u16")
558}
559
560fn default_fetch_prev_wait_ms() -> u64 { 750 }
561
562fn default_trusted_servers() -> Vec<OwnedServerName> {
563	vec![OwnedServerName::try_from("matrix.org").expect("valid ServerName")]
564}
565
566fn default_trusted_server_batch_size() -> usize { 192 }
567
568fn default_trusted_server_batch_concurrency() -> usize { 2 }
569
570fn default_timeout() -> u64 { 25 }
571
572fn default_keys_timeout() -> u64 { 8 }
573
574fn default_idle_timeout() -> u64 { 25 }
575
576fn default_idle_per_host() -> u16 { 1 }