1use std::{
8 env::consts::OS,
9 fs::read_to_string,
10 net::{IpAddr, SocketAddr},
11 time::Duration,
12};
13
14use argon2::Error as Argon2Error;
15use either::Either;
16use http::HeaderValue;
17use itertools::Itertools;
18use regex::RegexSet;
19use url::Url;
20
21use super::{
22 DEPRECATED_KEYS, IdentityProvider, KNOWN_KEYS,
23 turn::{Provider, Turn},
24};
25use crate::{
26 Config, Err, Result, debug, debug_info, err, error,
27 utils::{
28 is_secret_set,
29 string::{equals_any, is_opaque_id},
30 sys::storage::{Filesystem, filesystem_from_path},
31 time::timepoint_from_now,
32 },
33 warn,
34};
35
36const MAX_THUMBNAIL_CONCURRENCY: usize = 1024;
42
43pub fn reload(old: &Config, new: &Config) -> Result {
46 check(new)?;
47
48 if new.server_name != old.server_name {
49 return Err!(Config(
50 "server_name",
51 "You can't change the server's name from {:?}.",
52 old.server_name
53 ));
54 }
55
56 if new.http.ip_source != old.http.ip_source {
57 return Err!(Config(
58 "http.ip_source",
59 "http.ip_source cannot be changed at runtime; restart the server to apply this \
60 change."
61 ));
62 }
63
64 if new.storage_provider != old.storage_provider {
65 return Err!(Config(
66 "storage_provider",
67 "Storage providers cannot be changed at runtime; restart the server to apply this \
68 change."
69 ));
70 }
71
72 let old = &old.telemetry.sentry;
73 let new = &new.telemetry.sentry;
74
75 if new.enable != old.enable
76 || new.endpoint != old.endpoint
77 || new.send_server_name != old.send_server_name
78 || new.traces_sample_rate.to_bits() != old.traces_sample_rate.to_bits()
79 || new.attach_stacktrace != old.attach_stacktrace
80 || new.send_panic != old.send_panic
81 || new.send_error != old.send_error
82 || new.filter != old.filter
83 {
84 return Err!(Config(
85 "telemetry.sentry",
86 "Sentry settings cannot be changed at runtime; restart the server to apply this \
87 change."
88 ));
89 }
90
91 Ok(())
92}
93
94pub fn check(config: &Config) -> Result {
100 #[cfg(debug_assertions)]
101 warn!("Note: tuwunel was built without optimisations (i.e. debug build)");
102
103 warn_deprecated(config);
104 warn_legacy_state_local(config);
105 warn_literal_patterns(config);
106 warn_unknown_key(config)?;
107
108 check_observability(config)?;
109 check_network(config)?;
110 check_storage(config)?;
111 check_registration(config)?;
112 check_registration_terms(config)?;
113 check_profile_requests(config)?;
114 check_relation_limits(config)?;
115 check_space_hierarchy_cache(config)?;
116 check_typing_timeouts(config)?;
117 check_password_hashing(config)?;
118 check_jwt(config)?;
119 check_turn_and_media_misc(config)?;
120 check_url_previews(config)?;
121 check_room_version(config)?;
122 check_identity_providers(config)?;
123 warn_oidc_registration_token(config);
124 warn_oidc_client_approval(config);
125 warn_native_auth_without_sign_in(config);
126 check_media_providers(config)?;
127 check_well_known_support_contact_validity(config)?;
128 check_email(config)?;
129
130 Ok(())
131}
132
133fn warn_legacy_state_local(config: &Config) {
134 if config.federation.resolve_state_locally_shadow {
135 warn!(
136 "resolve_state_locally_shadow is deprecated; use \
137 federation.resolve_state_locally=false to disable local state derivation."
138 );
139 }
140}
141
142fn check_observability(config: &Config) -> Result {
143 if config.telemetry.sentry.enable && config.telemetry.sentry.endpoint.is_none() {
144 return Err!(Config(
145 "telemetry.sentry.endpoint",
146 "Sentry cannot be enabled without an endpoint set"
147 ));
148 }
149
150 if config.telemetry.sentry.enable
151 && !(0.0..=1.0).contains(&config.telemetry.sentry.traces_sample_rate)
152 {
153 return Err!(Config(
154 "telemetry.sentry.traces_sample_rate",
155 "Sentry traces sample rate must be between 0.0 and 1.0 inclusive"
156 ));
157 }
158
159 Ok(())
160}
161
162fn check_profile_requests(config: &Config) -> Result {
163 if config.profile.max_remote_fields == 0 {
164 return Err!(Config("profile.max_remote_fields", "Must be greater than zero"));
165 }
166
167 if config.profile.max_fields_per_request == 0 {
168 return Err!(Config("profile.max_fields_per_request", "Must be greater than zero"));
169 }
170
171 if config
172 .profile
173 .limit_requests_to_users_who_share_rooms
174 && !config.profile.require_auth
175 {
176 return Err!(Config(
177 "profile.limit_requests_to_users_who_share_rooms",
178 "profile.limit_requests_to_users_who_share_rooms requires profile.require_auth to \
179 be enabled"
180 ));
181 }
182
183 Ok(())
184}
185
186fn check_relation_limits(config: &Config) -> Result {
187 if config
188 .rooms
189 .redaction
190 .thread_latest_reply_search_limit
191 .eq(&0)
192 {
193 return Err!(Config(
194 "rooms.redaction.thread_latest_reply_search_limit",
195 "Must be greater than zero"
196 ));
197 }
198
199 Ok(())
200}
201
202fn check_space_hierarchy_cache(config: &Config) -> Result {
203 let cache = &config.cache.space_hierarchy;
204
205 if cache.ttl_min >= cache.ttl_max {
206 return Err!(Config(
207 "cache.space_hierarchy.ttl_min",
208 "Must be less than cache.space_hierarchy.ttl_max"
209 ));
210 }
211
212 Ok(())
213}
214
215fn check_typing_timeouts(config: &Config) -> Result {
216 let typing = &config.typing;
217
218 if typing.client_timeout_min_s > typing.client_timeout_max_s {
219 return Err!(Config(
220 "typing.client_timeout_min_s",
221 "Must not exceed typing.client_timeout_max_s"
222 ));
223 }
224
225 Ok(())
226}
227
228fn check_network(config: &Config) -> Result {
229 #[cfg(not(unix))]
230 if config.http.listen.unix_socket_path.is_some() {
231 return Err!(Config(
232 "http.listen.unix_socket_path",
233 "UNIX socket support is only available on *nix platforms. Please remove \
234 'http.listen.unix_socket_path' from your config."
235 ));
236 }
237
238 let certs_set = config.tls.certs.is_some();
239 let key_set = config.tls.key.is_some();
240 if certs_set ^ key_set {
241 return Err!(Config("tls", "tls.certs and tls.key must either both be set or unset"));
242 }
243
244 let depth = config.media.import.conduit.directory_depth;
247 let length = config.media.import.conduit.directory_length;
248
249 if depth > 0 && length == 0 {
250 return Err!(Config(
251 "media.import.conduit.directory_length",
252 "must be non-zero when media.import.conduit.directory_depth is non-zero"
253 ));
254 }
255
256 if depth > 0 && usize::from(depth).saturating_mul(usize::from(length)) >= 64 {
257 return Err!(Config(
258 "media.import.conduit.directory_depth",
259 "media.import.conduit.directory_depth times media.import.conduit.directory_length \
260 must be less than 64, the length of a SHA-256 hex digest"
261 ));
262 }
263
264 let bind_addrs = config.get_bind_addrs();
265
266 if let Some(source) = config.http.ip_source
267 && source.is_header()
268 {
269 warn!(
270 ?source,
271 "http.ip_source selects a header-based source. Ensure a trusted reverse proxy \
272 populates this header for every request; otherwise clients can spoof their IP \
273 address."
274 );
275 } else {
276 warn_unforwarded_local_listeners(config, &bind_addrs);
277 }
278
279 if !config.listening {
280 warn!("Configuration item `listening` is set to `false`. Cannot hear anyone.");
281 }
282
283 if config.federation.history.prev_events_concurrency == 0 {
284 return Err!(Config(
285 "federation.history.prev_events_concurrency",
286 "Previous-event recovery concurrency must be at least one; zero stalls every \
287 incoming event with a backward extremity."
288 ));
289 }
290
291 if config.http.listen.unix_socket_path.is_none() {
292 bind_addrs
293 .iter()
294 .for_each(warn_loopback_in_container);
295 }
296
297 for server in &config.network.dns.servers {
298 if server.parse::<SocketAddr>().is_err() && server.parse::<IpAddr>().is_err() {
299 return Err!(Config(
300 "network.dns.servers",
301 "{server:?} is not an IP address or socket address."
302 ));
303 }
304 }
305
306 for cidr in &config.network.http.ip_range_denylist {
308 if let Err(e) = ipaddress::IPAddress::parse(cidr) {
309 return Err!(Config(
310 "network.http.ip_range_denylist",
311 "Parsing specified IP CIDR range from string failed: {e}."
312 ));
313 }
314 }
315
316 Ok(())
317}
318
319fn warn_unforwarded_local_listeners<'a, Addrs>(config: &Config, bind_addrs: Addrs)
320where
321 Addrs: IntoIterator<Item = &'a SocketAddr>,
322{
323 let local = config.http.listen.unix_socket_path.is_some()
324 || bind_addrs
325 .into_iter()
326 .any(|addr| addr.ip().is_loopback());
327
328 if local {
329 warn!(
330 "Password attempts through a Unix socket or loopback listener have no per-address \
331 limit, since http.ip_source names no forwarding header to identify their clients. \
332 Behind a reverse proxy, set http.ip_source to the header the proxy sets."
333 );
334 }
335}
336
337fn warn_loopback_in_container(addr: &SocketAddr) {
338 use std::path::Path;
339
340 if !addr.ip().is_loopback() {
341 return;
342 }
343
344 debug_info!(
345 "Found loopback listening address {addr}, running checks if we're in a container."
346 );
347
348 if Path::new("/proc/vz").exists() && !Path::new("/proc/bz").exists()
349 {
351 error!(
352 "You are detected using OpenVZ with a loopback/localhost listening address of \
353 {addr}. If you are using OpenVZ for containers and you use NAT-based networking to \
354 communicate with the host and guest, this will NOT work. Please change this to \
355 \"0.0.0.0\". If this is expected, you can ignore.",
356 );
357 } else if Path::new("/.dockerenv").exists() {
358 error!(
359 "You are detected using Docker with a loopback/localhost listening address of \
360 {addr}. If you are using a reverse proxy on the host and require communication to \
361 tuwunel in the Docker container via NAT-based networking, this will NOT work. \
362 Please change this to \"0.0.0.0\". If this is expected, you can ignore.",
363 );
364 } else if Path::new("/run/.containerenv").exists() {
365 error!(
366 "You are detected using Podman with a loopback/localhost listening address of \
367 {addr}. If you are using a reverse proxy on the host and require communication to \
368 tuwunel in the Podman container via NAT-based networking, this will NOT work. \
369 Please change this to \"0.0.0.0\". If this is expected, you can ignore.",
370 );
371 }
372}
373
374fn check_storage(config: &Config) -> Result {
375 if config.rocksdb.max_log_files == 0 {
377 return Err!(Config(
378 "max_log_files",
379 "rocksdb_max_log_files cannot be 0. Please set a value at least 1."
380 ));
381 }
382
383 if config.rocksdb.allow_fallocate
384 && let Some(filesystem) = database_filesystem(config)
385 {
386 warn!(
387 %filesystem,
388 "database_path is on a Copy-on-Write filesystem, where preallocating write-ahead \
389 logs cannot reserve write space and can pin far more disk than the logs contain. \
390 Set rocksdb_allow_fallocate = false."
391 );
392 }
393
394 #[cfg(not(debug_assertions))]
396 if config.server_name == "your.server.name" {
397 return Err!(Config(
398 "server_name",
399 "You must specify a valid server name for production usage of tuwunel."
400 ));
401 }
402
403 Ok(())
404}
405
406fn database_filesystem(config: &Config) -> Option<Filesystem> {
411 config
412 .database_path
413 .ancestors()
414 .map(filesystem_from_path)
415 .find_map(Result::ok)
416 .flatten()
417}
418
419fn check_registration(config: &Config) -> Result {
420 if config
421 .authentication
422 .emergency_password
423 .as_ref()
424 .is_some_and(|emergency_password| emergency_password == "F670$2CP@Hw8mG7RY1$%!#Ic7YA")
425 {
426 return Err!(Config(
427 "authentication.emergency_password",
428 "The public example emergency password is being used, this is insecure. Please \
429 change this."
430 ));
431 }
432
433 if config
434 .authentication
435 .emergency_password
436 .as_ref()
437 .is_some_and(String::is_empty)
438 {
439 return Err!(Config(
440 "authentication.emergency_password",
441 "Emergency password was set to an empty string, this is not valid. Unset \
442 authentication.emergency_password to disable it or set it to a real password."
443 ));
444 }
445
446 if config
447 .registration
448 .token
449 .as_ref()
450 .is_some_and(String::is_empty)
451 {
452 return Err!(Config(
453 "registration.token",
454 "Registration token was specified but is empty (\"\")"
455 ));
456 }
457
458 if config
460 .registration
461 .token_file
462 .as_ref()
463 .is_some_and(|path| {
464 let Ok(token) = read_to_string(path).inspect_err(|e| {
465 error!("Failed to read the registration token file: {e}");
466 }) else {
467 return true;
468 };
469
470 token == String::new()
471 }) {
472 return Err!(Config(
473 "registration.token_file",
474 "Registration token file was specified but is empty or failed to be read"
475 ));
476 }
477
478 let no_token =
479 config.registration.token.is_none() && config.registration.token_file.is_none();
480
481 let email_required =
482 config.smtp.connection_uri.is_some() && config.smtp.require_email_for_registration;
483
484 if config.registration.enable
485 && no_token
486 && !email_required
487 && !config
488 .registration
489 .yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse
490 {
491 return Err!(Config(
492 "registration.token",
493 "!! You have `registration.enable` enabled without a registration token or a \
494 required email stage (`smtp.require_email_for_registration` with \
495 `smtp.connection_uri`). This allows ANYONE to register without any 2nd-step. \
496 Please set a registration token or require an email stage. For security and safety \
497 reasons, tuwunel will shut down. If you are extra sure this is the desired \
498 behaviour you want, please set the following config option to true:
499`registration.yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse`"
500 ));
501 }
502
503 if config.registration.enable
504 && no_token
505 && !email_required
506 && config
507 .registration
508 .yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse
509 {
510 warn!(
511 "Open registration is enabled via setting \
512 `registration.\
513 yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse` and \
514 `registration.enable` to true without a registration token or a required email \
515 stage (`smtp.require_email_for_registration` with `smtp.connection_uri`). You are \
516 expected to be aware of the risks now. If this is not the desired behaviour, \
517 please set a registration token or require an email stage."
518 );
519 }
520
521 Ok(())
522}
523
524fn check_registration_terms(config: &Config) -> Result {
525 for (id, policy) in &config.registration_terms {
526 if !is_opaque_id(id) {
527 return Err!(Config(
528 "registration_terms",
529 "Policy id {id:?} must be a non-empty opaque identifier of at most 255 \
530 characters from [0-9a-zA-Z._~-]."
531 ));
532 }
533
534 for (lang, translation) in &policy.translations {
535 if !matches!(translation.url.scheme(), "http" | "https") {
536 return Err!(Config(
537 "registration_terms",
538 "Policy {id:?} translation {lang:?} url must use the http or https scheme."
539 ));
540 }
541 }
542 }
543
544 Ok(())
545}
546
547fn check_password_hashing(config: &Config) -> Result {
548 let cost = config.password_hash_cost();
549
550 cost.check().map_err(|e| match e {
551 | Argon2Error::TimeTooSmall => err!(Config("authentication.argon2.t_cost", "{e}")),
552 | Argon2Error::ThreadsTooFew | Argon2Error::ThreadsTooMany => {
553 err!(Config("authentication.argon2.p_cost", "{e}"))
554 },
555 | Argon2Error::MemoryTooLittle => err!(Config(
556 "authentication.argon2.m_cost",
557 "{e}; it needs at least eight blocks per lane of authentication.argon2.p_cost"
558 )),
559 | _ => err!(Config("authentication.argon2.m_cost", "{e}")),
560 })?;
561
562 if !cost.is_recommended() {
563 warn!(
564 ?cost,
565 "The Argon2id cost is below the weakest OWASP recommendation, so new password \
566 hashes are cheaper to crack than the default. See authentication.argon2.m_cost for \
567 the recommended pairs."
568 );
569 }
570
571 Ok(())
572}
573
574fn check_jwt(config: &Config) -> Result {
575 let jwt = &config.jwt;
576
577 #[cfg(not(feature = "jwt_login"))]
578 if jwt.enable {
579 return Err!(Config(
580 "jwt.enable",
581 "tuwunel was not built with JWT login support (\"jwt_login\")"
582 ));
583 }
584
585 #[cfg(feature = "jwt_login")]
587 if jwt.enable {
588 jwt.key_format()?;
589 jwt.nonempty_key()?;
590 }
591
592 if jwt.enable && jwt.expire_access_token && config.authentication.access_token_ttl == 0 {
593 return Err!(Config(
594 "jwt.expire_access_token",
595 "Needs an authentication.access_token_ttl greater than zero."
596 ));
597 }
598
599 Ok(())
600}
601
602fn check_turn_and_media_misc(config: &Config) -> Result {
603 check_turn(&config.turn)?;
604
605 if config.http.max_request_size < 10_000_000 {
606 return Err!(Config(
607 "http.max_request_size",
608 "Max request size is less than 10MB. Please increase it as this is too low for \
609 operable federation."
610 ));
611 }
612
613 if config.presence.allow_outgoing && !config.presence.allow_local {
614 return Err!(Config(
615 "presence.allow_local",
616 "Outgoing presence requires allowing local presence. Please enable \
617 'presence.allow_local' or disable outgoing presence."
618 ));
619 }
620
621 if config.push.suppress_when_active {
622 warn!(
623 "Push suppression when active is enabled (EXPERIMENTAL): behavior may change or be \
624 unstable. Disable by removing or setting push.suppress_when_active to false."
625 );
626 }
627
628 check_thumbnails(config)?;
629 check_video_thumbnails(config)
630}
631
632fn check_turn(turn: &Turn) -> Result {
633 if turn.providers().count() > 1 {
634 return Err!(Config(
635 "turn.cloudflare.key_id",
636 "turn.endpoint.url is set as well; configure one TURN credential provider."
637 ));
638 }
639
640 let provider = turn.provider();
641
642 if provider.is_some() && turn.ttl == 0 {
643 return Err!(Config(
644 "turn.ttl",
645 "Needs to be greater than zero while turn.endpoint or turn.cloudflare is set."
646 ));
647 }
648
649 let local = is_secret_set(turn.secret_file.as_deref(), turn.secret.as_deref())
651 || !turn.username.is_empty()
652 || !turn.password.is_empty();
653
654 if let Some(Provider::Cloudflare(cloudflare, _)) = provider
655 && !is_secret_set(cloudflare.token_file.as_deref(), cloudflare.token.as_deref())
656 {
657 warn!(
658 "turn.cloudflare.key_id is set without turn.cloudflare.token or \
659 turn.cloudflare.token_file; every request for TURN credentials will fail."
660 );
661 }
662
663 match provider {
664 | Some(_) if local || !turn.uris.is_empty() => warn!(
665 "turn.uris, the shared TURN secret and the static TURN credentials are ignored \
666 while turn.endpoint or turn.cloudflare provides TURN credentials."
667 ),
668 | None if !local && !turn.uris.is_empty() => warn!(
669 "turn.uris is configured but no credential source is set; the endpoint \
670 /_matrix/client/v3/voip/turnServer will return empty username and password. Set \
671 turn.secret, turn.secret_file, or both turn.username and turn.password."
672 ),
673 | _ => {},
674 }
675
676 Ok(())
677}
678
679fn check_thumbnails(config: &Config) -> Result {
680 if config.media.thumbnail.max_pixels == 0 {
681 return Err!(Config(
682 "media.thumbnail.max_pixels",
683 "A pixel budget of zero refuses every picture; remove the setting to take the \
684 default."
685 ));
686 }
687
688 if unusable_concurrency(config.media.thumbnail.animated_concurrency) {
689 return Err!(Config(
690 "media.thumbnail.animated_concurrency",
691 "Animated thumbnail source jobs permitted at once must be between 1 and \
692 {MAX_THUMBNAIL_CONCURRENCY}: zero leaves every source read waiting for a slot that \
693 never frees, and the ceiling is far past any useful degree of parallelism."
694 ));
695 }
696
697 Ok(())
698}
699
700fn check_video_thumbnails(config: &Config) -> Result {
701 if unusable_concurrency(config.media.video_thumbnail.concurrency) {
702 return Err!(Config(
703 "media.video_thumbnail.concurrency",
704 "Video thumbnail programs permitted at once must be between 1 and \
705 {MAX_THUMBNAIL_CONCURRENCY}: zero leaves every extraction waiting for a slot that \
706 never frees, and the ceiling is far past any useful degree of parallelism."
707 ));
708 }
709
710 if config.media.video_thumbnail.timeout == 0 {
711 return Err!(Config(
712 "media.video_thumbnail.timeout",
713 "A video thumbnail deadline of zero expires before the program can start."
714 ));
715 }
716
717 Ok(())
718}
719
720fn unusable_concurrency(slots: usize) -> bool {
725 !(1..=MAX_THUMBNAIL_CONCURRENCY).contains(&slots)
726}
727
728fn check_url_previews(config: &Config) -> Result {
729 let url_preview_wildcards = [
730 (
731 "media.url_preview.domain_contains_allowlist",
732 &config.media.url_preview.domain_contains_allowlist,
733 ),
734 (
735 "media.url_preview.domain_explicit_allowlist",
736 &config.media.url_preview.domain_explicit_allowlist,
737 ),
738 (
739 "media.url_preview.url_contains_allowlist",
740 &config.media.url_preview.url_contains_allowlist,
741 ),
742 ];
743
744 url_preview_wildcards
745 .into_iter()
746 .filter(|&(_, list)| equals_any("*", list))
747 .for_each(|(name, _)| {
748 warn!(
749 setting = name,
750 "All URLs are allowed for URL previews by \"*\" in this setting. This opens up \
751 significant attack surface to your server. You are expected to be aware of the \
752 risks by doing this."
753 );
754 });
755
756 warn_domain_contains_entries(config);
757
758 if let Some(Either::Right(_)) = config.media.url_preview.bound_interface.as_ref()
759 && !matches!(OS, "android" | "fuchsia" | "linux")
760 {
761 return Err!(Config(
762 "media.url_preview.bound_interface",
763 "Not a valid IP address. Interface names not supported on {OS}."
764 ));
765 }
766
767 if let Some(user_agent) = config.media.url_preview.user_agent.as_deref()
768 && HeaderValue::from_str(user_agent).is_err()
769 {
770 return Err!(Config("media.url_preview.user_agent", "Not a valid HTTP header value."));
771 }
772
773 if let Some(user_agent) = config
774 .media
775 .url_preview
776 .media_user_agent
777 .as_deref()
778 && HeaderValue::from_str(user_agent).is_err()
779 {
780 return Err!(Config(
781 "media.url_preview.media_user_agent",
782 "Not a valid HTTP header value."
783 ));
784 }
785
786 if let Some(accept_language) = config
787 .media
788 .url_preview
789 .accept_language
790 .as_deref()
791 && HeaderValue::from_str(accept_language).is_err()
792 {
793 return Err!(Config(
794 "media.url_preview.accept_language",
795 "Not a valid HTTP header value."
796 ));
797 }
798
799 timepoint_from_now(Duration::from_secs(config.media.url_preview.cache_ttl)).map_err(
800 |_| {
801 err!(Config(
802 "media.url_preview.cache_ttl",
803 "Value is too large to add to the current time."
804 ))
805 },
806 )?;
807
808 Ok(())
809}
810
811fn warn_domain_contains_entries(config: &Config) {
816 let entries = &config.media.url_preview.domain_contains_allowlist;
817
818 if entries.iter().any(String::is_empty) {
819 warn!(
820 setting = "media.url_preview.domain_contains_allowlist",
821 "An empty entry matches nothing."
822 );
823 }
824
825 entries
826 .iter()
827 .filter(|entry| entry.contains('/'))
828 .for_each(|entry| {
829 warn!(
830 setting = "media.url_preview.domain_contains_allowlist",
831 ?entry,
832 "Matched against the host alone, so this entry never matches."
833 );
834 });
835}
836
837fn check_room_version(config: &Config) -> Result {
838 if !config.supported_room_version(&config.rooms.default_version) {
839 return Err!(Config(
840 "rooms.default_version",
841 "Room version {:?} is not available",
842 config.rooms.default_version
843 ));
844 }
845
846 if config
847 .rooms
848 .default_power_level_content_override
849 .as_ref()
850 .is_some_and(|value| !value.is_object())
851 {
852 return Err!(Config(
853 "rooms.default_power_level_content_override",
854 "must be a table (a JSON object)"
855 ));
856 }
857
858 Ok(())
859}
860
861fn check_identity_providers(config: &Config) -> Result {
862 for a in config.identity_provider.values() {
863 let count = config
864 .identity_provider
865 .values()
866 .filter(|b| a.id().eq(b.id()))
867 .count();
868
869 debug_assert_ne!(count, 0, "expected at least one identity_provider");
870 if count > 1 {
871 return Err!(Config(
872 "client_id",
873 "Duplicate identity_provider with client_id {}",
874 a.client_id
875 ));
876 }
877 }
878
879 for (i, provider) in &config.identity_provider {
880 check_identity_provider_secret(i, provider)?;
881 }
882
883 if !config
884 .authentication
885 .login
886 .sso_custom_providers_page
887 && config.identity_provider.len() > 1
888 && config
889 .identity_provider
890 .values()
891 .filter(|idp| idp.default)
892 .count()
893 .eq(&0)
894 {
895 let default = config
896 .identity_provider
897 .values()
898 .next()
899 .map(IdentityProvider::id)
900 .expect("Check at least one provider is configured to reach here");
901
902 warn!(
903 "More than one identity_provider has been configured without any default selected. \
904 To prevent this warning set `default = true` for one provider. Considering \
905 {default} the default for now..."
906 );
907 }
908
909 let mas_active = config
910 .authentication
911 .mas_secret
912 .as_deref()
913 .is_some_and(|secret| !secret.is_empty());
914
915 if mas_active
916 && !config
917 .identity_provider
918 .values()
919 .any(|provider| provider.brand == "mas")
920 {
921 warn!(
922 "authentication.mas_secret is set but no identity_provider is configured with \
923 `brand = MAS`. Tuwunel is its own OpenID Connect issuer and does not delegate \
924 authentication to MAS; the secret only authorizes MAS provisioning calls on \
925 `/_synapse/mas/`. Logging in through MAS additionally requires an \
926 identity_provider entry with `brand = MAS`."
927 );
928 }
929
930 if mas_active {
931 config
932 .identity_provider
933 .values()
934 .filter(|provider| provider.brand == "mas" && !provider.trusted)
935 .for_each(|provider| {
936 warn!(
937 provider = provider.id(),
938 "`authentication.mas_secret` is set and this MAS identity provider is \
939 configured without `trusted = true`. Existing accounts provisioned by MAS \
940 will not be matched automatically during SSO login, so users may receive \
941 separate accounts. Set `trusted = true` only when this identity provider \
942 is the same self-hosted MAS instance that provisions this server and you \
943 fully control it; otherwise associate users explicitly."
944 );
945 });
946 }
947
948 Ok(())
949}
950
951fn check_identity_provider_secret(i: &str, provider: &IdentityProvider) -> Result {
952 if provider.client_secret.is_some() {
953 return Ok(());
954 }
955
956 let Some(secret_path) = &provider.client_secret_file else {
957 return Err!(Config(
958 "client_secret",
959 "Either client secret or a client secret file must be set on identity provider №{i}."
960 ));
961 };
962
963 let secret = read_to_string(secret_path).map_err(|e| {
964 err!(Config(
965 "client_secret_file",
966 "Failed to read client secret file {secret_path:?} on identity provider №{i}: {e}"
967 ))
968 })?;
969
970 if secret.trim().is_empty() {
971 return Err!(Config(
972 "client_secret_file",
973 "Client secret file {secret_path:?} is empty on identity provider №{i}"
974 ));
975 }
976
977 Ok(())
978}
979
980fn warn_oidc_client_approval(config: &Config) {
981 if !config.authentication.oidc.require_client_approval {
982 warn!(
983 "authentication.oidc.require_client_approval is disabled, so an authorization code \
984 is issued without asking the user, whichever client requested it. Anyone who can \
985 reach dynamic client registration can then register a client with a redirect \
986 target they control and phish a sign-in link. Prefer listing the clients you serve \
987 in authentication.oidc.registration_allowed_redirect_hosts, which waives the \
988 prompt for them alone."
989 );
990 }
991}
992
993fn warn_oidc_registration_token(config: &Config) {
994 if !config
995 .authentication
996 .oidc
997 .registration_access_token
998 .is_empty()
999 {
1000 warn!(
1001 "authentication.oidc.registration_access_token is set, so dynamic client \
1002 registration requires an RFC 7591 initial access token. No Matrix client sends \
1003 one, so next-gen auth login will fail with `M_FORBIDDEN` for every ordinary \
1004 client. Leave it empty unless every OAuth client on this server is registered out \
1005 of band."
1006 );
1007 }
1008}
1009
1010fn warn_native_auth_without_sign_in(config: &Config) {
1011 if config.authentication.oidc.native_auth
1012 && !config.authentication.login.with_password
1013 && config.identity_provider.is_empty()
1014 {
1015 warn!(
1016 "authentication.oidc.native_auth is enabled, but authentication.login.with_password \
1017 is false and no identity_provider is configured, so the native login page offers \
1018 no way to sign in. Enable password login or configure an identity provider."
1019 );
1020 }
1021}
1022
1023fn check_media_providers(config: &Config) -> Result {
1024 if config
1025 .media
1026 .store_on_providers
1027 .iter()
1028 .any(|provider| !config.media.storage_providers.contains(provider))
1029 {
1030 return Err!(Config(
1031 "media.store_on_providers",
1032 "Providers must be listed in 'media.storage_providers'"
1033 ));
1034 }
1035
1036 if config
1037 .media
1038 .storage_providers
1039 .iter()
1040 .filter(|&provider| {
1041 if config.storage_provider.contains_key(provider) || provider == "media" {
1042 return false;
1043 }
1044
1045 error!(?provider, "`media.storage_providers` references non-existent provider");
1046 true
1047 })
1048 .count()
1049 .gt(&0)
1050 {
1051 return Err!(Config(
1052 "media.storage_providers",
1053 "Contains missing or unconfigured storage providers."
1054 ));
1055 }
1056
1057 if !has_upload_provider(config) {
1058 config
1059 .storage_provider_sections()
1060 .filter(|(name, _)| config.media.writes_to(name))
1061 .for_each(|(provider, _)| {
1062 error!(?provider, "Storage provider for uploads is disabled");
1063 });
1064
1065 return if config.media.store_on_providers.is_empty() {
1066 Err!(Config(
1067 "media.storage_providers",
1068 "No enabled storage provider is left to receive uploads."
1069 ))
1070 } else {
1071 Err!(Config(
1072 "media.store_on_providers",
1073 "No enabled storage provider is left to receive uploads."
1074 ))
1075 };
1076 }
1077
1078 if config.media.storage_providers.len() > 1 && config.media.store_on_providers.is_empty() {
1079 warn!(
1080 providers = ?config.media.storage_providers,
1081 "Media will be duplicated to multiple providers until \
1082 `media.store_on_providers` is configured. This warning can be suppressed by \
1083 explicitly configuring `media.store_on_providers`"
1084 );
1085 }
1086
1087 Ok(())
1088}
1089
1090fn has_upload_provider(config: &Config) -> bool {
1095 config
1096 .storage_provider_sections()
1097 .filter(|(_, provider)| provider.is_enabled())
1098 .any(|(name, _)| config.media.writes_to(name))
1099}
1100
1101fn check_well_known_support_contact_validity(config: &Config) -> Result {
1102 let well_known = &config.well_known;
1103
1104 if well_known.support_role.is_some()
1105 && well_known.support_email.is_none()
1106 && well_known.support_mxid.is_none()
1107 {
1108 return Err!(
1109 "well_known.support_role is set but neither support_email nor support_mxid is \
1110 configured to accompany it"
1111 );
1112 }
1113
1114 if let Some(pgp_key) = well_known.support_pgp_key.as_deref() {
1115 validate_pgp_key(pgp_key).map_err(|e| err!("well_known.support_pgp_key: {e}"))?;
1116 }
1117
1118 for (id, contact) in &well_known.support_contact {
1119 if contact.email_address.is_none() && contact.matrix_id.is_none() {
1120 return Err!(
1121 "well_known.support_contact.{id} has neither email_address nor matrix_id; at \
1122 least one is required"
1123 );
1124 }
1125
1126 if let Some(pgp_key) = contact.pgp_key.as_deref() {
1127 validate_pgp_key(pgp_key)
1128 .map_err(|e| err!("well_known.support_contact.{id}.pgp_key: {e}"))?;
1129 }
1130 }
1131
1132 Ok(())
1133}
1134
1135fn check_email(config: &Config) -> Result {
1136 let smtp = &config.smtp;
1137
1138 if smtp.connection_uri.is_some() && config.well_known.client.is_none() {
1139 return Err!(Config(
1140 "well_known.client",
1141 "global.smtp is configured but well_known.client is unset. Email verification links \
1142 are built from the public client base URL, so set well_known.client to a valid \
1143 HTTPS URL alongside global.smtp."
1144 ));
1145 }
1146
1147 if smtp.connection_uri.is_none()
1148 && (smtp.require_email_for_registration || smtp.require_email_for_token_registration)
1149 {
1150 return Err!(Config(
1151 "smtp.connection_uri",
1152 "global.smtp requires a verified email at registration but smtp.connection_uri is \
1153 unset. Set smtp.connection_uri so verification mail can be sent, or unset \
1154 require_email_for_registration and require_email_for_token_registration."
1155 ));
1156 }
1157
1158 Ok(())
1159}
1160
1161fn validate_pgp_key(value: &str) -> Result {
1163 if value.contains("BEGIN PGP") {
1164 return Err!(
1165 "must be a URI, not inlined key material; publish the key and reference it by URI \
1166 (for example https://example.com/key.asc or openpgp4fpr:<fingerprint>)"
1167 );
1168 }
1169
1170 let uri = Url::parse(value).map_err(|_| {
1171 err!("must be a URI; a bare fingerprint must be prefixed with `openpgp4fpr:`")
1172 })?;
1173
1174 if uri.scheme() == "openpgp4fpr" && !valid_openpgp4fpr(uri.path()) {
1175 return Err!("`openpgp4fpr:` must be followed by a 40- or 64-character hex fingerprint");
1176 }
1177
1178 Ok(())
1179}
1180
1181fn valid_openpgp4fpr(fpr: &str) -> bool {
1182 matches!(fpr.len(), 40 | 64) && fpr.bytes().all(|b| b.is_ascii_hexdigit())
1183}
1184
1185fn warn_deprecated(config: &Config) {
1188 debug!("Checking for deprecated config keys");
1189 let found_deprecated_keys = config
1190 .catchall
1191 .keys()
1192 .filter(|key| DEPRECATED_KEYS.iter().any(|s| s == key))
1193 .inspect(|key| warn!("Config parameter \"{key}\" is deprecated, ignoring."))
1194 .next()
1195 .is_some();
1196
1197 if found_deprecated_keys {
1198 warn!(
1199 "Deprecated config keys were found. Read tuwunel config documentation at https://tuwunel.chat/configuration.html and \
1200 check your configuration if any new configuration parameters should be adjusted"
1201 );
1202 }
1203}
1204
1205fn warn_literal_patterns(config: &Config) {
1213 let allowed = &config
1214 .federation
1215 .allowed_remote_server_names_experimental;
1216
1217 let directory_servers = &config
1218 .directory
1219 .rooms
1220 .forbidden_remote_server_names;
1221
1222 let options = [
1223 ("network.dns.passthru_domains", &config.network.dns.passthru_domains),
1224 ("federation.allowed_remote_server_names_experimental", allowed),
1225 ("media.prevent_downloads_from", &config.media.prevent_downloads_from),
1226 (
1227 "federation.forbidden_remote_server_names",
1228 &config.federation.forbidden_remote_server_names,
1229 ),
1230 ("directory.rooms.forbidden_remote_server_names", directory_servers),
1231 ("rooms.forbidden_alias_names", &config.rooms.forbidden_alias_names),
1232 ("registration.forbidden_usernames", &config.registration.forbidden_usernames),
1233 ("rooms.joins.deprioritize_servers", &config.rooms.joins.deprioritize_servers),
1234 ];
1235
1236 options
1237 .into_iter()
1238 .flat_map(|(name, regexes)| {
1239 regexes
1240 .patterns()
1241 .iter()
1242 .map(move |pattern| (name, pattern.as_str()))
1243 })
1244 .filter(|(_, pattern)| is_literal_dotted(pattern))
1245 .for_each(warn_literal_pattern);
1246}
1247
1248fn is_literal_dotted(pattern: &str) -> bool {
1256 let nameable =
1257 |c: char| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '=' | '/');
1258
1259 pattern.contains('.')
1260 && pattern.chars().any(|c| c.is_ascii_alphanumeric())
1261 && pattern.chars().all(nameable)
1262}
1263
1264fn warn_literal_pattern((name, pattern): (&str, &str)) {
1265 let escaped = pattern.replace('.', "\\.");
1266
1267 warn!(
1270 "Config option {name:?} holds the pattern {pattern:?}, which is a regular expression: \
1271 its unescaped dots match any character, so it matches more than the name it reads as. \
1272 To match the dots literally, write it as {escaped:?}, quoted exactly as shown."
1273 );
1274}
1275
1276fn warn_unknown_key(config: &Config) -> Result {
1279 debug!("Checking for unknown config keys");
1280 let known_keys =
1281 RegexSet::new(KNOWN_KEYS).expect("Invalid regular expression set construction");
1282
1283 let unknown_keys = config
1284 .catchall
1285 .keys()
1286 .filter(|key| !known_keys.is_match(key))
1287 .inspect(|key| {
1288 if config.configuration.error_on_unknown_opts {
1289 error!("Config parameter \"{key}\" is unknown to tuwunel");
1290 } else {
1291 warn!("Config parameter \"{key}\" is unknown to tuwunel, ignoring.");
1292 }
1293 })
1294 .collect_vec();
1295
1296 if !unknown_keys.is_empty() && config.configuration.error_on_unknown_opts {
1297 Err!("Unknown config options were found: {unknown_keys:?}")
1298 } else {
1299 Ok(())
1300 }
1301}