Skip to main content

tuwunel_core/config/
mod.rs

1//! Loads and validates server configuration.
2//!
3//! Configuration types preserve startup sources for reloads and expose typed
4//! settings to the rest of the workspace. Field documentation also supplies the
5//! generated example configuration.
6
7pub mod cache;
8pub mod check;
9pub mod database;
10pub mod federation;
11mod format;
12pub mod http;
13mod identity_provider_serde;
14pub mod ip_source;
15#[cfg(feature = "jwt_login")]
16mod jwt;
17pub mod manager;
18pub mod media;
19mod net;
20pub mod network;
21mod normalize;
22pub mod proxy;
23mod regenerate;
24mod rocksdb;
25pub mod room_version;
26pub mod rooms;
27pub mod runtime;
28pub mod sending;
29pub mod sources;
30#[cfg(test)]
31mod tests;
32pub mod well_known;
33
34pub mod authentication;
35pub mod directory;
36pub mod encryption;
37pub mod profile;
38pub mod registration;
39
40pub mod admin;
41pub mod appservice_client;
42pub mod client;
43pub mod compatibility;
44pub mod configuration;
45pub mod logging;
46pub mod presence;
47pub mod push;
48pub mod read_receipts;
49pub mod rendezvous;
50pub mod telemetry;
51pub mod tracing;
52pub mod turn;
53pub mod typing;
54
55use std::{
56	borrow::Cow,
57	collections::{BTreeMap, BTreeSet},
58	iter::once,
59	path::{Path, PathBuf},
60};
61
62use bytesize::ByteSize;
63use derive_more::Debug;
64use figment::{
65	Error as FigmentError, Profile as FigmentProfile, Provider, Source,
66	providers::{Env, Format},
67};
68pub use figment::{Figment, value::Value as FigmentValue};
69use itertools::Itertools;
70use regex::RegexSet;
71pub use rocksdb::Rocksdb;
72use ruma::{
73	OwnedMxcUri, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId,
74	api::client::discovery::discover_support::ContactRole,
75};
76use serde::{Deserialize, de::IgnoredAny};
77use smallstr::SmallString;
78use tuwunel_macros::config_example_generator;
79use url::Url;
80
81pub use self::{
82	admin::Admin,
83	appservice_client::AppserviceClient,
84	authentication::Authentication,
85	cache::Cache,
86	check::check,
87	client::Client,
88	compatibility::Compatibility,
89	configuration::Configuration,
90	database::Database,
91	directory::Directory,
92	encryption::Encryption,
93	federation::Federation,
94	http::Http,
95	ip_source::{IpSource, UNIX_SOCKET_PEER},
96	logging::Logging,
97	manager::Manager,
98	media::Media,
99	network::Network,
100	presence::Presence,
101	profile::Profile,
102	push::Push,
103	read_receipts::ReadReceipts,
104	regenerate::{
105		Overwrite, RegenerateOptions, RegenerationSummary, example_config, regenerate_config,
106		write_example_config,
107	},
108	registration::Registration,
109	rendezvous::Rendezvous,
110	rooms::Rooms,
111	runtime::Runtime,
112	sending::Sending,
113	sources::Sources,
114	telemetry::Telemetry,
115	tracing::Tracing,
116	turn::Turn,
117	typing::Typing,
118};
119use self::{
120	format::Toml,
121	normalize::{
122		assert_canonical, environment, normalize as normalize_provider, redact_error, unknown,
123	},
124	proxy::ProxyConfig,
125};
126use crate::{
127	Err, Error, Result, err, implement, redacted_debug,
128	utils::{
129		self, BoolExt,
130		bytes::{deserialize_bytesize_u64, deserialize_bytesize_usize},
131		hash::Cost,
132		sys,
133	},
134};
135
136// Later prefixes override earlier ones.
137pub(crate) const ENV_PREFIXES: [&str; 3] = ["CONDUIT_", "CONDUWUIT_", "TUWUNEL_"];
138
139/// Stores the configured localpart for the server's administrative user.
140///
141/// The inline budget covers ordinary Matrix localparts without a heap
142/// allocation. Longer valid localparts spill transparently.
143pub type ServerUserLocalpart = SmallString<[u8; 32]>;
144
145/// Stores an object-storage bucket name inline in the common case.
146pub type StorageBucketName = SmallString<[u8; 64]>;
147
148/// Names a storage provider section and holds its settings.
149///
150/// Configured sections are borrowed from the config; the built-in `media`
151/// provider is built on demand and owned.
152pub type ProviderSection<'a> = (&'a str, Cow<'a, StorageProvider>);
153
154/// Global settings
155///
156/// Every setting lives under `[global]`. The first keys below name the
157/// server and its storage; each `[global.<name>]` section further down is
158/// optional and keeps its defaults when left out.
159///
160/// Before the first start, set `server_name` and check `database_path`.
161/// The first start records `server_name` in the database, and a database
162/// recorded under another name is refused, so changing the name later
163/// means starting over with an empty database. `database_path` holds the
164/// database and, by default, uploaded media.
165///
166/// Tips:
167/// - No config file is read by default. Name one with `TUWUNEL_CONFIG`
168///   (or `CONDUWUIT_CONFIG`, `CONDUIT_CONFIG`) or with `-c`/`--config`,
169///   which is repeatable and loads after it; later files win. A file that
170///   mixes bare keys with a `[global]` header is refused.
171/// - Environment variables override files: `TUWUNEL_` plus the key path
172///   with `__` between levels, so `database.backup.path` becomes
173///   `TUWUNEL_DATABASE__BACKUP__PATH`. `-O key=value` overrides both.
174/// - Keys marked `reloadable: yes` apply on `SIGUSR1` or
175///   `!admin server reload-config`; others may need a restart. A reload
176///   that changes `server_name` fails.
177/// - Misspelled keys are ignored, not rejected; most log a warning, and
178///   `configuration.error_on_unknown_opts = true` makes that fatal.
179#[expect(rustdoc::broken_intra_doc_links, rustdoc::bare_urls)]
180#[derive(Clone, Deserialize)]
181#[config_example_generator(
182	filename = "tuwunel-example.toml",
183	section = "global",
184	undocumented = "# This item is undocumented. Please contribute documentation for it.",
185	header = r#"### Tuwunel Configuration
186###
187### THIS FILE IS GENERATED. CHANGES/CONTRIBUTIONS IN THE REPO WILL BE
188### OVERWRITTEN!
189###
190### You should rename this file before configuring your server. Changes to
191### documentation and defaults can be contributed in source code at
192### src/core/config/. This file is generated when building.
193###
194### Any values pre-populated are the default values for said config option.
195###
196### At the minimum, you MUST edit all the config options to your environment
197### that say "YOU NEED TO EDIT THIS".
198###
199### For more information, see:
200### https://tuwunel.chat/configuration.html
201"#,
202	ignore = "rocksdb catchall well_known tls rate_limiting ldap jwt appservice \
203	          identity_provider storage_provider registration_terms smtp cache database runtime \
204	          http network media federation rooms sending authentication directory encryption \
205	          profile registration admin appservice_client client compatibility configuration \
206	          logging presence push read_receipts rendezvous telemetry tracing turn typing",
207	forbidden = "database_restore_backup force_migration"
208)]
209pub struct Config {
210	/// RocksDB engine settings.
211	///
212	/// display: section
213	#[serde(default)]
214	pub rocksdb: Rocksdb,
215
216	/// The server_name is the pretty name of this server. It is used as a
217	/// suffix for user and room IDs/aliases.
218	///
219	/// See the docs for reverse proxying and delegation:
220	/// https://tuwunel.chat/deploying/generic.html#setting-up-the-reverse-proxy
221	///
222	/// Also see the `[global.well_known]` config section at the very bottom.
223	///
224	/// Examples of delegation:
225	/// - https://matrix.org/.well-known/matrix/server
226	/// - https://matrix.org/.well-known/matrix/client
227	///
228	/// YOU NEED TO EDIT THIS. THIS CANNOT BE CHANGED AFTER WITHOUT A DATABASE
229	/// WIPE.
230	///
231	/// example: "girlboss.ceo"
232	#[cfg_attr(test, serde(default = "default_server_name"))]
233	pub server_name: OwnedServerName,
234
235	/// This is the only directory where tuwunel will save its data, including
236	/// media. Note: this was previously "/var/lib/matrix-conduit".
237	///
238	/// default: "/var/lib/tuwunel"
239	#[serde(default = "default_database_path")]
240	pub database_path: PathBuf,
241
242	/// Configures direct TLS listeners.
243	///
244	/// Values are read from the separate `[global.tls]` section. Certificate
245	/// and key paths must be supplied together before TLS is enabled.
246	// external structure; separate section
247	#[serde(default)]
248	pub tls: TlsConfig,
249
250	/// Restore this online database backup on startup, before the database is
251	/// opened. The value is a backup ID as listed by `!admin server
252	/// list-backups`, or 0 for the most recent backup. Set by the
253	/// `--restore-backup` command line argument, and refused from a
254	/// configuration file, where it would repeat the restore on every
255	/// startup.
256	pub database_restore_backup: Option<u32>,
257
258	/// Configures Matrix discovery documents and related endpoints.
259	///
260	/// Values are read from the separate `[global.well_known]` section. Client,
261	/// server, support, and MatrixRTC responses consume these settings.
262	// external structure; separate section
263	#[serde(default)]
264	pub well_known: WellKnownConfig,
265
266	#[cfg(not(doctest))]
267	/// Examples:
268	///
269	/// - No proxy (default):
270	///
271	///       proxy = "none"
272	///
273	/// - For global proxy, create the section at the bottom of this file:
274	///
275	///       [global.proxy]
276	///       global = { url = "socks5h://localhost:9050" }
277	///
278	/// - To proxy some domains:
279	///
280	///       [global.proxy]
281	///       [[global.proxy.by_domain]]
282	///       url = "socks5h://localhost:9050"
283	///       include = ["*.onion", "matrix.myspecial.onion"]
284	///       exclude = ["*.myspecial.onion"]
285	///
286	/// Include vs. Exclude:
287	///
288	/// - If include is an empty list, it is assumed to be `["*"]`.
289	///
290	/// - If a domain matches both the exclude and include list, the proxy will
291	///   only be used if it was included because of a more specific rule than
292	///   it was excluded. In the above example, the proxy would be used for
293	///   `ordinary.onion`, `matrix.myspecial.onion`, but not
294	///   `hello.myspecial.onion`.
295	///
296	/// default: "none"
297	#[serde(default)]
298	pub proxy: ProxyConfig,
299
300	/// Configures request rate limits, one `[global.rate_limiting]` subsection
301	/// per kind of request.
302	// external structure; separate section
303	#[serde(default)]
304	pub rate_limiting: RateLimits,
305
306	/// Arbitrary argument vector for integration testing. Functionality in the
307	/// server is altered or informed for the requirements of integration tests.
308	/// - "smoke" performs a shutdown after startup admin commands rather than
309	///   hanging on client handling.
310	///
311	/// display: hidden
312	#[serde(default)]
313	pub test: BTreeSet<String>,
314
315	/// Indicates the server has started in maintenance mode. Historically
316	/// maintenance mode has been enabled by the command line argument
317	/// `--maintenance` which then sets various configuration items such as
318	/// `listening=false` among others. That is still the case. This option was
319	/// only added as a single source of truth that `--maintenance` mode is
320	/// active.
321	///
322	/// This option must never be set manually.
323	///
324	/// display: hidden
325	#[serde(default)]
326	pub maintenance: bool,
327
328	/// Enables listener sockets; can be set to false to disable listening. This
329	/// option is intended for developer/diagnostic purposes only.
330	#[serde(default = "true_fn")]
331	pub listening: bool,
332
333	/// Directory containing appservice yaml registration files.
334	///
335	/// default: ""
336	#[serde(default)]
337	pub appservice_dir: Option<PathBuf>,
338
339	/// Apply pending database migrations on startup. This option is intended for
340	/// developer debugging and testing only. Never set this option to false
341	/// unless you have been instructed to do so. Setting this option to false
342	/// may cause permanent damage and permanent loss of data.
343	///
344	/// Any new database migrations will not be applied on startup, and the
345	/// database schema version will not be adjusted. These migrations and
346	/// schema changes may be expected by the current codebase but may not be
347	/// available when this option is set to false.
348	///
349	/// Setting this option to false is accepted only after the required local
350	/// state memo invalidation has run once. Start once with this option true if
351	/// startup reports that prerequisite missing. With the marker present,
352	/// false continues to skip migrations as configured.
353	#[serde(default = "true_fn")]
354	pub database_migrations: bool,
355
356	/// Open a database whose schema version is newer than this build supports.
357	///
358	/// A database reporting a higher schema version than this build is normally
359	/// refused, since opening it stamps the schema down to this build's version
360	/// and may permanently lose data written by the newer build. Setting this
361	/// to true overrides that refusal: the database opens, one-time migrations
362	/// run, and the schema is stamped down to this build's version.
363	///
364	/// It has no effect when the discovered version is at or below this build's
365	/// version, where migrations apply normally either way. It is also not
366	/// needed to import a Conduit database or a fork of conduwuit; those are
367	/// recognized by lineage and open without it.
368	///
369	/// This option is extremely dangerous and intended for developer debugging
370	/// and testing only. Never set it unless you have been instructed to do so;
371	/// it may cause permanent damage and permanent loss of data.
372	#[serde(default)]
373	pub force_migration: bool,
374
375	/// Defines named media storage providers.
376	///
377	/// Each map key names a provider, and each value selects a local or
378	/// S3-compatible backend or disables the entry. Provider-specific settings
379	/// live in separate sections.
380	// external structure; separate section
381	#[serde(default)]
382	pub storage_provider: BTreeMap<String, StorageProvider>,
383
384	/// Defines policy documents users must accept during registration.
385	///
386	/// Each map key is the policy identifier exposed in the `m.login.terms` UIA
387	/// stage. An empty map leaves the terms stage disabled.
388	// external structure; separate section
389	#[serde(default)]
390	pub registration_terms: BTreeMap<String, TermsPolicy>,
391
392	/// Configures LDAP login integration.
393	///
394	/// Connection, bind, search, and attribute settings live in the separate
395	/// `[global.ldap]` section. LDAP authentication is disabled by default.
396	// external structure; separate section
397	#[serde(default)]
398	pub ldap: LdapConfig,
399
400	/// Configures JSON Web Token login integration.
401	///
402	/// Key format, algorithm, claim validation, and user provisioning settings
403	/// live in `[global.jwt]`. Token login is disabled by default.
404	// external structure; separate section
405	#[serde(default)]
406	pub jwt: JwtConfig,
407
408	/// Configures outbound SMTP email delivery.
409	///
410	/// Providing a connection URI enables the email subsystem. Registration
411	/// flags determine when a verified address is required.
412	// external structure; separate section
413	#[serde(default)]
414	pub smtp: SmtpConfig,
415
416	/// Defines inline application service registrations.
417	///
418	/// Each map key names one registration and supplies its default identifier.
419	/// The contained settings are converted to Matrix application service data.
420	// external structure; separate section
421	#[serde(default)]
422	pub appservice: BTreeMap<String, AppService>,
423
424	/// Defines OpenID Connect identity provider registrations.
425	///
426	/// Each entry configures client credentials, discovery, and account
427	/// mapping. Its stable `client_id` identifies the provider while `brand`
428	/// selects provider-specific defaults and workarounds.
429	// external structure; separate sections
430	#[serde(default, with = "identity_provider_serde")]
431	pub identity_provider: BTreeMap<String, IdentityProvider>,
432
433	#[serde(flatten)]
434	#[expect(clippy::zero_sized_map_values)]
435	// this is a catchall, the map shouldn't be zero at runtime
436	catchall: BTreeMap<String, IgnoredAny>,
437
438	/// Settings for cache.
439	///
440	/// display: section
441	#[serde(default)]
442	pub cache: Cache,
443
444	/// Settings for database.
445	///
446	/// display: section
447	#[serde(default)]
448	pub database: Database,
449
450	/// Settings for runtime.
451	///
452	/// display: section
453	#[serde(default)]
454	pub runtime: Runtime,
455
456	/// Settings for http.
457	///
458	/// display: section
459	#[serde(default)]
460	pub http: Http,
461
462	/// Settings for network.
463	///
464	/// display: section
465	#[serde(default)]
466	pub network: Network,
467
468	/// Settings for media.
469	///
470	/// display: section
471	#[serde(default)]
472	pub media: Media,
473
474	/// Settings for federation.
475	///
476	/// display: section
477	#[serde(default)]
478	pub federation: Federation,
479
480	/// Settings for rooms.
481	///
482	/// display: section
483	#[serde(default)]
484	pub rooms: Rooms,
485
486	/// Settings for sending.
487	///
488	/// display: section
489	#[serde(default)]
490	pub sending: Sending,
491
492	/// Settings for authentication.
493	///
494	/// display: section
495	#[serde(default)]
496	pub authentication: Authentication,
497
498	/// Settings for directory.
499	///
500	/// display: section
501	#[serde(default)]
502	pub directory: Directory,
503
504	/// Settings for encryption.
505	///
506	/// display: section
507	#[serde(default)]
508	pub encryption: Encryption,
509
510	/// Settings for profile.
511	///
512	/// display: section
513	#[serde(default)]
514	pub profile: Profile,
515
516	/// Settings for registration.
517	///
518	/// display: section
519	#[serde(default)]
520	pub registration: Registration,
521
522	/// Settings for admin.
523	///
524	/// display: section
525	#[serde(default)]
526	pub admin: Admin,
527
528	/// Settings for appservice client.
529	///
530	/// display: section
531	#[serde(default)]
532	pub appservice_client: AppserviceClient,
533
534	/// Settings for client.
535	///
536	/// display: section
537	#[serde(default)]
538	pub client: Client,
539
540	/// Settings for compatibility.
541	///
542	/// display: section
543	#[serde(default)]
544	pub compatibility: Compatibility,
545
546	/// Settings for configuration.
547	///
548	/// display: section
549	#[serde(default)]
550	pub configuration: Configuration,
551
552	/// Settings for logging.
553	///
554	/// display: section
555	#[serde(default)]
556	pub logging: Logging,
557
558	/// Settings for presence.
559	///
560	/// display: section
561	#[serde(default)]
562	pub presence: Presence,
563
564	/// Settings for push.
565	///
566	/// display: section
567	#[serde(default)]
568	pub push: Push,
569
570	/// Settings for read receipts.
571	///
572	/// display: section
573	#[serde(default)]
574	pub read_receipts: ReadReceipts,
575
576	/// Settings for rendezvous.
577	///
578	/// display: section
579	#[serde(default)]
580	pub rendezvous: Rendezvous,
581
582	/// Settings for telemetry.
583	///
584	/// display: section
585	#[serde(default)]
586	pub telemetry: Telemetry,
587
588	/// Settings for tracing.
589	///
590	/// display: section
591	#[serde(default)]
592	pub tracing: Tracing,
593
594	/// Settings for turn.
595	///
596	/// display: section
597	#[serde(default)]
598	pub turn: Turn,
599
600	/// Settings for typing.
601	///
602	/// display: section
603	#[serde(default)]
604	pub typing: Typing,
605}
606
607/// Direct TLS
608///
609/// Lets the server terminate TLS itself. Most deployments leave
610/// `[global.tls]` unset and let a reverse proxy handle HTTPS and
611/// certificates, in which case every TCP listener speaks plain HTTP. Use it
612/// when nothing sits in front of the server, together with a public
613/// `http.listen.address` and the `http.listen.port` values that clients and
614/// other homeservers connect to.
615///
616/// Set `certs` to a PEM file holding the full certificate chain and `key`
617/// to its PEM private key; setting only one of the two fails startup.
618///
619/// Minimal example:
620///
621/// ```toml
622///     [global.tls]
623///     certs = "/etc/tuwunel/tls/fullchain.pem"
624///     key = "/etc/tuwunel/tls/privkey.pem"
625/// ```
626///
627/// Tips:
628/// - TLS covers every TCP listener, including sockets passed by systemd.
629///   One port cannot serve TLS while another serves plain HTTP;
630///   `dual_protocol` makes every port accept both. The Unix socket stays
631///   plain HTTP.
632/// - The files are read once at startup; restart after renewing the
633///   certificate.
634/// - Builds without the `direct_tls` feature (on by default) refuse to start
635///   while `certs` and `key` are set.
636#[derive(Clone, Debug, Deserialize, Default)]
637#[config_example_generator(filename = "tuwunel-example.toml", section = "global.tls")]
638pub struct TlsConfig {
639	/// Path to a valid TLS certificate file; this section requires a build with
640	/// the `direct_tls` Cargo feature.
641	///
642	/// example: "/path/to/my/certificate.crt"
643	pub certs: Option<String>,
644
645	/// Path to a valid TLS certificate private key.
646	///
647	/// example: "/path/to/my/certificate.key"
648	pub key: Option<String>,
649
650	/// Controls whether listeners accept both HTTP and HTTPS.
651	///
652	/// Plain requests are served without redirecting them to HTTPS. This
653	/// weakens transport security and is disabled by default.
654	#[serde(default)]
655	pub dual_protocol: bool,
656}
657
658/// Matrix discovery (well-known) responses
659///
660/// Sets what the server answers at `/.well-known/matrix/client`,
661/// `/.well-known/matrix/server` and `/.well-known/matrix/support`. Clients
662/// and other servers fetch these files over HTTPS from the `server_name`
663/// host, so the settings take effect only when requests for that host reach
664/// the server, directly or through a reverse proxy. An endpoint with nothing
665/// configured answers 404.
666///
667/// Support contacts and policies have their own tables,
668/// `[global.well_known.support_contact.<ID>]` and
669/// `[global.well_known.support_policy.<ID>]`; with `support_page` they make
670/// up `/.well-known/matrix/support`. `livekit_url` publishes the MatrixRTC
671/// (Element Call) backend in the client response.
672///
673/// Example for `example.com` served from `matrix.example.com`:
674///
675/// ```toml
676///     [global.well_known]
677///     client = "https://matrix.example.com"
678///     server = "matrix.example.com:443"
679/// ```
680///
681/// Tips:
682/// - Other features need `client`: startup fails when `smtp.connection_uri`
683///   is set without it, and the built-in OIDC server (any
684///   `[global.identity_provider]` entry or `authentication.oidc.native_auth`)
685///   stays off with a warning.
686#[expect(rustdoc::bare_urls)]
687#[derive(Clone, Debug, Deserialize, Default)]
688#[config_example_generator(
689	filename = "tuwunel-example.toml",
690	section = "global.well_known",
691	ignore = "support_contact support_policy",
692	hidden = "support_role support_email support_mxid support_pgp_key"
693)]
694pub struct WellKnownConfig {
695	/// The server URL that the client well-known file will serve.
696	///
697	/// This should not contain a port, and should just be a valid HTTPS URL.
698	/// While this is unset, `/.well-known/matrix/client` answers 404 and
699	/// auto-discovery from the server name yields nothing, so the base URL has
700	/// to reach clients some other way. Leave it unset only when a reverse
701	/// proxy or another host publishes that file for this domain.
702	///
703	/// example: "https://matrix.example.com"
704	pub client: Option<Url>,
705
706	/// The server base domain of the URL with a specific port that the server
707	/// well-known file will serve. This should contain a port at the end, and
708	/// should not be a URL.
709	///
710	/// reloadable: yes
711	/// example: "matrix.example.com:443"
712	pub server: Option<OwnedServerName>,
713
714	/// Defines contacts published by the support discovery endpoint.
715	///
716	/// Each map value becomes one contact while its key is only a config
717	/// identifier. Legacy scalar support fields are appended separately.
718	// external structure; separate section
719	#[serde(default)]
720	pub support_contact: BTreeMap<String, SupportContact>,
721
722	/// Defines policies published by the support discovery endpoint.
723	///
724	/// Each map key becomes a policy identifier. The value supplies its version
725	/// and localized documents.
726	// external structure; separate section
727	#[serde(default)]
728	pub support_policy: BTreeMap<String, SupportPolicy>,
729
730	/// Publishes a support web page URL at `/.well-known/matrix/support`.
731	///
732	/// It is served beside the support contacts and policies, and any one of
733	/// the three makes the endpoint answer instead of returning 404.
734	///
735	/// reloadable: yes
736	/// example: "https://example.com/support"
737	pub support_page: Option<Url>,
738
739	/// The name of the support role.
740	///
741	///
742	/// display: hidden
743	// This config option is hidden because [global.well_known.support_contact.<ID>] should be
744	// used instead. However for compatibility purposes the config option will still function and
745	// be prioritised first.
746	pub support_role: Option<ContactRole>,
747
748	/// The email address for the above support role.
749	///
750	///
751	/// display: hidden
752	// This config option is hidden because [global.well_known.support_contact.<ID>] should be
753	// used instead. However for compatibility purposes the config option will still function and
754	// be prioritised first.
755	pub support_email: Option<String>,
756
757	/// The Matrix User ID for the above support role.
758	///
759	/// display: hidden
760	// This config option is hidden because [global.well_known.support_contact.<ID>] should be
761	// used instead. However for compatibility purposes the config option will still function and
762	// be prioritised first.
763	pub support_mxid: Option<OwnedUserId>,
764
765	/// The PGP key (i.e. OpenPGP) that one may use for encrypted communications
766	/// for the above support role. The value must be a URI. Use a web URL
767	/// pointing to the key (for example "https://example.com/key.asc"), an
768	/// OPENPGPKEY DNS record ("dns:..."), or a fingerprint carried with the
769	/// "openpgp4fpr:" scheme. A bare fingerprint without a scheme, or raw
770	/// inlined key material, is rejected at startup.
771	///
772	/// As this is a spec proposal (MSC4439), the identifier/prefix for this
773	/// field is currently "dev.zirco.msc4439.pgp_key"
774	///
775	/// display: hidden
776	// This config option is hidden because [global.well_known.support_contact.<ID>] should be
777	// used instead. However for compatibility purposes the config option will still function and
778	// be prioritised first.
779	pub support_pgp_key: Option<String>,
780
781	/// LiveKit JWT endpoint.
782	/// Required for Element Call / MatrixRTC (MSC4143).
783	///
784	/// Note: You must also set `client` above to your homeserver URL.
785	///
786	/// reloadable: yes
787	/// default: ""
788	#[serde(default)]
789	pub livekit_url: Option<String>,
790
791	/// Custom MatrixRTC transports.
792	///
793	/// If you're looking to setup Element Call / MatrixRTC with Livekit,
794	/// you should not use this option and instead set `livekit_url`.
795	/// This is only required if you want to configure a non-livekit MatrixRTC
796	/// transport. There are no known client implementations that support any
797	/// other transport types.
798	///
799	/// This option was previously the only way to configure a Livekit
800	/// transport. It has been superseded by `livekit_url`.
801	///
802	/// Example:
803	/// ```toml
804	/// [global.well_known]
805	/// client = "https://matrix.yourdomain.com"
806	///
807	/// [[global.well_known.rtc_transports]]
808	/// type = "livekit"
809	/// livekit_service_url = "https://livekit.yourdomain.com"
810	/// ```
811	///
812	/// reloadable: yes
813	/// default: []
814	#[serde(default)]
815	pub rtc_transports: Vec<serde_json::Value>,
816}
817
818/// Support policy document
819///
820/// Publishes one policy document, such as a privacy policy or terms of
821/// service, in `/.well-known/matrix/support` (the
822/// `org.matrix.msc4266.policies` field of MSC4266). These are informational;
823/// to make new users accept documents at sign-up, use
824/// `[global.registration_terms.<ID>]`.
825///
826/// - `<ID>`: the policy id published to clients, such as `privacy_policy`.
827///   The id is not validated (the spec allows `0-9 a-z A-Z . _ ~ -`). Bare
828///   keys may use `A-Z a-z 0-9 _ -`; anything else must be quoted
829///   (`[global.well_known.support_policy."privacy.v2"]`), and an unquoted
830///   dot splits the name into nested tables.
831///
832/// `version` and a
833/// `[global.well_known.support_policy.<ID>.policy_translation.<LANG>]`
834/// table are required; a policy table without them fails to load. Give
835/// it at least one language.
836///
837/// Minimal example:
838///
839/// ```toml
840///     [global.well_known.support_policy.privacy_policy]
841///     version = "1.0"
842///
843///     [global.well_known.support_policy.privacy_policy.policy_translation.en]
844///     name = "Privacy Policy"
845///     url = "https://example.com/privacy"
846/// ```
847///
848/// Tips:
849/// - The translation table is `policy_translation` here but `translations`
850///   under `[global.registration_terms.<ID>]`.
851#[derive(Clone, Debug, Deserialize)]
852#[config_example_generator(
853	filename = "tuwunel-example.toml",
854	section = "global.well_known.support_policy.<ID>",
855	ignore = "policy_translation"
856)]
857pub struct SupportPolicy {
858	/// Version string of the policy document.
859	///
860	/// example: "v6.7"
861	/// reloadable: yes
862	pub version: String,
863
864	/// Maps language identifiers to localized policy documents.
865	///
866	/// Each value supplies the display name and URL for its language. The map
867	/// is converted to the response's localized policy entries.
868	// external structure; separate section
869	pub policy_translation: BTreeMap<String, SupportPolicyTranslation>,
870}
871
872/// Support policy translation
873///
874/// One language version of a `[global.well_known.support_policy.<ID>]`
875/// document: the title and link clients show for that language. Add one
876/// table per language; `name` and `url` are both required.
877///
878/// - `<ID>`: the `<ID>` of the policy table this translation belongs to,
879///   spelled (and quoted) the same way.
880/// - `<LANG>`: the language code, such as `en`, `fr` or `en-US` (RFC 5646;
881///   some clients use `en_US`). It is published as the key for this
882///   translation next to the policy's `version`, so it must not be
883///   `version`; it is not validated otherwise. Bare keys may use
884///   `A-Z a-z 0-9 _ -`; anything else must be quoted, and an unquoted dot
885///   splits the name into nested tables.
886///
887/// Example:
888///
889/// ```toml
890///     [global.well_known.support_policy.privacy_policy.policy_translation.de]
891///     name = "Datenschutzrichtlinie"
892///     url = "https://example.com/privacy-de"
893/// ```
894#[derive(Clone, Debug, Deserialize)]
895#[config_example_generator(
896	filename = "tuwunel-example.toml",
897	section = "global.well_known.support_policy.<ID>.policy_translation.<LANG>"
898)]
899pub struct SupportPolicyTranslation {
900	/// User friendly name of the policy document.
901	///
902	/// example: "Privacy Policy"
903	/// reloadable: yes
904	pub name: String,
905
906	/// Link to the test of the policy document. A valid URL must be specified.
907	///
908	/// example: "https://website.local/privacy-policy"
909	/// reloadable: yes
910	pub url: Url,
911}
912
913/// Registration terms
914///
915/// Requires new users to accept policy documents, such as terms of service
916/// or a privacy policy, when they register. Each table adds one document to
917/// the `m.login.terms` stage of registration and to the built-in sign-up
918/// page (`authentication.oidc.native_auth`). With none configured,
919/// registration has no terms stage.
920///
921/// - `<ID>`: the policy id sent to clients, such as `terms_of_service`.
922///   Checked at startup: 1 to 255 characters from `0-9 a-z A-Z . _ ~ -`.
923///   Bare keys may use `A-Z a-z 0-9 _ -`, so an id with `.` or `~` must be
924///   quoted (`[global.registration_terms."tos.v2"]`); an unquoted dot
925///   splits the name into nested tables.
926///
927/// `version` and a `[global.registration_terms.<ID>.translations.<LANG>]`
928/// table are required; give it at least one language.
929///
930/// Minimal example:
931///
932/// ```toml
933///     [global.registration_terms.terms_of_service]
934///     version = "1.0"
935///
936///     [global.registration_terms.terms_of_service.translations.en]
937///     name = "Terms of Service"
938///     url = "https://example.com/terms"
939/// ```
940///
941/// Tips:
942/// - A terms stage does not satisfy the open-registration startup check:
943///   `registration.enable` still needs a registration token or a required
944///   email stage.
945/// - Only new accounts see the terms (appservice and guest registrations
946///   skip them); changing `version` does not ask existing users again.
947#[derive(Clone, Debug, Deserialize)]
948#[config_example_generator(
949	filename = "tuwunel-example.toml",
950	section = "global.registration_terms.<ID>",
951	ignore = "translations"
952)]
953pub struct TermsPolicy {
954	/// Version of this policy document, presented to the client. Configuring
955	/// any `[global.registration_terms.<ID>]` block makes registration
956	/// require an `m.login.terms` stage listing every such document; the
957	/// `<ID>` is the policy id sent to clients.
958	///
959	/// example: "1.2"
960	/// reloadable: yes
961	pub version: String,
962
963	/// Maps language identifiers to localized registration policy documents.
964	///
965	/// Each value supplies the display name and HTTP or HTTPS URL for its
966	/// language. These translations are presented in the terms stage.
967	// external structure; separate section
968	pub translations: BTreeMap<String, TermsPolicyTranslation>,
969}
970
971/// Registration terms translation
972///
973/// One language version of a `[global.registration_terms.<ID>]` document:
974/// the title and link shown for that language. Every translation's `url`
975/// is recorded as accepted in the new account's `m.accepted_terms` account
976/// data.
977///
978/// - `<ID>`: the `<ID>` of the policy table this translation belongs to,
979///   spelled (and quoted) the same way.
980/// - `<LANG>`: the language code, such as `en`, `fr` or `en-US` (RFC 5646;
981///   some clients use `en_US`). It is sent as the key for this translation
982///   next to the policy's `version`, so it must not be `version`; it is not
983///   validated otherwise. Bare keys may use `A-Z a-z 0-9 _ -`; anything
984///   else must be quoted, and an unquoted dot splits the name into nested
985///   tables.
986///
987/// `name` and `url` are required; a `url` whose scheme is not `http` or
988/// `https` fails the startup check.
989///
990/// Tips:
991/// - The built-in sign-up page (`authentication.oidc.native_auth`) links
992///   one translation per policy: `en` when present, otherwise the first
993///   `<LANG>` in sort order.
994#[derive(Clone, Debug, Deserialize)]
995#[config_example_generator(
996	filename = "tuwunel-example.toml",
997	section = "global.registration_terms.<ID>.translations.<LANG>"
998)]
999pub struct TermsPolicyTranslation {
1000	/// User friendly name of the policy document in this language.
1001	///
1002	/// example: "Terms of Service"
1003	/// reloadable: yes
1004	pub name: String,
1005
1006	/// Link to the text of the policy document. Must be a valid http(s) URL.
1007	///
1008	/// example: "https://example.org/terms-1.2-en.html"
1009	/// reloadable: yes
1010	pub url: Url,
1011}
1012
1013impl From<SupportPolicyTranslation>
1014	for ruma::api::identity_service::tos::get_terms_of_service::v2::LocalizedPolicy
1015{
1016	fn from(conf: SupportPolicyTranslation) -> Self {
1017		Self {
1018			name: conf.name,
1019			url: conf.url.to_string(),
1020		}
1021	}
1022}
1023
1024/// Support contact
1025///
1026/// Publishes one contact in the `contacts` list of
1027/// `/.well-known/matrix/support`, where users and other server admins look
1028/// for someone to reach. With no contact, `support_page` or support policy
1029/// configured, the endpoint answers 404.
1030///
1031/// - `<ID>`: your label for this contact. It is not published; contacts
1032///   are listed in `<ID>` order, and startup errors name the entry by it.
1033///   Bare keys may use `A-Z a-z 0-9 _ -`; anything else must be quoted
1034///   (`[global.well_known.support_contact."ops.team"]`), and an unquoted
1035///   dot splits the name into nested tables.
1036///
1037/// `role` is required, normally `m.role.admin` or `m.role.security`;
1038/// `m.role.moderator` and `m.role.dpo` are accepted but published under
1039/// their unstable MSC4121 and MSC4265 names. Startup fails unless at least
1040/// one of `email_address` or `matrix_id` is set.
1041///
1042/// Example:
1043///
1044/// ```toml
1045///     [global.well_known.support_contact.admin]
1046///     role = "m.role.admin"
1047///     email_address = "admin@example.com"
1048///     matrix_id = "@admin:example.com"
1049/// ```
1050#[derive(Clone, Debug, Deserialize)]
1051#[config_example_generator(
1052	filename = "tuwunel-example.toml",
1053	section = "global.well_known.support_contact.<ID>"
1054)]
1055pub struct SupportContact {
1056	/// The name of the support role.
1057	///
1058	/// example: "m.role.admin"
1059	pub role: ContactRole,
1060
1061	/// The email address for the above support role.
1062	///
1063	/// example: "admin@example.com"
1064	pub email_address: Option<String>,
1065
1066	/// The Matrix User ID for the above support role.
1067	///
1068	/// example: "@admin:example.com"
1069	pub matrix_id: Option<OwnedUserId>,
1070
1071	/// The PGP key (i.e. OpenPGP) that one may use for encrypted communications
1072	/// for the above support role. The value must be a URI. Use a web URL
1073	/// pointing to the key (for example "https://example.com/key.asc"), an
1074	/// OPENPGPKEY DNS record ("dns:..."), or a fingerprint carried with the
1075	/// "openpgp4fpr:" scheme. A bare fingerprint without a scheme, or raw
1076	/// inlined key material, is rejected at startup.
1077	///
1078	/// As this is a spec proposal (MSC4439), the identifier/prefix for this
1079	/// field is currently "dev.zirco.msc4439.pgp_key"
1080	///
1081	/// example: "openpgp4fpr:8B77919975EAFA5E2456EE03665FE73077489DB0"
1082	pub pgp_key: Option<String>,
1083}
1084
1085impl From<SupportContact> for ruma::api::client::discovery::discover_support::Contact {
1086	fn from(conf: SupportContact) -> Self {
1087		Self {
1088			role: conf.role,
1089			matrix_id: conf.matrix_id,
1090			email_address: conf.email_address,
1091			pgp_key: conf.pgp_key,
1092		}
1093	}
1094}
1095
1096/// LDAP login
1097///
1098/// Checks password sign-ins against an LDAP directory and creates the local
1099/// account on first successful bind, regardless of `registration.enable`.
1100/// Off by default; needs the `ldap` build feature, which the default build
1101/// includes.
1102///
1103/// Set `enable` and `uri`. With both `bind_dn` and `bind_password_file`,
1104/// the server binds as that service account, then searches `base_dn` with
1105/// `filter`; leaving either unset searches anonymously. A `bind_dn`
1106/// containing `{username}` skips the search and binds directly as the user.
1107///
1108/// Minimal example (search with a service account):
1109///
1110/// ```toml
1111///     [global.ldap]
1112///     enable = true
1113///     uri = "ldaps://ldap.example.org:636"
1114///     base_dn = "ou=users,dc=example,dc=org"
1115///     bind_dn = "cn=ldap-reader,dc=example,dc=org"
1116///     bind_password_file = "/etc/tuwunel/.ldap_bind_password"
1117/// ```
1118///
1119/// Tips:
1120/// - A search with no match falls back to the local password, and two or
1121///   more matches refuse the login. Direct bind never falls back, and with a
1122///   nonempty `admin_filter` it revokes admin from every user who signs in.
1123/// - `authentication.login.with_password = false` turns LDAP login off, and
1124///   `authentication.emergency_password` is ignored while LDAP is enabled.
1125/// - Only `uri` is checked at startup, and only that it parses as a URL: a
1126///   missing `uri` or an unreachable directory shows up as failed logins.
1127#[derive(Clone, Debug, Default, Deserialize)]
1128#[config_example_generator(filename = "tuwunel-example.toml", section = "global.ldap")]
1129pub struct LdapConfig {
1130	/// Whether to enable LDAP login.
1131	///
1132	/// reloadable: yes
1133	/// example: "true"
1134	#[serde(default)]
1135	pub enable: bool,
1136
1137	/// URI of the LDAP server.
1138	///
1139	/// reloadable: yes
1140	/// example: "ldap://ldap.example.com:389"
1141	pub uri: Option<Url>,
1142
1143	/// Root of the searches.
1144	///
1145	/// reloadable: yes
1146	/// example: "ou=users,dc=example,dc=org"
1147	///
1148	/// default:
1149	#[serde(default)]
1150	pub base_dn: String,
1151
1152	/// Bind DN if anonymous search is not enabled.
1153	///
1154	/// You can use the variable `{username}` that will be replaced by the
1155	/// entered username. In such case, the password used to bind will be the
1156	/// one provided for the login and not the one given by
1157	/// `bind_password_file`. Beware: automatically granting admin rights will
1158	/// not work if you use this direct bind instead of a LDAP search.
1159	///
1160	/// reloadable: yes
1161	/// example: "cn=ldap-reader,dc=example,dc=org" or
1162	/// "cn={username},ou=users,dc=example,dc=org"
1163	///
1164	/// default: ""
1165	#[serde(default)]
1166	pub bind_dn: Option<String>,
1167
1168	/// Path to a file on the system that contains the password for the
1169	/// `bind_dn`.
1170	///
1171	/// The server must be able to access the file, and it must not be empty.
1172	///
1173	/// reloadable: yes
1174	/// default: ""
1175	#[serde(default)]
1176	pub bind_password_file: Option<PathBuf>,
1177
1178	/// Search filter to limit user searches.
1179	///
1180	/// You can use the variable `{username}` that will be replaced by the
1181	/// entered username for more complex filters.
1182	///
1183	/// reloadable: yes
1184	/// example: "(&(objectClass=person)(memberOf=matrix))"
1185	///
1186	/// default: "(objectClass=*)"
1187	#[serde(default = "default_ldap_search_filter")]
1188	pub filter: String,
1189
1190	/// Attribute to use to uniquely identify the user.
1191	///
1192	/// reloadable: yes
1193	/// example: "uid" or "cn"
1194	///
1195	/// default: "uid"
1196	#[serde(default = "default_ldap_uid_attribute")]
1197	pub uid_attribute: String,
1198
1199	/// Root of the searches for admin users.
1200	///
1201	/// Defaults to `base_dn` if empty.
1202	///
1203	/// reloadable: yes
1204	/// example: "ou=admins,dc=example,dc=org"
1205	///
1206	/// default:
1207	#[serde(default)]
1208	pub admin_base_dn: String,
1209
1210	/// The LDAP search filter to find administrative users for tuwunel.
1211	///
1212	/// If left blank, administrative state must be configured manually for each
1213	/// user.
1214	///
1215	/// You can use the variable `{username}` that will be replaced by the
1216	/// entered username for more complex filters.
1217	///
1218	/// reloadable: yes
1219	/// example: "(objectClass=tuwunelAdmin)" or "(uid={username})"
1220	///
1221	/// default:
1222	#[serde(default)]
1223	pub admin_filter: String,
1224}
1225
1226/// JSON Web Token login
1227///
1228/// Accepts a signed JWT as proof of identity, both as the
1229/// `org.matrix.login.jwt` login type and as a user-interactive
1230/// authentication stage, for deployments where an external system mints
1231/// tokens for its users. The token's `sub` claim is the user's localpart on
1232/// this server, lowercased. Off by default.
1233///
1234/// Set `enable` and `key`. The default `format` and `algorithm` expect an
1235/// HMAC shared secret with HS256; an issuer signing with ECDSA or EdDSA needs
1236/// its PEM public key in `key` and a matching `format` and `algorithm`.
1237///
1238/// Minimal example:
1239///
1240/// ```toml
1241///     [global.jwt]
1242///     enable = true
1243///     key = "replace-with-a-long-random-secret"
1244/// ```
1245///
1246/// Tips:
1247/// - Startup and reload refuse an empty `key` or an unknown `format` while
1248///   enabled, but a `key` that does not decode or an unsuitable `algorithm`
1249///   fails only at login.
1250/// - With `register_user` (the default), a valid token for an unknown user
1251///   creates the account regardless of `registration.enable`.
1252/// - `validate_signature = false` has an effect only in debug builds.
1253#[derive(Clone, Debug, Default, Deserialize)]
1254#[config_example_generator(filename = "tuwunel-example.toml", section = "global.jwt")]
1255pub struct JwtConfig {
1256	/// Enable JWT logins
1257	///
1258	/// reloadable: yes
1259	/// default: false
1260	#[serde(default)]
1261	pub enable: bool,
1262
1263	/// Validation key, also called 'secret' in Synapse config. The type of key
1264	/// can be configured in 'format', but defaults to the common HMAC which
1265	/// is a plaintext shared-secret, so you should keep this value private.
1266	///
1267	/// display: sensitive
1268	/// reloadable: yes
1269	/// default:
1270	#[debug("{}", redacted_debug!(str key))]
1271	#[serde(default, alias = "secret")]
1272	pub key: String,
1273
1274	/// Format of the 'key': HMAC, B64HMAC, ECDSA, or EDDSA, case-insensitive.
1275	///
1276	/// HMAC is a plaintext shared secret, and B64HMAC (also spelled HMACB64)
1277	/// is the same secret base64-encoded in the standard alphabet with '='
1278	/// padding, for random binary secrets that cannot be pasted as text.
1279	/// ECDSA and EDDSA are PEM-encoded public keys, EDDSA for Ed25519.
1280	/// Startup and reload both refuse an unknown format while JWT is enabled.
1281	///
1282	/// reloadable: yes
1283	/// default: "HMAC"
1284	#[serde(default = "default_jwt_format")]
1285	pub format: String,
1286
1287	/// Automatically create new user from a valid claim, otherwise access is
1288	/// denied for an unknown even with an authentic token.
1289	///
1290	/// reloadable: yes
1291	/// default: true
1292	#[serde(default = "true_fn")]
1293	pub register_user: bool,
1294
1295	/// Expire the access token of a new JWT login and withhold a refresh token.
1296	///
1297	/// The access token lasts `authentication.access_token_ttl` seconds
1298	/// whatever the client asks for, so staying signed in takes a fresh JWT and
1299	/// the token issuer decides how long a login lasts. Off by default because
1300	/// a client that cannot obtain a fresh JWT would be signed out for good.
1301	/// A JWT login retires the refresh token its device holds, but a client
1302	/// that only refreshes never logs in, so remove devices holding a refresh
1303	/// token when enabling this. Startup and reload refuse a zero
1304	/// `authentication.access_token_ttl` while enabled.
1305	///
1306	/// reloadable: yes
1307	/// default: false
1308	#[serde(default)]
1309	pub expire_access_token: bool,
1310
1311	/// Signature algorithm for validating tokens.
1312	///
1313	/// The name must suit the key format: HS256, HS384, or HS512 for HMAC
1314	/// and B64HMAC, ES256 or ES384 for ECDSA, and EdDSA for EDDSA.
1315	///
1316	/// reloadable: yes
1317	/// default: "HS256"
1318	#[serde(default = "default_jwt_algorithm")]
1319	pub algorithm: String,
1320
1321	/// Optional audience claim list. The token must claim one or more values
1322	/// from this list when set.
1323	///
1324	/// reloadable: yes
1325	/// default: []
1326	#[serde(default)]
1327	pub audience: Vec<String>,
1328
1329	/// Optional issuer claim list. The token must claim one or more values
1330	/// from this list when set.
1331	///
1332	/// reloadable: yes
1333	/// default: []
1334	#[serde(default)]
1335	pub issuer: Vec<String>,
1336
1337	/// Require expiration claim in the token. This defaults to false for
1338	/// synapse migration compatibility.
1339	///
1340	/// reloadable: yes
1341	/// default: false
1342	#[serde(default)]
1343	pub require_exp: bool,
1344
1345	/// Require not-before claim in the token. This defaults to false for
1346	/// synapse migration compatibility.
1347	///
1348	/// reloadable: yes
1349	/// default: false
1350	#[serde(default)]
1351	pub require_nbf: bool,
1352
1353	/// Validate expiration time of the token when present. Whether or not it is
1354	/// required depends on require_exp, but when present this ensures the token
1355	/// is not used after a time.
1356	///
1357	/// reloadable: yes
1358	/// default: true
1359	#[serde(default = "true_fn")]
1360	pub validate_exp: bool,
1361
1362	/// Validate not-before time of the token when present. Whether or not it is
1363	/// required depends on require_nbf, but when present this ensures the token
1364	/// is not used before a time.
1365	///
1366	/// reloadable: yes
1367	/// default: true
1368	#[serde(default = "true_fn")]
1369	pub validate_nbf: bool,
1370
1371	/// Bypass validation for diagnostic/debug use only.
1372	///
1373	/// reloadable: yes
1374	/// default: true
1375	#[serde(default = "true_fn")]
1376	pub validate_signature: bool,
1377}
1378
1379/// Rate limits
1380///
1381/// Groups request rate limits by kind of request. It holds
1382/// `[global.rate_limiting.login]` for password sign-in; the built-in OIDC
1383/// endpoints have a separate per-IP throttle,
1384/// `authentication.oidc.rc_per_second`.
1385#[derive(Clone, Copy, Debug, Default, Deserialize)]
1386#[config_example_generator(
1387	filename = "tuwunel-example.toml",
1388	section = "global.rate_limiting",
1389	ignore = "login"
1390)]
1391pub struct RateLimits {
1392	/// Limits password sign-in per account, in the `failed` and `account`
1393	/// subsections.
1394	// external structure; separate section
1395	#[serde(default)]
1396	pub login: LoginRateLimits,
1397}
1398
1399/// Password sign-in limits
1400///
1401/// Three token buckets guard password checks, each in its own sub-section:
1402/// `[global.rate_limiting.login.failed]` counts wrong passwords per account
1403/// and client address, `[global.rate_limiting.login.address]` counts every
1404/// attempt per client address across accounts, and
1405/// `[global.rate_limiting.login.account]` counts successful sign-ins per
1406/// account from any address. They cover `m.login.password` at `/login` and
1407/// the built-in OIDC login page. Password re-entry for sensitive actions
1408/// (UIAA) has its own `failed` and `address` buckets with the same settings
1409/// and no `account` limit. A refused attempt gets `M_LIMIT_EXCEEDED`.
1410///
1411/// Tips:
1412/// - Behind a reverse proxy, set `http.ip_source` to the header it writes.
1413///   Without it, password checks use the TCP peer address: a proxy on the
1414///   same host (or the Unix socket) gets no per-address limit, and every
1415///   user behind a proxy on another host shares one address.
1416/// - Sign-ins that `[global.ldap]` decides by binding to the directory are
1417///   not counted; its fallback to the local password is.
1418/// - Buckets are kept in memory and reset on restart.
1419#[derive(Clone, Copy, Debug, Default, Deserialize)]
1420#[config_example_generator(
1421	filename = "tuwunel-example.toml",
1422	section = "global.rate_limiting.login",
1423	ignore = "failed account address"
1424)]
1425pub struct LoginRateLimits {
1426	/// Limits wrong passwords against one account from one client address.
1427	// external structure; separate section
1428	#[serde(default)]
1429	pub failed: LoginFailedRateLimit,
1430
1431	/// Limits successful sign-ins to one account.
1432	// external structure; separate section
1433	#[serde(default)]
1434	pub account: LoginAccountRateLimit,
1435
1436	/// Limits password attempts across accounts from one client address.
1437	// external structure; separate section
1438	#[serde(default)]
1439	pub address: LoginAddressRateLimit,
1440}
1441
1442/// Wrong-password limit
1443///
1444/// Throttles password guessing against one account from one client address.
1445/// Only wrong passwords, including names that match no account, use up the
1446/// allowance: `burst_count` at once, then one more every 1/`per_second`
1447/// seconds. Other addresses keep their own allowance for the same account.
1448#[derive(Clone, Copy, Debug, Deserialize)]
1449#[config_example_generator(
1450	filename = "tuwunel-example.toml",
1451	section = "global.rate_limiting.login.failed"
1452)]
1453pub struct LoginFailedRateLimit {
1454	/// Token-bucket refill rate for wrong passwords per account and client
1455	/// address.
1456	///
1457	/// Every attempt reserves a token before verification; a correct password
1458	/// returns it, while a wrong password keeps it.
1459	/// An empty bucket refuses even a correct password from that address,
1460	/// without blocking the account from other addresses.
1461	/// IPv6 addresses share a bucket within each /64, and authenticated
1462	/// password re-entry (UIAA) uses separate buckets from public login.
1463	///
1464	/// `0` disables this limit rather than making a bucket that never refills.
1465	///
1466	/// reloadable: yes
1467	/// default: 0.17
1468	#[serde(default = "default_login_failed_per_second")]
1469	pub per_second: f64,
1470
1471	/// Token-bucket depth for wrong passwords per account and client address.
1472	///
1473	/// The number of failures allowed before `per_second` governs.
1474	/// `0` disables this limit, as does a `0` rate.
1475	///
1476	/// reloadable: yes
1477	/// default: 3
1478	#[serde(default = "default_login_failed_burst_count")]
1479	pub burst_count: u32,
1480}
1481
1482/// Per-address attempt limit
1483///
1484/// Caps all password attempts from one client address across every account,
1485/// successful or not, bounding password spraying and hashing work:
1486/// `burst_count` attempts at once, then one more every 1/`per_second`
1487/// seconds. Clients behind one NAT, one IPv6 /64, or a reverse proxy on
1488/// another host share a budget unless `http.ip_source` names a forwarding
1489/// header. Without one, a loopback peer (a local proxy or the Unix
1490/// socket) is not limited per address.
1491#[derive(Clone, Copy, Debug, Deserialize)]
1492#[config_example_generator(
1493	filename = "tuwunel-example.toml",
1494	section = "global.rate_limiting.login.address"
1495)]
1496pub struct LoginAddressRateLimit {
1497	/// Token-bucket refill rate for password attempts per client address.
1498	///
1499	/// IPv6 addresses share a bucket within each /64; clients behind a shared
1500	/// address share its allowance.
1501	/// Public login and authenticated password re-entry use separate buckets.
1502	/// Unless `http.ip_source` names a forwarding header, a loopback peer such
1503	/// as a local proxy or the Unix socket is not limited per address; configure
1504	/// trusted forwarding behind a proxy to limit its clients by address.
1505	///
1506	/// `0` disables this limit rather than making a bucket that never refills.
1507	///
1508	/// reloadable: yes
1509	/// default: 1.0
1510	#[serde(default = "default_login_address_per_second")]
1511	pub per_second: f64,
1512
1513	/// Token-bucket depth for password attempts per client address.
1514	///
1515	/// The number of attempts allowed before `per_second` governs.
1516	/// `0` disables this limit, as does a `0` rate.
1517	///
1518	/// reloadable: yes
1519	/// default: 20
1520	#[serde(default = "default_login_address_burst_count")]
1521	pub burst_count: u32,
1522}
1523
1524/// Successful sign-in limit
1525///
1526/// Caps how often one account can sign in with a correct password, from any
1527/// address: `burst_count` sign-ins at once, then one more every
1528/// 1/`per_second` seconds. Wrong passwords never count, so guessing cannot
1529/// lock the owner out on this axis. A script that logs in repeatedly can
1530/// reach the default limit.
1531#[derive(Clone, Copy, Debug, Deserialize)]
1532#[config_example_generator(
1533	filename = "tuwunel-example.toml",
1534	section = "global.rate_limiting.login.account"
1535)]
1536pub struct LoginAccountRateLimit {
1537	/// Token-bucket refill rate (sign-ins per second) for successful password
1538	/// logins to one account.
1539	///
1540	/// Applies to `/login` with `m.login.password` (but not to the LDAP binds it
1541	/// makes) and to the built-in OIDC login page, keyed on the account rather
1542	/// than the client IP. Mirrors Synapse's `rc_login.account` and its default
1543	/// of `burst_count` sign-ins, then about one every five and a half minutes;
1544	/// once those are used up, a correct password is refused with
1545	/// `M_LIMIT_EXCEEDED`.
1546	///
1547	/// `0` disables this limit rather than making a bucket that never refills.
1548	///
1549	/// reloadable: yes
1550	/// default: 0.003
1551	#[serde(default = "default_login_account_per_second")]
1552	pub per_second: f64,
1553
1554	/// Token-bucket depth (burst size) for successful password logins to one
1555	/// account.
1556	///
1557	/// The number of sign-ins allowed before `per_second` governs. `0` disables
1558	/// this limit, as does a `0` rate. The default is Synapse's
1559	/// `rc_login.account.burst_count`.
1560	///
1561	/// reloadable: yes
1562	/// default: 5
1563	#[serde(default = "default_login_account_burst_count")]
1564	pub burst_count: u32,
1565}
1566
1567/// Outbound email (SMTP)
1568///
1569/// Sends verification mail so users can prove they own an email address:
1570/// at registration, when adding an address, and for password reset. With
1571/// no `connection_uri`, no mail is sent and those requests are refused.
1572///
1573/// `connection_uri` needs `sender` and `well_known.client` (verification
1574/// links point there), and the `require_email_*` keys need `connection_uri`;
1575/// otherwise startup fails.
1576///
1577/// Minimal example:
1578///
1579/// ```toml
1580///     [global.well_known]
1581///     client = "https://matrix.example.com"
1582///
1583///     [global.smtp]
1584///     connection_uri = "smtps://user:pass@mail.example.com:465"
1585///     sender = "Example <noreply@example.com>"
1586/// ```
1587///
1588/// Tips:
1589/// - `require_email_for_registration` with `connection_uri` adds a
1590///   verified-email stage to registration, which startup accepts in place
1591///   of the registration token that `registration.enable` otherwise needs.
1592/// - Verification links open `/_tuwunel/3pid/email/validate` under
1593///   `well_known.client`; the reverse proxy must forward that path.
1594/// - The built-in OIDC sign-up page cannot collect an email address, so it
1595///   refuses registration while an email is required.
1596#[derive(Clone, Debug, Default, Deserialize)]
1597#[config_example_generator(filename = "tuwunel-example.toml", section = "global.smtp")]
1598pub struct SmtpConfig {
1599	/// Connection URL for the outbound SMTP relay used to send email
1600	/// verification messages. Setting this enables the email subsystem;
1601	/// without it no mail is sent.
1602	///
1603	/// Use a `smtp://` URL for an unencrypted or STARTTLS connection and a
1604	/// `smtps://` URL for implicit TLS. Credentials and the host go inline:
1605	/// `smtps://user:pass@host:port`. The port defaults per scheme when
1606	/// omitted.
1607	///
1608	/// The userinfo component is URL-encoded, so an `@` inside the username
1609	/// must be written as `%40` (for example a login of `bot@example.com`
1610	/// becomes `smtps://bot%40example.com:pass@host:465`). Other reserved
1611	/// characters in the username or password are percent-encoded the same
1612	/// way.
1613	///
1614	/// display: uri-userinfo
1615	/// example: "smtps://user:pass@mail.example.com:465"
1616	pub connection_uri: Option<String>,
1617
1618	/// The mailbox that outbound verification messages are sent from. Accepts
1619	/// either a bare address or a display-name form.
1620	///
1621	/// example: "Example <noreply@example.com>"
1622	pub sender: Option<String>,
1623
1624	/// Rejects email domains matching these regular expressions during native
1625	/// registration and self-service email addition.
1626	///
1627	/// SSO registration and email addresses supplied by identity providers are
1628	/// exempt.
1629	///
1630	/// Patterns match only the canonical domain: lowercase with `ß` expanded to
1631	/// `ss`, without changing plus-addressing or dots. Anchor patterns to match
1632	/// whole domains, for example `^example[.]com$` or `(^|[.])example[.]com$`
1633	/// to include subdomains; an empty list imposes no domain exclusions.
1634	/// Existing bindings and password resets remain usable, while previously
1635	/// verified addresses are checked again before native registration or
1636	/// self-service addition.
1637	///
1638	/// reloadable: yes
1639	/// default: []
1640	#[serde(default, with = "serde_regex")]
1641	pub forbidden_email_domains: RegexSet,
1642
1643	/// Require a verified email address to complete registration. When set,
1644	/// the registration flow does not finish until the user proves control of
1645	/// an email address.
1646	///
1647	/// default: false
1648	#[serde(default)]
1649	pub require_email_for_registration: bool,
1650
1651	/// Require a verified email address when registering with a registration
1652	/// token. When set, token-based registration also demands a verified
1653	/// email address.
1654	///
1655	/// default: false
1656	#[serde(default)]
1657	pub require_email_for_token_registration: bool,
1658}
1659
1660/// Upstream identity providers (SSO)
1661///
1662/// Delegates sign-in to external OAuth 2.0 or OpenID Connect providers;
1663/// repeat the `[[global.identity_provider]]` header once per provider. Both
1664/// legacy `m.login.sso` and the built-in OIDC server
1665/// (`[global.authentication.oidc]`) sign users in through these entries.
1666///
1667/// Each entry needs `brand`, a unique `client_id`, and `client_secret` or
1668/// a readable, nonempty `client_secret_file`; startup refuses a repeated
1669/// `client_id`, a provider with neither secret key, and an unreadable or
1670/// empty `client_secret_file`. `issuer_url` is
1671/// required except for the `github`, `gitlab` and `google` brands.
1672/// Register `well_known.client` followed by
1673/// `/_matrix/client/unstable/login/sso/callback/<client_id>` as the redirect
1674/// URI at the provider; it is the default `callback_url`, so set that
1675/// yourself when `well_known.client` is unset.
1676///
1677/// Minimal example:
1678///
1679/// ```toml
1680///     [[global.identity_provider]]
1681///     brand = "keycloak"
1682///     client_id = "tuwunel"
1683///     client_secret_file = "/etc/tuwunel/.client_secret"
1684///     issuer_url = "https://sso.example.com/realms/example"
1685/// ```
1686///
1687/// Tips:
1688/// - With several providers, mark one `default = true`; otherwise the first
1689///   entry serves the bare SSO redirect, and startup warns unless
1690///   `authentication.login.sso_custom_providers_page` is set.
1691/// - Discovery runs on first use, not at startup: a missing `issuer_url`, or
1692///   one that differs from the issuer the provider reports, fails sign-in.
1693/// - New accounts from a provider follow its `registration` key, not
1694///   `registration.enable`.
1695#[derive(Clone, Debug, Deserialize)]
1696#[config_example_generator(
1697	filename = "tuwunel-example.toml",
1698	section = "[global.identity_provider]"
1699)]
1700pub struct IdentityProvider {
1701	/// The brand-name of the service (e.g. Apple, Facebook, GitHub, GitLab,
1702	/// Google) or the software (e.g. keycloak, MAS) providing the identity.
1703	/// When a brand is recognized we apply certain defaults to this config
1704	/// for your convenience. For certain brands we apply essential internal
1705	/// workarounds specific to that provider; it is important to configure this
1706	/// field properly when a provider needs to be recognized (like GitHub for
1707	/// example).
1708	///
1709	/// Several configured providers can share the same brand name. It is not
1710	/// case-sensitive. As a convenience for common simple deployments we can
1711	/// identify this provider by brand in addition to the unique `client_id` if
1712	/// and only if there is a single provider for the brand; see notes for
1713	/// `client_id`.
1714	#[serde(deserialize_with = "utils::string::de::to_lowercase")]
1715	pub brand: String,
1716
1717	/// The ID of your OAuth application which the provider generates upon
1718	/// registration. This ID then uniquely identifies this configuration
1719	/// instance itself, becoming the identity provider's ID and must be unique
1720	/// and remain unchanged.
1721	///
1722	/// As a convenience we also identify this config by `brand` if and only if
1723	/// there is a single provider configured for a `brand`. Note carefully that
1724	/// multiple providers configured with the same `brand` is not an error and
1725	/// this provider will simply not be found when querying by `brand`.
1726	pub client_id: String,
1727
1728	/// Secret key the provider generated for you along with the `client_id`
1729	/// above. Unlike the `client_id`, the `client_secret` can be changed here
1730	/// whenever the provider regenerates one for you.
1731	///
1732	/// display: sensitive
1733	#[debug("{}", redacted_debug!(client_secret))]
1734	pub client_secret: Option<String>,
1735
1736	/// Secret key to use, read from the file path specified.
1737	///
1738	/// Alternative to `client_secret` for deployments that prefer to keep the
1739	/// secret outside the config file. When both are configured `client_secret`
1740	/// is used and this field is ignored. The file is read at startup and on
1741	/// each OAuth exchange, must exist and must be non-empty; leading and
1742	/// trailing whitespace is trimmed. Under systemd the path must be visible
1743	/// to the service after sandboxing (`ReadWritePaths` / `ProtectHome`),
1744	/// typically by placing the file under `/etc/tuwunel/`.
1745	///
1746	/// example: "/etc/tuwunel/.client_secret"
1747	pub client_secret_file: Option<PathBuf>,
1748
1749	/// Issuer URL the provider publishes for you. We have pre-supplied default
1750	/// values for some of the canonical public providers, making this field
1751	/// optional based on the `brand` set above. Otherwise it is required to
1752	/// find self-hosted providers. It must be identical to what is configured
1753	/// and expected by the provider and must never change because we associate
1754	/// identities to it. If the `/.well-known/openid-configuration` is not
1755	/// found behind this URL see `base_path` below as a workaround.
1756	pub issuer_url: Option<Url>,
1757
1758	/// The callback URL configured when registering the OAuth application with
1759	/// the provider. Tuwunel's callback URL must be strictly formatted exactly
1760	/// as instructed. The URL host must point directly at the matrix server and
1761	/// use the following path:
1762	/// `/_matrix/client/unstable/login/sso/callback/<client_id>` where
1763	/// `<client_id>` is the same one configured for this provider above.
1764	pub callback_url: Option<Url>,
1765
1766	/// When more than one identity_provider has been configured and
1767	/// `authentication.login.single_sso` is false and
1768	/// `authentication.login.sso_custom_providers_page` is false this will
1769	/// determine the behavior of the `/_matrix/client/v3/login/sso/redirect`
1770	/// endpoint (note the url lacks a trailing `client_id`).
1771	///
1772	/// When only one identity_provider is configured it will be interpreted
1773	/// as the default and this does not need to be set. Otherwise a default
1774	/// *must* be selected for some clients (e.g. fluffychat) to work properly
1775	/// when the above conditions require it. To operate out-of-the-box we
1776	/// default to one configured provider if none are explicitly default; a
1777	/// warning will be logged on startup for this condition.
1778	///
1779	/// (EXPERIMENTAL) Multiple providers can be set to default. All providers
1780	/// configured with this option set to `true` will associate with the same
1781	/// Matrix account when a client flows through
1782	/// `/_matrix/client/v3/login/sso/redirect`.
1783	///
1784	/// When a user authorizes any provider configured default, the flow will
1785	/// include all other providers configured default as well for association.
1786	/// NOTE: authorization must succeed for ALL default providers.
1787	#[serde(default)]
1788	pub default: bool,
1789
1790	/// Optional display-name for this provider instance seen on the login page
1791	/// by users. It defaults to `brand`. When configuring multiple providers
1792	/// using the same `brand` this can be set to distinguish them.
1793	pub name: Option<String>,
1794
1795	/// Optional icon for the provider. The canonical providers have a default
1796	/// icon based on the `brand` supplied above when this is not supplied. Note
1797	/// that it uses an MXC url which is curious in the auth-media era and may
1798	/// not be reliable.
1799	pub icon: Option<OwnedMxcUri>,
1800
1801	/// Optional list of scopes to authorize.
1802	///
1803	/// An empty array sends `openid email profile`. The exception is
1804	/// `brand = "MAS"`, which sends only `openid`: MAS rejects `profile`, and
1805	/// its userinfo endpoint returns just `sub` and `username`. Set this to
1806	/// request a different subset. The user can further restrict scopes during
1807	/// their authorization.
1808	///
1809	/// default: []
1810	#[serde(default)]
1811	pub scope: BTreeSet<String>,
1812
1813	/// Optional list of userinfo claims which shape and restrict the way we
1814	/// compute a Matrix UserId for new registrations. Reviewing Tuwunel's
1815	/// documentation will be necessary for a complete description in detail. An
1816	/// empty array imposes no restriction here, avoiding generated fallbacks as
1817	/// much as possible.
1818	///
1819	/// For simplicity we reserve a claim called "unique" which can be listed
1820	/// alone to ensure *only* generated ID's are used for registrations.
1821	///
1822	/// Note that listing the claim "sub" has special significance and will take
1823	/// precedence over all other claims, listed or unlisted. "sub" is not
1824	/// normally used to determine a UserId unless explicitly listed here.
1825	///
1826	/// As of now arbitrary claims cannot be listed here, we only recognize
1827	/// specific hard-coded claims.
1828	///
1829	/// default: []
1830	#[serde(default)]
1831	pub userid_claims: BTreeSet<String>,
1832
1833	/// Whether userinfo claims may grant access to an existing matching account.
1834	///
1835	/// By default we skip matching users and register the first available
1836	/// username, falling back to random characters to avoid conflicts; a trusted
1837	/// provider instead finds the first matching user and grants access to it,
1838	/// which is how an existing matrix account is associated with a provider and
1839	/// also how one can be hijacked. A trusted provider's `email` claim is also
1840	/// bound to a new account when it sends no `email_verified` claim, where an
1841	/// untrusted one must mark it verified. Only set this option to true for
1842	/// providers you self-host and control, never for public providers such as
1843	/// GitHub or GitLab. An existing user can still be associated with an
1844	/// untrusted provider, but only with the command '!admin query oauth
1845	/// associate'.
1846	///
1847	/// default: false
1848	#[serde(default)]
1849	pub trusted: bool,
1850
1851	/// Setting this option to false will inhibit unique ID's from being
1852	/// generated as a last-resort when determining a UserId from a provider's
1853	/// claims. In the case of untrusted providers, when all provided claims
1854	/// conflict with existing user accounts, a unique fallback ID needs
1855	/// to be generated for registration to not be denied with an error.
1856	///
1857	/// Set this option to false if you operate a private server or a trusted
1858	/// identity provider where random UserId's are undesirable; the result of a
1859	/// misconfiguration or other issue where an error is warranted.
1860	///
1861	/// This option should be set to true for public servers or some users may
1862	/// never be able to register.
1863	///
1864	/// default: true
1865	#[serde(default = "true_fn")]
1866	pub unique_id_fallbacks: bool,
1867
1868	/// Controls whether new user registration is possible from this provider.
1869	/// When this option is set to false, authorizations from this provider
1870	/// only affect existing users and will never result in a new registration
1871	/// when the claims fail to match any existing user (in the case of trusted
1872	/// providers) or an available username is found (in the case of untrusted
1873	/// providers).
1874	///
1875	/// When LDAP is enabled, a user found in the LDAP directory counts as an
1876	/// existing user and is still provisioned on first login, since the
1877	/// directory is the authoritative account store.
1878	///
1879	/// Setting this option to false is generally not useful unless there is
1880	/// an explicit reason to do so.
1881	///
1882	/// default: true
1883	#[serde(default = "true_fn")]
1884	pub registration: bool,
1885
1886	/// Optional extra path components after the issuer_url leading to the
1887	/// location of the `.well-known` directory used for discovery. If the path
1888	/// starts with a slash it will be treated as absolute, meaning overwriting
1889	/// any path in the issuer_url. The path needs to end with a slash. This
1890	/// will be empty for specification-compliant providers.
1891	pub base_path: Option<String>,
1892
1893	/// Overrides the `.well-known` location where the provider's openid
1894	/// configuration is found. It is very unlikely you will need to set this;
1895	/// available for developers or special purposes only.
1896	pub discovery_url: Option<Url>,
1897
1898	/// Overrides the authorize URL requested during the grant phase. This is
1899	/// generally discovered or derived automatically, but may be required as a
1900	/// workaround for any non-standard or undiscoverable provider.
1901	pub authorization_url: Option<Url>,
1902
1903	/// Overrides the access token URL; the same caveats apply as with the other
1904	/// URL overrides.
1905	pub token_url: Option<Url>,
1906
1907	/// Overrides the revocation URL; the same caveats apply as with the other
1908	/// URL overrides.
1909	pub revocation_url: Option<Url>,
1910
1911	/// Overrides the introspection URL; the same caveats apply as with the
1912	/// other URL overrides.
1913	pub introspection_url: Option<Url>,
1914
1915	/// Overrides the userinfo URL; the same caveats apply as with the other URL
1916	/// overrides.
1917	pub userinfo_url: Option<Url>,
1918
1919	/// Whether to perform discovery and adjust this provider's configuration
1920	/// accordingly. This defaults to true. When true, it is an error when
1921	/// discovery fails and authorizations will not be attempted to the
1922	/// provider.
1923	#[serde(default = "true_fn")]
1924	pub discovery: bool,
1925
1926	/// The duration in seconds before a grant authorization session expires.
1927	///
1928	/// default: 300
1929	#[serde(default = "default_sso_grant_session_duration")]
1930	pub grant_session_duration: Option<u64>,
1931
1932	/// Whether to check the redirect cookie during the callback. This is a
1933	/// security feature and should remain enabled. This is available for
1934	/// developers or deployments which cannot tolerate cookies and are willing
1935	/// to tolerate the risks.
1936	///
1937	/// default: true
1938	#[serde(default = "true_fn")]
1939	pub check_cookie: bool,
1940
1941	/// Extra query parameters appended to every authorization request sent to
1942	/// the identity provider.
1943	///
1944	/// E.g. to force re-authentication even if IdP cookies are present:
1945	/// ```toml
1946	/// [[global.identity_provider]]
1947	/// extra_authorization_parameters = { prompt = "login" }
1948	/// ```
1949	///
1950	/// default: {}
1951	#[serde(default)]
1952	pub extra_authorization_parameters: BTreeMap<String, String>,
1953
1954	/// Forward the MSC3824 `action` query parameter from the SSO redirect
1955	/// endpoints to this provider as an OpenID Connect `prompt` value.
1956	///
1957	/// When a client appends `action=register` to a `/login/sso/redirect`
1958	/// request the upstream authorization request carries `prompt=create`
1959	/// (the OpenID Connect "Initiating User Registration" extension) so the
1960	/// provider can present its registration screen. `action=login` is left
1961	/// unforwarded to avoid forcing a re-authentication, and a `prompt` set in
1962	/// `extra_authorization_parameters` still applies in that case. An
1963	/// action-derived `prompt` takes precedence over one configured there.
1964	///
1965	/// Leave this disabled unless the provider supports the `prompt=create`
1966	/// registration extension; a provider that does not may reject or ignore
1967	/// the request.
1968	///
1969	/// default: false
1970	#[serde(default)]
1971	pub forward_action_prompt: bool,
1972}
1973
1974impl IdentityProvider {
1975	/// Returns the provider's stable identifier.
1976	///
1977	/// The identifier is the OAuth application's client ID. It is borrowed from
1978	/// this configuration without allocation.
1979	#[inline]
1980	#[must_use]
1981	pub fn id(&self) -> &str { self.client_id.as_str() }
1982
1983	/// Loads the effective client secret.
1984	///
1985	/// An inline secret takes precedence over a configured secret file. File
1986	/// contents are read asynchronously and trimmed before being returned.
1987	pub async fn get_client_secret(&self) -> Result<String> {
1988		if let Some(client_secret) = &self.client_secret {
1989			return Ok(client_secret.clone());
1990		}
1991
1992		let Some(client_secret_file) = &self.client_secret_file else {
1993			return Err!("No client secret or client secret file configured");
1994		};
1995
1996		let client_secret = tokio::fs::read_to_string(client_secret_file).await?;
1997
1998		Ok(client_secret.trim().to_owned())
1999	}
2000}
2001
2002/// Returns the name shown to a user choosing between providers.
2003///
2004/// The configured name wins, and the brand stands in when none is set.
2005#[implement(IdentityProvider)]
2006#[inline]
2007#[must_use]
2008pub fn display_name(&self) -> &str { self.name.as_deref().unwrap_or(&self.brand) }
2009
2010/// Selects the backend for a named media storage provider.
2011///
2012/// Local providers store objects beneath a filesystem path, while S3 providers
2013/// use a compatible object store. The default variant disables the entry.
2014#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
2015pub enum StorageProvider {
2016	/// Selects a local filesystem backend.
2017	///
2018	/// The contained settings root object paths beneath a configured directory.
2019	/// Startup checks can require that directory to be usable.
2020	#[expect(non_camel_case_types)]
2021	local(StorageProviderLocal),
2022
2023	/// Selects an S3-compatible object storage backend.
2024	///
2025	/// The boxed settings configure endpoint, credentials, encryption, and
2026	/// multipart uploads. Custom endpoints permit compatible non-AWS services.
2027	#[expect(non_camel_case_types)]
2028	#[serde(rename = "s3", alias = "S3")]
2029	s3(Box<StorageProviderS3>),
2030
2031	/// Selects a Google Cloud Storage backend.
2032	///
2033	/// The boxed settings configure the bucket and object prefix. Credentials
2034	/// are resolved by the object-store client, which falls back to the
2035	/// instance metadata server when none are configured; that is what allows
2036	/// use from GKE Workload Identity without any exported key material.
2037	#[expect(non_camel_case_types)]
2038	#[serde(rename = "gcs", alias = "GCS")]
2039	gcs(Box<StorageProviderGcs>),
2040
2041	/// Disables this storage provider entry.
2042	///
2043	/// This is the default when no backend variant is selected. It carries no
2044	/// backend settings.
2045	#[default]
2046	None,
2047}
2048
2049/// Local filesystem storage provider
2050///
2051/// Stores media files under a local directory. Unless replaced, a built-in
2052/// local provider named `media` keeps media in the `media` directory under
2053/// `database_path`; add a table here to move that directory or to add
2054/// another one.
2055///
2056/// - `<ID>`: your name for this provider. Media uses a provider only when
2057///   `media.storage_providers` (default `["media"]`) lists it;
2058///   `media.store_on_providers` and `media.import.conduit.source_provider`
2059///   name providers the same way. Listing an undefined id fails startup.
2060///   `media` is the built-in local provider, and a `media` entry replaces
2061///   it. Use one backend (`local`, `s3` or `gcs`) per `<ID>`. Bare keys may
2062///   use `A-Z a-z 0-9 _ -`; anything else must be quoted
2063///   (`[global.storage_provider."my.media".local]`), and an unquoted dot
2064///   splits the name into nested tables.
2065///
2066/// `base_path` is required; an empty value disables the entry. Unless
2067/// `create_if_missing` is set, the directory must already exist or startup
2068/// fails.
2069///
2070/// Example (moving the built-in `media` directory):
2071///
2072/// ```toml
2073///     [global.storage_provider.media.local]
2074///     base_path = "/srv/tuwunel/media"
2075/// ```
2076///
2077/// Tips:
2078/// - The built-in `media` provider creates its directory; an explicit
2079///   `media` entry does so only with `create_if_missing`.
2080/// - Providers are built once at startup, so a config reload that adds,
2081///   removes or changes a provider section is refused; restart instead.
2082#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
2083#[config_example_generator(
2084	filename = "tuwunel-example.toml",
2085	section = "global.storage_provider.<ID>.local"
2086)]
2087pub struct StorageProviderLocal {
2088	/// Absolute path to this local filesystem storage provider. Technically the
2089	/// provider exists at the filesystem root, and the base_path is prefixed to
2090	/// all objects.
2091	#[serde(alias = "path")]
2092	pub base_path: String,
2093
2094	/// Creates the directory on the local filesystem if missing. This is not
2095	/// recommended to prevent misconfigured environments and missing mounts
2096	/// from silently succeeding.
2097	#[serde(default)]
2098	pub create_if_missing: bool,
2099
2100	/// Toggles the preservation of a directory after its last file contents are
2101	/// removed.
2102	#[serde(default = "true_fn")]
2103	pub delete_empty_directories: bool,
2104
2105	/// Enables checks performed at startup determining the usability of the
2106	/// local directory. Failures will abort the server's startup.
2107	///
2108	/// default: true
2109	#[serde(default = "true_fn")]
2110	pub startup_check: bool,
2111}
2112
2113/// S3 storage provider
2114///
2115/// Stores media in an S3-compatible object store: AWS S3, or another
2116/// service reached through `endpoint`.
2117///
2118/// - `<ID>`: your name for this provider. Media uses a provider only when
2119///   `media.storage_providers` (default `["media"]`) lists it;
2120///   `media.store_on_providers` and `media.import.conduit.source_provider`
2121///   name providers the same way. Listing an undefined id fails startup.
2122///   `media` is the built-in local provider, and a `media` entry replaces
2123///   it. Use one backend (`local`, `s3` or `gcs`) per `<ID>`. Bare keys may
2124///   use `A-Z a-z 0-9 _ -`; anything else must be quoted
2125///   (`[global.storage_provider."my.media".s3]`), and an unquoted dot
2126///   splits the name into nested tables.
2127///
2128/// Set `url` or `bucket`; with neither, the entry is skipped, even when
2129/// `media.storage_providers` lists it. Skipping it is an error only when no
2130/// enabled provider is left to receive uploads. Keys left unset fall back
2131/// to the standard `AWS_*` environment variables.
2132///
2133/// Example:
2134///
2135/// ```toml
2136///     [global.storage_provider.s3_media.s3]
2137///     bucket = "my-media-bucket"
2138///     region = "us-west-2"
2139///     key = "CHANGE_ME"
2140///     secret = "CHANGE_ME"
2141/// ```
2142///
2143/// Tips:
2144/// - `media.storage_providers = ["media", "s3_media"]` with
2145///   `media.store_on_providers = ["s3_media"]` writes new media to S3 and
2146///   still reads older media from `media`. Without `store_on_providers`,
2147///   every upload goes to both (startup warns).
2148/// - The path in an `s3://bucket/path` `url` is not used as a prefix; set
2149///   `base_path` instead.
2150/// - Providers are built once at startup, so a config reload that adds,
2151///   removes or changes a provider section is refused; restart instead.
2152#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
2153#[config_example_generator(
2154	filename = "tuwunel-example.toml",
2155	section = "global.storage_provider.<ID>.s3",
2156	section_aliases = "S3"
2157)]
2158pub struct StorageProviderS3 {
2159	/// Sets the bucket, and for some forms the region, from an S3 URL.
2160	///
2161	/// An `s3://bucket` URL supplies only the bucket, and its path is ignored,
2162	/// so set `base_path` for a prefix within the bucket. An AWS `https://` URL
2163	/// that names a region (`https://s3.<region>.amazonaws.com/<bucket>` or
2164	/// `https://<bucket>.s3.<region>.amazonaws.com`) supplies it too, a
2165	/// Cloudflare R2 URL sets it to `auto`, and values taken from the URL
2166	/// override `bucket` and `region`.
2167	///
2168	/// example: "s3://my-media-bucket"
2169	pub url: Option<String>,
2170
2171	/// The name of the S3 bucket. e.g. "bucketname-123456789-us-west-2-an".
2172	pub bucket: Option<String>,
2173
2174	/// The region of the S3 bucket. e.g. "us-west-2".
2175	///
2176	/// default: "us-east-1"
2177	pub region: Option<String>,
2178
2179	/// Your amazon IAM Key ID with access granted to this bucket.
2180	/// e.g. "ABCDEFG1X1ZZYYXXWWVV"
2181	#[debug("{}", redacted_debug!(key))]
2182	pub key: Option<String>,
2183
2184	/// The secret key component which is approx 40 characters of base64.
2185	///
2186	/// default:
2187	/// display: sensitive
2188	#[serde(skip_serializing)]
2189	#[debug("{}", redacted_debug!(secret))]
2190	pub secret: Option<String>,
2191
2192	/// Optional path prefix within the bucket where all our operations will
2193	/// take place.
2194	#[serde(alias = "path")]
2195	pub base_path: Option<String>,
2196
2197	/// (expert use) Sets the S3 endpoint for self-hosted or other compatible
2198	/// services.
2199	///
2200	/// A dual-stack AWS or Cloudflare R2 `url` sets its own endpoint, which
2201	/// overrides this value.
2202	pub endpoint: Option<String>,
2203
2204	/// (expert use) Turns virtual-hosted-style requests on or off, which some
2205	/// self-hosted services need.
2206	///
2207	/// A virtual-hosted AWS `url` (`https://<bucket>.s3.<region>.amazonaws.com`)
2208	/// turns them on regardless of this value.
2209	#[serde(default)]
2210	pub use_vhost_request: Option<bool>,
2211
2212	/// (expert use) Alternative session-token authentication method.
2213	///
2214	/// display: sensitive
2215	/// default:
2216	#[serde(skip_serializing)]
2217	#[debug("{}", redacted_debug!(token))]
2218	pub token: Option<String>,
2219
2220	/// (expert use) Associated SSE-KMS key material.
2221	///
2222	/// display: sensitive
2223	#[debug("{}", redacted_debug!(kms))]
2224	pub kms: Option<String>,
2225
2226	/// (expert use) When configured for the bucket it should be reflected here.
2227	pub use_bucket_key: Option<bool>,
2228
2229	/// (expert use) Threshold size for switching to Multi-part uploads. This is
2230	/// a quirk of the S3 protocol which requires us to use a different approach
2231	/// for "large" uploads. This value determines what a "large" upload is. The
2232	/// default value should be sufficient for most providers. The value is a
2233	/// parsed string allowing SI or IEC units for convenience.
2234	///
2235	/// default: "100 MiB"
2236	#[serde(default = "default_multipart_threshold")]
2237	pub multipart_threshold: ByteSize,
2238
2239	/// (expert use) Size of each individual part within a Multi-part upload.
2240	/// Once an upload exceeds `multipart_threshold` the payload is split into
2241	/// parts of this size, each sent as a separate HTTP PUT. Smaller values
2242	/// keep individual requests under per-request timeouts on slow uplinks at
2243	/// the cost of more round-trips. S3 requires every part except the last
2244	/// to be at least 5 MiB. The value is a parsed string allowing SI or IEC
2245	/// units for convenience.
2246	///
2247	/// default: "10 MiB"
2248	#[serde(default = "default_multipart_part_size")]
2249	pub multipart_part_size: ByteSize,
2250
2251	/// (developer use) Allows relaxing default requirement forcing HTTPS.
2252	///
2253	/// default: true
2254	#[serde(default = "some_true_fn")]
2255	pub use_https: Option<bool>,
2256
2257	/// (developer_use) Allows skipping request header signatures (will be
2258	/// reejected by AWS).
2259	///
2260	/// default: true
2261	#[serde(default = "some_true_fn")]
2262	pub use_signatures: Option<bool>,
2263
2264	/// (developer_use) Allows disabling request payload signatures.
2265	///
2266	/// default: true
2267	#[serde(default = "some_true_fn")]
2268	pub use_payload_signatures: Option<bool>,
2269
2270	/// (developer use) Enables checks performed at startup such as pinging the
2271	/// provider. Failures are considered critical startup errors which abort
2272	/// startup. When set to false, faulty providers are only discovered with
2273	/// first use and will not be fatal errors.
2274	///
2275	/// Only set this to false if you expect a provider to be down at startup or
2276	/// for development/testing purposes; checks are disabled when the server
2277	/// is started in '--maintenance' mode.
2278	///
2279	/// default: true
2280	#[serde(default = "true_fn")]
2281	pub startup_check: bool,
2282}
2283
2284/// Google Cloud Storage provider
2285///
2286/// Stores media in a Google Cloud Storage bucket. With no credential keys
2287/// set, credentials come from the environment and finally the instance
2288/// metadata server, so GKE Workload Identity needs no key file.
2289///
2290/// - `<ID>`: your name for this provider. Media uses a provider only when
2291///   `media.storage_providers` (default `["media"]`) lists it;
2292///   `media.store_on_providers` and `media.import.conduit.source_provider`
2293///   name providers the same way. Listing an undefined id fails startup.
2294///   `media` is the built-in local provider, and a `media` entry replaces
2295///   it. Use one backend (`local`, `s3` or `gcs`) per `<ID>`. Bare keys may
2296///   use `A-Z a-z 0-9 _ -`; anything else must be quoted
2297///   (`[global.storage_provider."my.media".gcs]`), and an unquoted dot
2298///   splits the name into nested tables.
2299///
2300/// `bucket` is the only required key; without it the entry is skipped,
2301/// even when `media.storage_providers` lists it. Skipping it is an error
2302/// only when no enabled provider is left to receive uploads.
2303///
2304/// Minimal example:
2305///
2306/// ```toml
2307///     [global.storage_provider.gcs_media.gcs]
2308///     bucket = "my-media-bucket"
2309/// ```
2310///
2311/// Tips:
2312/// - `media.storage_providers = ["media", "gcs_media"]` with
2313///   `media.store_on_providers = ["gcs_media"]` writes new media to GCS and
2314///   still reads older media from `media`. Without `store_on_providers`,
2315///   every upload goes to both (startup warns).
2316/// - Providers are built once at startup, so a config reload that adds,
2317///   removes or changes a provider section is refused; restart instead.
2318#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
2319#[config_example_generator(
2320	filename = "tuwunel-example.toml",
2321	section = "global.storage_provider.<ID>.gcs",
2322	section_aliases = "GCS"
2323)]
2324pub struct StorageProviderGcs {
2325	/// The name of the GCS bucket, e.g. "my-media-bucket". Required; an unset
2326	/// bucket disables this provider.
2327	///
2328	/// A `gs://bucket/path` URL is intentionally not accepted here: the path
2329	/// component would not be applied as an object prefix. Set `bucket` and
2330	/// `base_path` separately instead.
2331	pub bucket: Option<StorageBucketName>,
2332
2333	/// Optional path prefix within the bucket where all our operations will take
2334	/// place.
2335	#[serde(alias = "path")]
2336	pub base_path: Option<String>,
2337
2338	/// (expert use) Path to a Google service account key file. Leave unset to
2339	/// resolve credentials from the environment, which on GCE/GKE ends at the
2340	/// instance metadata server; that is the keyless path and the recommended
2341	/// configuration. Setting this requires exported key material.
2342	pub service_account_path: Option<String>,
2343
2344	/// (expert use) Path to an application default credentials file. Leave unset
2345	/// to resolve credentials from the environment. Only service-account and
2346	/// authorized-user documents are recognised, not every
2347	/// external-account/workload-identity-federation file format.
2348	pub application_credentials_path: Option<String>,
2349
2350	/// (expert use) Threshold size for switching to multi-part uploads. This value
2351	/// determines what a "large" upload is. The value is a parsed string allowing
2352	/// SI or IEC units for convenience.
2353	///
2354	/// default: "100 MiB"
2355	#[serde(default = "default_multipart_threshold")]
2356	pub multipart_threshold: ByteSize,
2357
2358	/// (expert use) Size of each individual part within a multi-part upload. Once
2359	/// an upload exceeds `multipart_threshold` the payload is split into parts of
2360	/// this size, each sent as a separate request. The value is a parsed string
2361	/// allowing SI or IEC units for convenience.
2362	///
2363	/// default: "10 MiB"
2364	#[serde(default = "default_multipart_part_size")]
2365	pub multipart_part_size: ByteSize,
2366
2367	/// (developer use) Allows skipping request signatures.
2368	///
2369	/// default: true
2370	#[serde(default = "some_true_fn")]
2371	pub use_signatures: Option<bool>,
2372
2373	/// (developer use) Enables checks performed at startup, such as probing the
2374	/// provider. Failures are considered critical startup errors and abort
2375	/// startup. When set to false, faulty providers are only discovered on first
2376	/// use and will not be fatal errors.
2377	///
2378	/// The check is a listing probe: it requires `storage.objects.list`, proves
2379	/// neither write nor delete permission, and passes on an empty bucket.
2380	///
2381	/// default: true
2382	#[serde(default = "true_fn")]
2383	pub startup_check: bool,
2384}
2385
2386/// Application services (bridges and bots)
2387///
2388/// Registers an appservice inline, instead of through a registration file
2389/// in `appservice_dir` or `!admin appservices register`. Add one table per
2390/// appservice, with its namespaces in `[[global.appservice.<ID>.users]]`,
2391/// `rooms` and `aliases` tables. Inline appservices load at startup; a
2392/// config reload does not apply changes here.
2393///
2394/// - `<ID>`: your name for this appservice. It becomes the registration
2395///   `id` used by `!admin appservices` commands (an explicit `id` key must
2396///   match it), and the bot user is `@<ID>:<server_name>` unless
2397///   `sender_localpart` is set. It must be unique across all appservices.
2398///   Lowercase letters, digits, `_` and `-` suit both a bare key and a
2399///   localpart; anything else must be quoted
2400///   (`[global.appservice."my.bridge"]`), and an unquoted dot splits the
2401///   name into nested tables.
2402///
2403/// `as_token` and `hs_token` are required and must match the bridge's
2404/// registration; `url` is where events are sent (omit it if none are
2405/// needed).
2406///
2407/// Example:
2408///
2409/// ```toml
2410///     [global.appservice.whatsapp]
2411///     url = "http://127.0.0.1:29318"
2412///     as_token = "CHANGE_ME_AS_TOKEN"
2413///     hs_token = "CHANGE_ME_HS_TOKEN"
2414/// ```
2415///
2416/// Tips:
2417/// - An `id` or `as_token` that another registration also uses (inline,
2418///   in `appservice_dir` or from the admin room) aborts appservice loading
2419///   at startup, and registrations after it are not loaded; unregister an
2420///   admin-room copy before moving it here. The admin commands can neither
2421///   register over nor unregister an inline appservice.
2422#[derive(Clone, Debug, Default, Deserialize)]
2423#[config_example_generator(
2424	filename = "tuwunel-example.toml",
2425	section = "global.appservice.<ID>",
2426	ignore = "users aliases rooms",
2427	hidden = "id"
2428)]
2429pub struct AppService {
2430	/// Identifies the application service registration.
2431	///
2432	/// An empty value is replaced with the enclosing config map key. An
2433	/// explicit value must match that key.
2434	#[serde(default)]
2435	pub id: String,
2436
2437	/// The URL for the application service.
2438	///
2439	/// Optionally set to `null` if no traffic is required.
2440	///
2441	/// On Unix, use `unix:///absolute/path.sock` to connect over a Unix socket.
2442	///
2443	/// example: "unix:///run/mautrix-whatsapp/appservice.sock"
2444	pub url: Option<String>,
2445
2446	/// A unique token for application services to use to authenticate requests
2447	/// to Homeservers.
2448	///
2449	/// default:
2450	/// display: sensitive
2451	#[debug("{}", redacted_debug!(str as_token))]
2452	pub as_token: String,
2453
2454	/// A unique token for Homeservers to use to authenticate requests to
2455	/// application services.
2456	///
2457	/// default:
2458	/// display: sensitive
2459	#[debug("{}", redacted_debug!(str hs_token))]
2460	pub hs_token: String,
2461
2462	/// The localpart of the user associated with the application service.
2463	pub sender_localpart: Option<String>,
2464
2465	/// Events which are sent from certain users.
2466	#[serde(default)]
2467	pub users: Vec<AppServiceNamespace>,
2468
2469	/// Events which are sent in rooms with certain room aliases.
2470	#[serde(default)]
2471	pub aliases: Vec<AppServiceNamespace>,
2472
2473	/// Events which are sent in rooms with certain room IDs.
2474	#[serde(default)]
2475	pub rooms: Vec<AppServiceNamespace>,
2476
2477	/// Whether requests from masqueraded users are rate-limited.
2478	///
2479	/// The sender is excluded.
2480	#[serde(default)]
2481	pub rate_limited: bool,
2482
2483	/// The external protocols which the application service provides (e.g.
2484	/// IRC).
2485	///
2486	/// default: []
2487	#[serde(default)]
2488	pub protocols: Vec<String>,
2489
2490	/// Whether the application service wants to receive ephemeral data.
2491	///
2492	/// default: false
2493	#[serde(default)]
2494	pub receive_ephemeral: bool,
2495
2496	/// Whether the application service wants to do device management, as part
2497	/// of MSC4190.
2498	///
2499	/// default: false
2500	#[serde(default)]
2501	pub device_management: bool,
2502
2503	/// Whether the application service wants MSC3202 transaction extensions
2504	/// (device lists, one-time-key counts, and unused fallback key types).
2505	///
2506	/// The registration-file key is `org.matrix.msc3202`; this inline-config
2507	/// key is `msc3202_transaction_extensions`.
2508	///
2509	/// default: false
2510	#[serde(default)]
2511	pub msc3202_transaction_extensions: bool,
2512
2513	/// Scopes the application service requests, as part of MSC4502.
2514	///
2515	/// The registration-file key is `io.element.msc4502.scopes`; this
2516	/// inline-config key is `scopes`. The one known scope,
2517	/// `urn:matrix:client:io.element.msc4502:rooms:is_joined`, lets the
2518	/// appservice ask whether any user or server is joined to a room. An
2519	/// unknown scope grants nothing and is logged as a warning at startup.
2520	///
2521	/// default: []
2522	#[serde(default)]
2523	pub scopes: Vec<String>,
2524
2525	/// The path prefix the application service claims for proxied requests,
2526	/// as part of MSC4512.
2527	///
2528	/// The registration-file key is `io.element.msc4512.proxy_prefix`; this
2529	/// inline-config key is `proxy_prefix`. Authenticated requests under
2530	/// `/_matrix/client/<version>/<prefix>` and
2531	/// `/_matrix/federation/<version>/<prefix>` are forwarded to `proxy_url`,
2532	/// and the appservice may send federation requests under the prefix
2533	/// through the MSC4512 `fed_proxy` endpoint. The one allowed prefix is
2534	/// `rtc/livekit`. Give it together with `proxy_url`; an invalid claim, or
2535	/// one another appservice holds, is ignored with a warning at startup.
2536	///
2537	/// example: "rtc/livekit"
2538	pub proxy_prefix: Option<String>,
2539
2540	/// The URL proxied requests under `proxy_prefix` are forwarded to, as part
2541	/// of MSC4512.
2542	///
2543	/// The registration-file key is `io.element.msc4512.proxy_url`; this
2544	/// inline-config key is `proxy_url`. It takes the forms `url` takes,
2545	/// `unix:///absolute/path.sock` included.
2546	///
2547	/// example: "http://lk-jwt-service:8080"
2548	pub proxy_url: Option<String>,
2549}
2550
2551impl From<AppService> for ruma::api::appservice::Registration {
2552	fn from(conf: AppService) -> Self {
2553		use ruma::api::appservice::Namespaces;
2554
2555		let sender_localpart = conf
2556			.sender_localpart
2557			.unwrap_or_else(|| conf.id.clone());
2558
2559		Self {
2560			id: conf.id,
2561			url: conf.url,
2562			as_token: conf.as_token,
2563			hs_token: conf.hs_token,
2564			receive_ephemeral: conf.receive_ephemeral,
2565			device_management: conf.device_management,
2566			msc3202_transaction_extensions: conf.msc3202_transaction_extensions,
2567			protocols: conf.protocols.into(),
2568			rate_limited: conf.rate_limited.into(),
2569			sender_localpart,
2570			namespaces: Namespaces {
2571				users: conf.users.into_iter().map(Into::into).collect(),
2572				aliases: conf.aliases.into_iter().map(Into::into).collect(),
2573				rooms: conf.rooms.into_iter().map(Into::into).collect(),
2574			},
2575			keys_claims: false,
2576			scopes: conf.scopes,
2577			proxy_prefix: conf.proxy_prefix,
2578			proxy_url: conf.proxy_url,
2579		}
2580	}
2581}
2582
2583/// Appservice namespaces
2584///
2585/// Claims the user IDs, room aliases or room IDs an appservice manages.
2586/// Each `[[...]]` header appends one entry to the list it names, so repeat
2587/// the header for more patterns. The appservice may act only as users
2588/// matching `users` and create only aliases matching `aliases`; the server
2589/// sends it events from rooms that hold its users or match its `aliases` or
2590/// `rooms` entries.
2591///
2592/// - `<ID>`: the `<ID>` of the `[global.appservice.<ID>]` table this entry
2593///   belongs to, spelled (and quoted) the same way.
2594/// - `<users|rooms|aliases>`: one of the literal names `users` (user IDs
2595///   on this server), `aliases` (room aliases) or `rooms` (room IDs). Any
2596///   other name is ignored without a warning.
2597///
2598/// `regex` is required. Matching is unanchored (add `^` and `$`),
2599/// case-insensitive for `users` and `aliases`, case-sensitive for `rooms`.
2600/// Write the pattern as a single-quoted TOML string so backslashes stay
2601/// literal.
2602///
2603/// Example:
2604///
2605/// ```toml
2606///     [[global.appservice.whatsapp.users]]
2607///     exclusive = true
2608///     regex = '^@whatsapp_.*:example\.com$'
2609/// ```
2610///
2611/// Tips:
2612/// - `exclusive = true` stops ordinary users from registering matching user
2613///   IDs or creating matching aliases; on `rooms` entries it has no effect.
2614#[derive(Clone, Debug, Default, Deserialize)]
2615#[config_example_generator(
2616	filename = "tuwunel-example.toml",
2617	section = "[global.appservice.<ID>.<users|rooms|aliases>]"
2618)]
2619pub struct AppServiceNamespace {
2620	/// Whether this application service has exclusive access to events within
2621	/// this namespace.
2622	#[serde(default)]
2623	pub exclusive: bool,
2624
2625	/// A regular expression defining which values this namespace includes.
2626	pub regex: String,
2627}
2628
2629impl From<AppServiceNamespace> for ruma::api::appservice::Namespace {
2630	fn from(conf: AppServiceNamespace) -> Self {
2631		Self {
2632			exclusive: conf.exclusive,
2633			regex: conf.regex,
2634		}
2635	}
2636}
2637
2638/// Items matched here will not generate an "unknown to tuwunel" warning when
2639/// configured. This is important for environment variables which share the
2640/// `TUWUNEL_` prefix namespace but aren't config items;  match them here in
2641/// their split+lowercased format.
2642static KNOWN_KEYS: &[&str; 3] = &["^config$", "^runtime_[a-z0-9_]+$", "^appservice_keys_claims$"];
2643
2644/// Items listed here generate a deprecation warning when configured.
2645static DEPRECATED_KEYS: &[&str; 11] = &[
2646	"appservice_keys_claims",
2647	"cache_capacity",
2648	"conduit_cache_capacity_modifier",
2649	"ldap.name_attribute",
2650	"max_concurrent_requests",
2651	"well_known_client",
2652	"well_known_server",
2653	"well_known_support_page",
2654	"well_known_support_role",
2655	"well_known_support_email",
2656	"well_known_support_mxid",
2657];
2658
2659impl Config {
2660	/// Loads raw configuration from ordered file and environment sources.
2661	///
2662	/// Explicit paths follow config files selected through the supported
2663	/// environment variables, and later files override earlier files. Config
2664	/// values from the three environment namespaces take precedence over files.
2665	pub fn load<'a, I>(paths: I) -> Result<Figment>
2666	where
2667		I: Iterator<Item = &'a Path>,
2668	{
2669		let paths = Self::file_paths(paths);
2670		let config = Self::load_files(paths)?;
2671
2672		Self::merge_environment(config)
2673	}
2674}
2675
2676#[implement(Config)]
2677pub(crate) fn file_paths<'a, I>(paths: I) -> impl Iterator<Item = PathBuf>
2678where
2679	I: Iterator<Item = &'a Path>,
2680{
2681	[
2682		Env::var("CONDUIT_CONFIG"),
2683		Env::var("CONDUWUIT_CONFIG"),
2684		Env::var("TUWUNEL_CONFIG"),
2685	]
2686	.into_iter()
2687	.flatten()
2688	.map(PathBuf::from)
2689	.chain(paths.map(Path::to_path_buf))
2690}
2691
2692#[implement(Config)]
2693pub(crate) fn load_files<I, P>(paths: I) -> Result<Figment>
2694where
2695	I: Iterator<Item = P>,
2696	P: Into<PathBuf>,
2697{
2698	let toml_files = paths.map(Into::into).collect_vec();
2699
2700	// figment reads only `is_file()` paths and silently loads anything else as empty.
2701	let invalid_toml_files = toml_files
2702		.iter()
2703		.filter(|path| !path.is_file())
2704		.map(|path| path.as_os_str())
2705		.collect_vec();
2706
2707	if !invalid_toml_files.is_empty() {
2708		return Err!(
2709			"The following config files do not exist, are not regular files, or have broken \
2710			 symlinks: {invalid_toml_files:?}"
2711		);
2712	}
2713
2714	toml_files
2715		.iter()
2716		.try_fold(Figment::new(), |config, path| {
2717			Self::load_file(path).map(|file| config.merge(file))
2718		})
2719}
2720
2721#[implement(Config)]
2722fn load_file(path: &Path) -> Result<Figment> {
2723	let provider = Toml::file(path);
2724	let profiles = Provider::data(&provider)?;
2725	let values = profiles.get(&FigmentProfile::Default);
2726	let headerless = values.is_some_and(|values| {
2727		values
2728			.values()
2729			.any(|value| value.as_dict().is_none())
2730	});
2731
2732	let has_global = values.is_some_and(|values| values.contains_key("global"));
2733
2734	if headerless && has_global {
2735		return Err!(
2736			"Configuration file mixes bare keys with a [global] profile: {}.",
2737			path.display()
2738		);
2739	}
2740
2741	let provider = match headerless {
2742		| true => provider.profile(FigmentProfile::Global),
2743		| false => provider.nested(),
2744	};
2745
2746	let config = Figment::new().merge(Self::normalize(provider)?);
2747
2748	Ok(config)
2749}
2750
2751/// Normalizes one configuration source before it is combined with others.
2752///
2753/// Legacy paths retain source metadata and follow the same precedence as
2754/// canonical paths. Conflicting spellings within one source are rejected.
2755/// The returned provider supplies its snapshot to one combination operation.
2756#[implement(Config)]
2757pub fn normalize<P: Provider>(provider: P) -> Result<impl Provider> {
2758	normalize_provider(provider).map_err(Into::into)
2759}
2760
2761#[implement(Config)]
2762pub(crate) fn merge_environment(config: Figment) -> Result<Figment> {
2763	ENV_PREFIXES
2764		.into_iter()
2765		.try_fold(config, |config, prefix| {
2766			environment(prefix)
2767				.map(|provider| config.merge(provider))
2768				.map_err(Into::into)
2769		})
2770}
2771
2772impl Config {
2773	/// Extracts the typed configuration from the merged raw sources.
2774	///
2775	/// A rejection is reported against the configuration file when one was
2776	/// loaded. With none loaded, the field detail is followed by a note that
2777	/// no file was selected, naming `--config` and `TUWUNEL_CONFIG`. Keys the
2778	/// schema does not know are recorded in `catchall`.
2779	pub fn new(raw_config: &Figment) -> Result<Self> {
2780		assert_canonical(raw_config)?;
2781		let config = raw_config
2782			.extract::<Self>()
2783			.map_err(redact_error)
2784			.map_err(|e| extraction_error(raw_config, &e))?;
2785
2786		Ok(with_unknown(config, raw_config))
2787	}
2788
2789	/// Validates the complete configuration.
2790	///
2791	/// The startup checks emit warnings for deprecated or risky settings and
2792	/// reject invalid combinations. Reload-specific comparisons are performed
2793	/// by the configuration manager separately.
2794	pub fn check(&self) -> Result { check(self) }
2795}
2796
2797fn extraction_error(raw: &Figment, error: &FigmentError) -> Error {
2798	let from_file = raw
2799		.metadata()
2800		.any(|metadata| matches!(metadata.source, Some(Source::File(_))));
2801
2802	match from_file {
2803		| true => err!("There was a problem with your configuration file: {error}"),
2804		| false => err!(
2805			"There was a problem with your configuration: {error} (no configuration file was \
2806			 loaded; pass one with --config or set TUWUNEL_CONFIG)"
2807		),
2808	}
2809}
2810
2811fn with_unknown(mut config: Config, raw: &Figment) -> Config {
2812	config
2813		.catchall
2814		.extend(unknown(raw).map(|path| (path, IgnoredAny)));
2815
2816	config
2817}
2818
2819/// Argon2id cost parameters for hashing a new password.
2820///
2821/// The three settings are interdependent, so they travel as a unit rather than
2822/// being read one at a time. Verification never consults them: the cost of
2823/// checking a password comes from the stored hash.
2824#[implement(Config)]
2825#[inline]
2826#[must_use]
2827pub fn password_hash_cost(&self) -> Cost {
2828	Cost {
2829		m_cost: self.authentication.argon2.m_cost,
2830		t_cost: self.authentication.argon2.t_cost,
2831		p_cost: self.authentication.argon2.p_cost,
2832	}
2833}
2834
2835/// Returns whether login screens list each identity provider by name.
2836///
2837/// `authentication.login.single_sso` and
2838/// `authentication.login.sso_custom_providers_page` each replace that list with
2839/// one single sign-on entry.
2840#[implement(Config)]
2841#[inline]
2842#[must_use]
2843pub fn lists_identity_providers(&self) -> bool {
2844	self.authentication
2845		.login
2846		.sso_custom_providers_page
2847		.is_false()
2848		&& !self.authentication.login.single_sso
2849}
2850
2851/// Returns whether new accounts may be registered with a password.
2852///
2853/// Password registration needs both `registration.enable` and
2854/// `authentication.login.with_password`, since a password account on a server
2855/// refusing password login could never sign in again. Registration through an
2856/// identity provider follows that provider's own `registration` option instead.
2857#[implement(Config)]
2858#[inline]
2859#[must_use]
2860pub fn allows_password_registration(&self) -> bool {
2861	self.registration.enable && self.authentication.login.with_password
2862}
2863
2864/// Lists the storage provider sections the storage service builds from.
2865///
2866/// These are the configured sections plus the built-in local `media`
2867/// provider, which keeps media in the `media` directory under
2868/// `database_path` and is left out when a `media` section replaces it.
2869#[implement(Config)]
2870pub fn storage_provider_sections(&self) -> impl Iterator<Item = ProviderSection<'_>> {
2871	let builtin = once("media")
2872		.filter(|name| !self.storage_provider.contains_key(*name))
2873		.map(|name| {
2874			let base_path = self
2875				.database_path
2876				.join(name)
2877				.to_string_lossy()
2878				.into_owned();
2879
2880			let provider = StorageProviderLocal {
2881				create_if_missing: true,
2882				base_path,
2883				..Default::default()
2884			};
2885
2886			(name, Cow::Owned(StorageProvider::local(provider)))
2887		});
2888
2889	self.storage_provider
2890		.iter()
2891		.map(|(name, provider)| (name.as_str(), Cow::Borrowed(provider)))
2892		.chain(builtin)
2893}
2894
2895impl TlsConfig {
2896	/// Returns the configured TLS certificate and key paths together.
2897	///
2898	/// A pair is returned only when both options are present. Startup
2899	/// validation rejects a configuration containing only one of the two
2900	/// paths.
2901	#[must_use]
2902	pub fn get_tls_cert_key(&self) -> Option<(&Path, &Path)> {
2903		let cert = self.certs.as_ref()?;
2904
2905		let cert = Path::new(cert);
2906
2907		let key = self.key.as_ref()?; // this cannot fail, aborts startup on cert.is_some ^ key.is_some
2908
2909		let key = Path::new(key);
2910
2911		Some((cert, key))
2912	}
2913}
2914
2915impl StorageProvider {
2916	/// Reports whether this entry selects a backend the storage service builds.
2917	///
2918	/// `None` is never enabled; a backend variant defers to that backend's own
2919	/// rule.
2920	#[must_use]
2921	pub fn is_enabled(&self) -> bool {
2922		match self {
2923			| Self::local(local) => local.is_enabled(),
2924			| Self::s3(s3) => s3.is_enabled(),
2925			| Self::gcs(gcs) => gcs.is_enabled(),
2926			| Self::None => false,
2927		}
2928	}
2929}
2930
2931impl StorageProviderLocal {
2932	/// Reports whether this local provider is enabled.
2933	///
2934	/// An empty `base_path` disables the entry.
2935	#[inline]
2936	#[must_use]
2937	pub fn is_enabled(&self) -> bool { !self.base_path.is_empty() }
2938}
2939
2940impl StorageProviderS3 {
2941	/// Reports whether this S3 provider is enabled.
2942	///
2943	/// Setting neither `url` nor `bucket` disables the entry.
2944	#[inline]
2945	#[must_use]
2946	pub fn is_enabled(&self) -> bool { self.url.is_some() || self.bucket.is_some() }
2947}
2948
2949impl StorageProviderGcs {
2950	/// Reports whether this GCS provider is enabled.
2951	///
2952	/// An unset `bucket` disables the entry.
2953	#[inline]
2954	#[must_use]
2955	pub fn is_enabled(&self) -> bool { self.bucket.is_some() }
2956}
2957
2958impl Default for LoginFailedRateLimit {
2959	fn default() -> Self {
2960		Self {
2961			per_second: default_login_failed_per_second(),
2962			burst_count: default_login_failed_burst_count(),
2963		}
2964	}
2965}
2966
2967impl Default for LoginAddressRateLimit {
2968	fn default() -> Self {
2969		Self {
2970			per_second: default_login_address_per_second(),
2971			burst_count: default_login_address_burst_count(),
2972		}
2973	}
2974}
2975
2976fn default_login_address_per_second() -> f64 { 1.0 }
2977
2978fn default_login_address_burst_count() -> u32 { 20 }
2979
2980impl Default for LoginAccountRateLimit {
2981	fn default() -> Self {
2982		Self {
2983			per_second: default_login_account_per_second(),
2984			burst_count: default_login_account_burst_count(),
2985		}
2986	}
2987}
2988
2989fn true_fn() -> bool { true }
2990
2991// Synapse's `rc_login` defaults, taken unchanged:
2992// https://element-hq.github.io/synapse/latest/usage/configuration/config_documentation.html#rc_login
2993fn default_login_failed_per_second() -> f64 { 0.17 }
2994
2995fn default_login_failed_burst_count() -> u32 { 3 }
2996
2997fn default_login_account_per_second() -> f64 { 0.003 }
2998
2999fn default_login_account_burst_count() -> u32 { 5 }
3000
3001fn some_true_fn() -> Option<bool> { Some(true) }
3002
3003#[cfg(test)]
3004fn default_server_name() -> OwnedServerName { ruma::owned_server_name!("localhost") }
3005
3006fn default_database_path() -> PathBuf { "/var/lib/tuwunel".to_owned().into() }
3007
3008#[expect(clippy::as_conversions, clippy::cast_precision_loss)]
3009fn parallelism_scaled_f64(val: f64) -> f64 { val * (sys::available_parallelism() as f64) }
3010
3011fn parallelism_scaled_u32(val: u32) -> u32 {
3012	let val = val
3013		.try_into()
3014		.expect("failed to cast u32 to usize");
3015	parallelism_scaled(val)
3016		.try_into()
3017		.unwrap_or(u32::MAX)
3018}
3019
3020fn parallelism_scaled(val: usize) -> usize { val.saturating_mul(sys::available_parallelism()) }
3021
3022fn default_ldap_search_filter() -> String { "(objectClass=*)".to_owned() }
3023
3024fn default_ldap_uid_attribute() -> String { String::from("uid") }
3025
3026fn default_jwt_algorithm() -> String { "HS256".to_owned() }
3027
3028fn default_jwt_format() -> String { "HMAC".to_owned() }
3029
3030fn default_sso_grant_session_duration() -> Option<u64> { Some(300) }
3031
3032fn default_multipart_threshold() -> ByteSize { ByteSize::mib(100) }
3033
3034fn default_multipart_part_size() -> ByteSize { ByteSize::mib(10) }