-
Notifications
You must be signed in to change notification settings - Fork 211
Expand file tree
/
Copy pathmod.rs
More file actions
4514 lines (3963 loc) · 160 KB
/
Copy pathmod.rs
File metadata and controls
4514 lines (3963 loc) · 160 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub mod check;
mod identity_provider_serde;
pub mod ip_source;
pub mod manager;
mod net;
pub mod proxy;
pub mod room_version;
#[cfg(test)]
mod tests;
pub mod well_known;
use std::{
collections::{BTreeMap, BTreeSet},
net::IpAddr,
path::{Path, PathBuf},
};
use bytesize::ByteSize;
use derive_more::Debug;
use either::{Either, Either::Left};
use figment::providers::{Data, Env, Format, Toml};
pub use figment::{Figment, value::Value as FigmentValue};
use ipnet::IpNet;
use itertools::Itertools;
use regex::RegexSet;
use ruma::{
OwnedMxcUri, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, RoomVersionId,
api::client::discovery::discover_support::ContactRole,
};
use serde::{Deserialize, de::IgnoredAny};
use tuwunel_macros::config_example_generator;
use url::Url;
pub use self::{check::check, ip_source::IpSource, manager::Manager};
use self::{
net::{ListeningAddr, ListeningPort},
proxy::ProxyConfig,
};
use crate::{
Err, Result, err, redacted_debug,
utils::{self, bytes::deserialize_bytesize_usize, sys},
};
/// All the config options for tuwunel.
#[expect(rustdoc::broken_intra_doc_links, rustdoc::bare_urls)]
#[derive(Clone, Deserialize)]
#[config_example_generator(
filename = "tuwunel-example.toml",
section = "global",
undocumented = "# This item is undocumented. Please contribute documentation for it.",
header = r#"### Tuwunel Configuration
###
### THIS FILE IS GENERATED. CHANGES/CONTRIBUTIONS IN THE REPO WILL BE
### OVERWRITTEN!
###
### You should rename this file before configuring your server. Changes to
### documentation and defaults can be contributed in source code at
### src/core/config/mod.rs. This file is generated when building.
###
### Any values pre-populated are the default values for said config option.
###
### At the minimum, you MUST edit all the config options to your environment
### that say "YOU NEED TO EDIT THIS".
###
### For more information, see:
### https://tuwunel.chat/configuration.html
"#,
ignore = "catchall well_known tls allow_invalid_tls_certificates ldap jwt appservice \
identity_provider storage_provider"
)]
pub struct Config {
/// The server_name is the pretty name of this server. It is used as a
/// suffix for user and room IDs/aliases.
///
/// See the docs for reverse proxying and delegation:
/// https://tuwunel.chat/deploying/generic.html#setting-up-the-reverse-proxy
///
/// Also see the `[global.well_known]` config section at the very bottom.
///
/// Examples of delegation:
/// - https://matrix.org/.well-known/matrix/server
/// - https://matrix.org/.well-known/matrix/client
///
/// YOU NEED TO EDIT THIS. THIS CANNOT BE CHANGED AFTER WITHOUT A DATABASE
/// WIPE.
///
/// example: "girlboss.ceo"
#[cfg_attr(test, serde(default = "default_server_name"))]
pub server_name: OwnedServerName,
/// Alternate server names this homeserver is authoritative for. Users
/// with a Matrix ID on any of these domains can authenticate and use this
/// server, in addition to users on the primary `server_name`.
///
/// Each name must be a valid Matrix server name.
///
/// Alternate server names can be added after initialization, but should not
/// be removed while there exist accounts or appservice registrations using
/// that domain.
///
/// Each alternate domain must independently satisfy the Matrix
/// well-known/delegation requirements so that federation peers and clients
/// can resolve it to this server.
///
/// Note that servers providing the legacy registration endpoint can block
/// registration of users on alternate server names by including the full
/// User ID (e.g. "@user:example.com") or just the domain (e.g. ":example.com") in
/// `forbidden_usernames`.
///
/// example: ["legacy.example.com", "alias.example.org"]
///
/// default: []
#[serde(default)]
pub alternate_server_names: Vec<OwnedServerName>,
/// This is the only directory where tuwunel will save its data, including
/// media. Note: this was previously "/var/lib/matrix-conduit".
///
/// default: "/var/lib/tuwunel"
#[serde(default = "default_database_path")]
pub database_path: PathBuf,
/// Text which will be added to the end of the user's displayname upon
/// registration with a space before the text. In Conduit, this was the
/// lightning bolt emoji.
///
/// To disable, set this to "" (an empty string).
///
/// reloadable: yes
/// default: "💕"
#[serde(default = "default_new_user_displayname_suffix")]
pub new_user_displayname_suffix: String,
#[expect(clippy::doc_link_with_quotes)]
/// The default address (IPv4 or IPv6) tuwunel will listen on.
///
/// If you are using Docker or a container NAT networking setup, this must
/// be "0.0.0.0".
///
/// To listen on multiple addresses, specify a vector e.g. ["127.0.0.1",
/// "::1"]
///
/// default: ["127.0.0.1", "::1"]
#[serde(default)]
address: Option<ListeningAddr>,
/// The port(s) tuwunel will listen on.
///
/// For reverse proxying, see:
/// https://tuwunel.chat/deploying/generic.html#setting-up-the-reverse-proxy
///
/// If you are using Docker, don't change this, you'll need to map an
/// external port to this.
///
/// To listen on multiple ports, specify a vector e.g. [8080, 8448]
///
/// default: 8008
#[serde(default = "default_port")]
port: ListeningPort,
// external structure; separate section
#[serde(default)]
pub tls: TlsConfig,
/// The UNIX socket tuwunel will listen on.
///
/// Remember to make sure that your reverse proxy has access to this socket
/// file, either by adding your reverse proxy to the 'tuwunel' group or
/// granting world R/W permissions with `unix_socket_perms` (666 minimum).
///
/// example: "/run/tuwunel/tuwunel.sock"
pub unix_socket_path: Option<PathBuf>,
/// The default permissions (in octal) to create the UNIX socket with.
///
/// default: 660
#[serde(default = "default_unix_socket_perms")]
pub unix_socket_perms: u32,
/// Error on startup if any config option specified is unknown to Tuwunel.
///
/// This is false by default to allow easier deprecation or removal of
/// config options in the future without breaking existing deployments. The
/// default behaviour is to simply warn on startup.
/// reloadable: yes
#[serde(default)]
pub error_on_unknown_config_opts: bool,
/// tuwunel supports online database backups using RocksDB's Backup engine
/// API. To use this, set a database backup path that tuwunel can write
/// to.
///
/// For more information, see:
/// https://tuwunel.chat/maintenance.html#backups
///
/// reloadable: yes
/// example: "/opt/tuwunel-db-backups"
pub database_backup_path: Option<PathBuf>,
/// The amount of online RocksDB database backups to keep/retain, if using
/// "database_backup_path", before deleting the oldest one.
///
/// reloadable: yes
/// default: 1
#[serde(default = "default_database_backups_to_keep")]
pub database_backups_to_keep: i16,
/// Set this to any float value to multiply tuwunel's in-memory LRU caches
/// with such as "auth_chain_cache_capacity".
///
/// May be useful if you have significant memory to spare to increase
/// performance.
///
/// If you have low memory, reducing this may be viable.
///
/// By default, the individual caches such as "auth_chain_cache_capacity"
/// are scaled by your CPU core count.
///
/// default: 1.0
#[serde(
default = "default_cache_capacity_modifier",
alias = "conduit_cache_capacity_modifier"
)]
pub cache_capacity_modifier: f64,
/// Set this to any float value in megabytes for tuwunel to tell the
/// database engine that this much memory is available for database read
/// caches.
///
/// May be useful if you have significant memory to spare to increase
/// performance.
///
/// Similar to the individual LRU caches, this is scaled up with your CPU
/// core count.
///
/// This defaults to 128.0 + (64.0 * CPU core count).
///
/// default: varies by system
#[serde(default = "default_db_cache_capacity_mb")]
pub db_cache_capacity_mb: f64,
/// Set this to any float value in megabytes for tuwunel to tell the
/// database engine that this much memory is available for database write
/// caches.
///
/// May be useful if you have significant memory to spare to increase
/// performance.
///
/// Similar to the individual LRU caches, this is scaled up with your CPU
/// core count.
///
/// This defaults to 48.0 + (4.0 * CPU core count).
///
/// default: varies by system
#[serde(default = "default_db_write_buffer_capacity_mb")]
pub db_write_buffer_capacity_mb: f64,
/// default: varies by system
#[serde(default = "default_pdu_cache_capacity")]
pub pdu_cache_capacity: u32,
/// default: varies by system
#[serde(default = "default_auth_chain_cache_capacity")]
pub auth_chain_cache_capacity: u32,
/// default: varies by system
#[serde(default = "default_shorteventid_cache_capacity")]
pub shorteventid_cache_capacity: u32,
/// default: varies by system
#[serde(default = "default_eventidshort_cache_capacity")]
pub eventidshort_cache_capacity: u32,
/// default: varies by system
#[serde(default = "default_eventid_pdu_cache_capacity")]
pub eventid_pdu_cache_capacity: u32,
/// default: varies by system
#[serde(default = "default_shortstatekey_cache_capacity")]
pub shortstatekey_cache_capacity: u32,
/// default: varies by system
#[serde(default = "default_statekeyshort_cache_capacity")]
pub statekeyshort_cache_capacity: u32,
/// default: varies by system
#[serde(default = "default_servernameevent_data_cache_capacity")]
pub servernameevent_data_cache_capacity: u32,
/// default: varies by system
#[serde(default = "default_stateinfo_cache_capacity")]
pub stateinfo_cache_capacity: u32,
/// Minimum time-to-live in seconds for room summary entries in the spaces
/// cache.
///
/// reloadable: yes
/// default: 21600
#[serde(default = "default_spacehierarchy_cache_ttl_min")]
pub spacehierarchy_cache_ttl_min: u64,
/// Maximum time-to-live in seconds for room summary entries in the spaces
/// cache.
///
/// reloadable: yes
/// default: 129600
#[serde(default = "default_spacehierarchy_cache_ttl_max")]
pub spacehierarchy_cache_ttl_max: u64,
/// Minimum timeout a client can request for long-polling sync. Requests
/// will be clamped up to this value if smaller.
///
/// reloadable: yes
/// default: 5000
#[serde(default = "default_client_sync_timeout_min")]
pub client_sync_timeout_min: u64,
/// Default timeout for long-polling sync if a client does not request
/// another in their query-string.
///
/// reloadable: yes
/// default: 30000
#[serde(default = "default_client_sync_timeout_default")]
pub client_sync_timeout_default: u64,
/// Maximum timeout a client can request for long-polling sync. Requests
/// will be clamped down to this value if larger.
///
/// reloadable: yes
/// default: 90000
#[serde(default = "default_client_sync_timeout_max")]
pub client_sync_timeout_max: u64,
/// Maximum entries stored in DNS memory-cache. The size of an entry may
/// vary so please take care if raising this value excessively. Only
/// decrease this when using an external DNS cache. Please note that
/// systemd-resolved does *not* count as an external cache, even when
/// configured to do so.
///
/// default: 32768
#[serde(default = "default_dns_cache_entries")]
pub dns_cache_entries: u32,
/// Minimum time-to-live in seconds for entries in the DNS cache. The
/// default may appear high to most administrators; this is by design as the
/// exotic loads of federating to many other servers require a higher TTL
/// than many domains have set. Even when using an external DNS cache the
/// problem is shifted to that cache which is ignorant of its role for
/// this application and can adhere to many low TTL's increasing its load.
///
/// default: 10800
#[serde(default = "default_dns_min_ttl")]
pub dns_min_ttl: u64,
/// Minimum time-to-live in seconds for NXDOMAIN entries in the DNS cache.
/// This value is critical for the server to federate efficiently.
/// NXDOMAIN's are assumed to not be returning to the federation and
/// aggressively cached rather than constantly rechecked.
///
/// Defaults to 3 days as these are *very rarely* false negatives.
///
/// default: 259200
#[serde(default = "default_dns_min_ttl_nxdomain")]
pub dns_min_ttl_nxdomain: u64,
/// Number of DNS nameserver retries after a timeout or error.
///
/// default: 10
#[serde(default = "default_dns_attempts")]
pub dns_attempts: u16,
/// The number of seconds to wait for a reply to a DNS query. Please note
/// that recursive queries can take up to several seconds for some domains,
/// so this value should not be too low, especially on slower hardware or
/// resolvers.
///
/// default: 10
#[serde(default = "default_dns_timeout")]
pub dns_timeout: u64,
/// Fallback to TCP on DNS errors. Set this to false if unsupported by
/// nameserver.
#[serde(default = "true_fn")]
pub dns_tcp_fallback: bool,
/// Enable to query all nameservers until the domain is found. Referred to
/// as "trust_negative_responses" in hickory_resolver. This can avoid
/// useless DNS queries if the first nameserver responds with NXDOMAIN or
/// an empty NOERROR response.
#[serde(default = "true_fn")]
pub query_all_nameservers: bool,
/// Enable using *only* TCP for querying your specified nameservers instead
/// of UDP.
///
/// If you are running tuwunel in a container environment, this config
/// option may need to be enabled. For more details, see:
/// https://tuwunel.chat/troubleshooting.html#potential-dns-issues-when-using-docker
#[serde(default)]
pub query_over_tcp_only: bool,
/// DNS A/AAAA record lookup strategy
///
/// Takes a number of one of the following options:
/// 1 - Ipv4Only (Only query for A records, no AAAA/IPv6)
///
/// 2 - Ipv6Only (Only query for AAAA records, no A/IPv4)
///
/// 3 - Ipv4AndIpv6 (Query for A and AAAA records in parallel, uses whatever
/// returns a successful response first)
///
/// 4 - Ipv6thenIpv4 (Query for AAAA record, if that fails then query the A
/// record)
///
/// 5 - Ipv4thenIpv6 (Query for A record, if that fails then query the AAAA
/// record)
///
/// If you don't have IPv6 networking, then for better DNS performance it
/// may be suitable to set this to Ipv4Only (1) as you will never ever use
/// the AAAA record contents even if the AAAA record is successful instead
/// of the A record.
///
/// default: 5
#[serde(default = "default_ip_lookup_strategy")]
pub ip_lookup_strategy: u8,
/// List of domain patterns resolved via the alternative path without any
/// persistent cache, very small memory cache, and no enforced TTL. This
/// is intended for internal network and application services which require
/// these specific properties. This path does not support federation or
/// general purposes.
///
/// reloadable: yes
/// example: ["*\.dns\.podman$"]
///
/// default: []
#[serde(default, with = "serde_regex")]
pub dns_passthru_domains: RegexSet,
/// Whether to resolve appservices via the alternative path; setting this is
/// superior to providing domains in `dns_passthru_domains` if all
/// appservices intend to be matched anyway. The overhead of matching regex
/// and maintaining the list of domains can be avoided.
#[serde(default)]
pub dns_passthru_appservices: bool,
/// Enable or disable case randomization for DNS queries. This is a security
/// mitigation where answer spoofing is prevented by having to exactly match
/// the question. Occasional errors seen in logs which may have lead you
/// here tend to be from overloading DNS. Nevertheless for servers which
/// are truly incapable this can be set to false.
///
/// This currently defaults to false due to user reports regarding some
/// popular DNS caches which may or may not be patched soon. It may again
/// default to true in an upcoming release.
#[serde(default)]
pub dns_case_randomization: bool,
/// Max request size for file uploads. Accepts an integer byte count or a
/// string with SI/IEC suffix such as "24 MiB".
///
/// default: 24 MiB
#[serde(
default = "default_max_request_size",
deserialize_with = "deserialize_bytesize_usize"
)]
pub max_request_size: usize,
/// Maximum size of a response body buffered from a remote server. Applies
/// to federation requests, push gateway and appservice transactions, and
/// remote media fetched for URL previews. A peer cannot be trusted to honor
/// a requested limit, so this bounds the response held in memory
/// regardless, guarding against a remote driving the process out of
/// memory. Accepts an integer byte count or a string with SI/IEC suffix
/// such as "256 MiB".
///
/// default: 256 MiB
#[serde(
default = "default_max_response_size",
deserialize_with = "deserialize_bytesize_usize"
)]
pub max_response_size: usize,
/// Maximum number of concurrently pending (asynchronous) media uploads a
/// user can have.
///
/// reloadable: yes
/// default: 5
#[serde(default = "default_max_pending_media_uploads")]
pub max_pending_media_uploads: usize,
/// The time in seconds before an unused pending MXC URI expires and is
/// removed.
///
/// reloadable: yes
/// default: 86400 (24 hours)
#[serde(default = "default_media_create_unused_expiration_time")]
pub media_create_unused_expiration_time: u64,
/// The maximum number of media create requests per second allowed from a
/// single user.
///
/// reloadable: yes
/// default: 10
#[serde(default = "default_media_rc_create_per_second")]
pub media_rc_create_per_second: u32,
/// The maximum burst count for media create requests from a single user.
///
/// reloadable: yes
/// default: 50
#[serde(default = "default_media_rc_create_burst_count")]
pub media_rc_create_burst_count: u32,
/// reloadable: yes
/// default: 192
#[serde(default = "default_max_fetch_prev_events")]
pub max_fetch_prev_events: u16,
/// Maximum time, in milliseconds, to wait for the missing prev_events of an
/// incoming timeline event to arrive on their own before fetching them over
/// federation. A gap that closes within this window skips the fetch. The
/// wait is event-driven and wakes the instant the events arrive, so this is
/// a ceiling on added latency, not a fixed cost. Set to 0 to fetch
/// immediately.
///
/// reloadable: yes
/// default: 750
#[serde(default = "default_fetch_prev_wait_ms")]
pub fetch_prev_wait_ms: u64,
/// Default/base connection timeout (seconds). This is used only by URL
/// previews and update/news endpoint checks.
///
/// default: 10
#[serde(default = "default_request_conn_timeout")]
pub request_conn_timeout: u64,
/// Default/base request timeout (seconds). The time waiting to receive more
/// data from another server. This is used only by URL previews,
/// update/news, and misc endpoint checks.
///
/// default: 35
#[serde(default = "default_request_timeout")]
pub request_timeout: u64,
/// Default/base request total timeout (seconds). The time limit for a whole
/// request. This is set very high to not cancel healthy requests while
/// serving as a backstop. This is used only by URL previews and update/news
/// endpoint checks.
///
/// default: 320
#[serde(default = "default_request_total_timeout")]
pub request_total_timeout: u64,
/// Default/base idle connection pool timeout (seconds). This is used only
/// by URL previews and update/news endpoint checks.
///
/// default: 5
#[serde(default = "default_request_idle_timeout")]
pub request_idle_timeout: u64,
/// Default/base max idle connections per host. This is used only by URL
/// previews and update/news endpoint checks. Defaults to 1 as generally the
/// same open connection can be re-used.
///
/// default: 1
#[serde(default = "default_request_idle_per_host")]
pub request_idle_per_host: u16,
/// Allow the outbound HTTP client to negotiate gzip with other servers:
/// advertise it in Accept-Encoding and transparently decompress responses.
/// This covers federation, media, and URL preview traffic, and is separate
/// from `gzip_compression`, which compresses tuwunel's own responses.
///
/// Enabled by default. Set to false to force the client to neither request
/// nor decompress gzip. Does nothing unless tuwunel was built with the
/// `gzip_compression` feature.
///
/// default: true
#[serde(default = "true_fn")]
pub request_gzip: bool,
/// Allow the outbound HTTP client to negotiate brotli with other servers:
/// advertise it in Accept-Encoding and transparently decompress responses.
/// This covers federation, media, and URL preview traffic, and is separate
/// from `brotli_compression`, which compresses tuwunel's own responses.
///
/// Enabled by default. Set to false to force the client to neither request
/// nor decompress brotli. Does nothing unless tuwunel was built with the
/// `brotli_compression` feature.
///
/// default: true
#[serde(default = "true_fn")]
pub request_brotli: bool,
/// Allow the outbound HTTP client to negotiate zstd with other servers:
/// advertise it in Accept-Encoding and transparently decompress responses.
/// This covers federation, media, and URL preview traffic, and is separate
/// from `zstd_compression`, which compresses tuwunel's own responses.
///
/// Enabled by default. Set to false to force the client to neither request
/// nor decompress zstd. Does nothing unless tuwunel was built with the
/// `zstd_compression` feature.
///
/// default: true
#[serde(default = "true_fn")]
pub request_zstd: bool,
/// Federation well-known resolution connection timeout (seconds).
///
/// default: 6
#[serde(default = "default_well_known_conn_timeout")]
pub well_known_conn_timeout: u64,
/// Federation HTTP well-known resolution request timeout (seconds).
///
/// default: 10
#[serde(default = "default_well_known_timeout")]
pub well_known_timeout: u64,
/// Federation client request timeout (seconds). You most definitely want
/// this to be high to account for extremely large room joins, slow
/// homeservers, your own resources etc.
///
/// default: 300
#[serde(default = "default_federation_timeout")]
pub federation_timeout: u64,
/// Timeout (seconds) for client-initiated federation key lookups, namely
/// /keys/query and /keys/claim against remote servers. Should be well
/// below `federation_timeout` so an interactive request to an unresponsive
/// server does not outlast the requesting client's own send deadline. A
/// lookup that exceeds this bound records a transient federation failure
/// for that server, so subsequent lookups back off instead of blocking
/// again.
///
/// default: 8
#[serde(default = "default_federation_keys_timeout")]
pub federation_keys_timeout: u64,
/// Federation client idle connection pool timeout (seconds).
///
/// default: 25
#[serde(default = "default_federation_idle_timeout")]
pub federation_idle_timeout: u64,
/// Federation client max idle connections per host. Defaults to 1 as
/// generally the same open connection can be re-used.
///
/// default: 1
#[serde(default = "default_federation_idle_per_host")]
pub federation_idle_per_host: u16,
/// Federation sender request timeout (seconds). The time it takes for the
/// remote server to process sent transactions can take a while.
///
/// default: 180
#[serde(default = "default_sender_timeout")]
pub sender_timeout: u64,
/// Federation sender idle connection pool timeout (seconds).
///
/// default: 180
#[serde(default = "default_sender_idle_timeout")]
pub sender_idle_timeout: u64,
/// Federation sender transaction retry backoff limit (seconds).
///
/// reloadable: yes
/// default: 86400
#[serde(default = "default_sender_retry_backoff_limit")]
pub sender_retry_backoff_limit: u64,
/// Appservice URL request connection timeout. Defaults to 35 seconds as
/// generally appservices are hosted within the same network.
///
/// default: 35
#[serde(default = "default_appservice_timeout")]
pub appservice_timeout: u64,
/// Appservice URL idle connection pool timeout (seconds).
///
/// default: 300
#[serde(default = "default_appservice_idle_timeout")]
pub appservice_idle_timeout: u64,
/// Notification gateway pusher idle connection pool timeout.
///
/// default: 15
#[serde(default = "default_pusher_idle_timeout")]
pub pusher_idle_timeout: u64,
/// Maximum time to receive a request from a client (seconds).
///
/// default: 75
#[serde(default = "default_client_receive_timeout")]
pub client_receive_timeout: u64,
/// Maximum time to process a request received from a client (seconds).
///
/// default: 240
#[serde(default = "default_client_request_timeout")]
pub client_request_timeout: u64,
/// Maximum time to transmit a response to a client (seconds)
///
/// default: 120
#[serde(default = "default_client_response_timeout")]
pub client_response_timeout: u64,
/// Grace period for clean shutdown of client requests (seconds).
///
/// reloadable: yes
/// default: 10
#[serde(default = "default_client_shutdown_timeout")]
pub client_shutdown_timeout: u64,
/// Source of the client IP address for rate limiting, logging, and
/// security tooling.
///
/// When unset (the default), the `ClientIp` extractor scans common
/// proxy headers in leftmost-IP mode (`X-Forwarded-For`, RFC 7239
/// `Forwarded`, `X-Real-IP`, `Fly-Client-IP`, `True-Client-IP`,
/// `CF-Connecting-IP`, `CloudFront-Viewer-Address`) and falls back
/// to the TCP peer address; clients can spoof their address via
/// request headers in that mode.
///
/// When set, `ClientIp` resolves exclusively from the selected
/// source. The rightmost value is used for multi-valued headers;
/// only the proxy can append to the right, so this is resistant to
/// client spoofing.
///
/// Supported values:
/// - "connect_info" - TCP peer address only (direct connections)
/// - "rightmost_x_forwarded_for" - nginx, Caddy
/// - "rightmost_forwarded" - RFC 7239 proxies
/// - "x_real_ip" - nginx `X-Real-IP`
/// - "cf_connecting_ip" - Cloudflare / cloudflared
/// - "true_client_ip" - Akamai, Cloudflare Enterprise
/// - "fly_client_ip" - Fly.io
/// - "cloudfront_viewer_address" - AWS CloudFront
///
/// On Unix-socket deployments, leave this unset rather than setting
/// "connect_info"; that source requires a TCP peer address.
///
/// WARNING: A header-based value without a trusted reverse proxy in
/// front of tuwunel allows clients to forge their IP. Changing this
/// value requires a server restart.
///
/// default: unset
/// config-example: "connect_info"
#[serde(default)]
pub ip_source: Option<IpSource>,
/// Subnets whose TCP peers are treated as trusted and bypass the
/// `ip_source`-based extraction, falling through to the same
/// insecure header-scan + `ConnectInfo` fallback used when
/// `ip_source` is unset. Each entry is CIDR notation, including
/// the prefix length (use `/32` or `/128` to trust a single host).
///
/// Loopback (`127.0.0.0/8`, `::1/128`) is always bypassed and
/// need not be listed.
///
/// Use this when locally attached bridges or other server-side
/// clients connect from a private container or VPN subnet that
/// cannot carry the configured proxy header (e.g. a user-defined
/// Docker bridge network without `network_mode: host`).
///
/// NOTE: If you configure an entire subnet here, be sure that it
/// does not include the address Tuwunel receives external traffic
/// from, i.e. that of your proxy. This would, for example, happen
/// if you deployed the proxy in a common bridge network with your
/// other components (e.g. in a Compose deployment) and specified
/// said network's subnet here. Traffic from the proxy would then
/// also have the bypass applied, rendering the `ip_source` option
/// effectively useless.
///
/// WARNING: Any peer in these subnets can forge the client IP via
/// request headers. Only include subnets you control end-to-end.
/// Changing this value requires a server restart.
///
/// default: []
/// config-example: ["172.18.0.0/16", "fd00::/8"]
#[expect(
clippy::doc_link_with_quotes,
reason = "config-example directive emits literal quoted strings, not an intra-doc link"
)]
#[serde(default)]
pub ip_source_trusted_subnets: Vec<IpNet>,
/// Grace period for clean shutdown of federation requests (seconds).
///
/// reloadable: yes
/// default: 5
#[serde(default = "default_sender_shutdown_timeout")]
pub sender_shutdown_timeout: u64,
/// Enables registration. If set to false, no users can register on this
/// server.
///
/// If set to true without a token configured, users can register with no
/// form of 2nd-step only if you set the following option to true:
/// `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse`
///
/// If you would like registration only via token reg, please configure
/// `registration_token` or `registration_token_file`.
/// reloadable: yes
#[serde(default)]
pub allow_registration: bool,
/// Enabling this setting opens registration to anyone without restrictions.
/// This makes your server vulnerable to abuse
/// reloadable: yes
#[serde(default)]
pub yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse: bool,
/// A static registration token that new users will have to provide when
/// creating an account. If unset and `allow_registration` is true,
/// you must set
/// `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse`
/// to true to allow open registration without any conditions.
///
/// YOU NEED TO EDIT THIS OR USE registration_token_file.
///
/// reloadable: yes
/// example: "o&^uCtes4HPf0Vu@F20jQeeWE7"
///
/// display: sensitive
pub registration_token: Option<String>,
/// Path to a file on the system that gets read for additional registration
/// tokens. Multiple tokens can be added if you separate them with
/// whitespace
///
/// tuwunel must be able to access the file, and it must not be empty
///
/// reloadable: yes
/// example: "/etc/tuwunel/.reg_token"
pub registration_token_file: Option<PathBuf>,
/// A pre-shared secret enabling out-of-band account creation via the
/// Synapse-style `/_synapse/admin/v1/register` endpoint. The endpoint is
/// only available when this is set. Requests authenticate by HMAC-SHA1
/// keyed on this value; UIAA is bypassed.
///
/// Use a high-entropy value (at least 32 bytes) and treat it as a
/// secret of equivalent power to a server admin's access token.
///
/// reloadable: yes
/// example: "kZ2hN5pQ8wXyL4mR7tBfCgJxV3aD6sE1u"
///
/// display: sensitive
pub registration_shared_secret: Option<String>,
/// Path to a file containing the registration shared secret. Trimmed of
/// surrounding whitespace on read. Takes precedence over
/// `registration_shared_secret` when both are set.
///
/// reloadable: yes
/// example: "/etc/tuwunel/.reg_shared_secret"
pub registration_shared_secret_file: Option<PathBuf>,
/// Controls whether encrypted rooms and events are allowed.
/// reloadable: yes
#[serde(default = "true_fn")]
pub allow_encryption: bool,
/// Controls whether locally-created rooms should be end-to-end encrypted by
/// default. This option is equivalent to the one found in Synapse.
///
/// Options:
/// - "all": All created rooms are encrypted.
/// - "invite": Any room created with `private_chat` or
/// `trusted_private_chat` presets.
/// - "none": Explicit value for no effect.
/// - Other values default to no effect.
///
/// reloadable: yes
/// default: "none"
#[serde(default)]
pub encryption_enabled_by_default_for_room_type: Option<String>,
/// Controls whether federation is allowed or not. It is not recommended to
/// disable this after installation due to potential federation breakage but
/// this is technically not a permanent setting.
#[serde(default = "true_fn")]
pub allow_federation: bool,
/// (EXPERIMENTAL) Resolve the base event of a room context request by
/// fetching it from federation when the server never received it.
///
/// When a client requests
/// `/_matrix/client/v3/rooms/{roomId}/context/{eventId}` for an event
/// the server does not hold locally, the server fetches it from a room
/// peer and persists it before responding, rather than returning a
/// 404. This is gated on `allow_federation`; with federation disabled
/// it has no effect. Other on-demand federation fetch sites are gated
/// separately.
///
/// reloadable: yes
/// default: false
#[serde(default)]
pub fetch_unreceived_contexts_over_federation: bool,
/// Per-round ceiling on how many servers a federation event fetch contacts
/// concurrently. Tightens the built-in fan-out profile of every fetch kind;
/// it never widens one. 0 leaves the profiles unchanged.
///
/// reloadable: yes
/// default: 0
#[serde(default)]
pub fetch_fanout_max_width: usize,
/// Ceiling on how many staged rounds a federation event fetch runs before
/// giving up. Tightens the built-in round count of every fetch kind; it
/// never raises one. 0 leaves the profiles unchanged.
///
/// reloadable: yes
/// default: 0
#[serde(default)]
pub fetch_fanout_rounds: usize,
/// Sets the default `m.federate` property for newly created rooms when the
/// client does not request one. If `allow_federation` is set to false at
/// the same this value is set to false it then always overrides the client
/// requested `m.federate` value to false.
///
/// Rooms are fixed to the setting at the time of their creation and can
/// never be changed; changing this value only affects new rooms.
/// reloadable: yes
#[serde(default = "true_fn")]
pub federate_created_rooms: bool,
/// Allows federation requests to be made to itself
///
/// This isn't intended and is very likely a bug if federation requests are
/// being sent to yourself. This currently mainly exists for development
/// purposes.
/// reloadable: yes
#[serde(default)]
pub federation_loopback: bool,
/// Always calls /forget on behalf of the user if leaving a room. This is a
/// part of MSC4267 "Automatically forgetting rooms on leave"
/// reloadable: yes
#[serde(default)]
pub forget_forced_upon_leave: bool,
/// Set this to true to require authentication on the normally
/// unauthenticated profile retrieval endpoints (GET)
/// "/_matrix/client/v3/profile/{userId}".
///
/// This can prevent profile scraping.
/// reloadable: yes
#[serde(default)]
pub require_auth_for_profile_requests: bool,
/// Preserve per-room profile overrides during a global profile update.
///
/// When `true` (default), a profile change (displayname or avatar_url)
/// arriving via the profile endpoints skips rooms whose current
/// `m.room.member` already differs from the user's prior global
/// profile. This is the natural behavior users expect after setting a
/// per-room nickname or avatar with a client's `/myroomnick`-style
/// command: a subsequent global change does not clobber the override.
///
/// Set to `false` to always rewrite every joined room's member event
/// to match the new global profile. That matches the literal spec
/// reading.
///
/// MSC4466 lets clients pick this per request via the
/// `org.matrix.msc4466.propagate_to` query parameter
/// (`all` / `unchanged` / `none`); an explicit value overrides this
/// default in either direction.
///
/// reloadable: yes
/// default: true
#[serde(default = "true_fn")]
pub preserve_room_profile_overrides: bool,
/// Set this to true to allow your server's public room directory to be
/// federated. Set this to false to protect against /publicRooms spiders,
/// but will forbid external users from viewing your server's public room
/// directory. If federation is disabled entirely (`allow_federation`), this
/// is inherently false.
/// reloadable: yes
#[serde(default)]
pub allow_public_room_directory_over_federation: bool,
/// Set this to true to allow your server's public room directory to be
/// queried without client authentication (access token) through the Client
/// APIs. Set this to false to protect against /publicRooms spiders.
/// reloadable: yes
#[serde(default)]
pub allow_public_room_directory_without_auth: bool,
/// Allows room directory searches to match on partial room_id's when the
/// search term starts with '!'.
///