syn2mas/synapse_reader/config/
mod.rs1mod oidc;
7
8use std::collections::BTreeMap;
9
10use camino::Utf8PathBuf;
11use chrono::{DateTime, Utc};
12use figment::providers::{Format, Yaml};
13use mas_config::{PasswordAlgorithm, PasswordHashingScheme};
14use rand::Rng;
15use serde::Deserialize;
16use sqlx::postgres::PgConnectOptions;
17use tracing::warn;
18use url::Url;
19
20pub use self::oidc::OidcProvider;
21
22#[derive(Deserialize)]
28#[expect(clippy::struct_excessive_bools)]
29pub struct Config {
30 pub database: DatabaseSection,
31
32 #[serde(default)]
33 pub password_config: PasswordSection,
34
35 pub bcrypt_rounds: Option<u32>,
36
37 #[serde(default)]
38 pub allow_guest_access: bool,
39
40 #[serde(default)]
41 pub enable_registration: bool,
42
43 #[serde(default)]
44 pub enable_registration_captcha: bool,
45 pub recaptcha_public_key: Option<String>,
46 pub recaptcha_private_key: Option<String>,
47
48 #[serde(default)]
51 pub enable_3pid_changes: Option<bool>,
52
53 #[serde(default = "default_true")]
54 enable_set_display_name: bool,
55
56 #[serde(default)]
57 pub user_consent: Option<UserConsentSection>,
58
59 #[serde(default)]
60 pub registrations_require_3pid: Vec<String>,
61
62 #[serde(default)]
63 pub registration_requires_token: bool,
64
65 pub registration_shared_secret: Option<String>,
66
67 #[serde(default)]
68 pub login_via_existing_session: EnableableSection,
69
70 #[serde(default)]
71 pub cas_config: EnableableSection,
72
73 #[serde(default)]
74 pub saml2_config: EnableableSection,
75
76 #[serde(default)]
77 pub jwt_config: EnableableSection,
78
79 #[serde(default)]
80 pub oidc_config: Option<OidcProvider>,
81
82 #[serde(default)]
83 pub oidc_providers: Vec<OidcProvider>,
84
85 pub server_name: String,
86
87 pub public_baseurl: Option<Url>,
88}
89
90impl Config {
91 pub fn load(files: &[Utf8PathBuf]) -> Result<Config, figment::Error> {
98 let mut figment = figment::Figment::new();
99 for file in files {
100 figment = figment.merge(Yaml::file(file));
105 }
106 figment.extract::<Config>()
107 }
108
109 #[must_use]
117 pub fn all_oidc_providers(&self) -> BTreeMap<String, OidcProvider> {
118 let mut out = BTreeMap::new();
119
120 if let Some(provider) = &self.oidc_config {
121 if provider.has_required_fields() {
122 let mut provider = provider.clone();
123 let idp_id = provider.idp_id.take().unwrap_or("oidc".to_owned());
125 provider.idp_id = Some(idp_id.clone());
126 out.insert(idp_id, provider);
127 }
128 }
129
130 for provider in &self.oidc_providers {
131 let mut provider = provider.clone();
132 let idp_id = match provider.idp_id.take() {
133 None => "oidc".to_owned(),
134 Some(idp_id) if idp_id == "oidc" => idp_id,
135 Some(idp_id) => format!("oidc-{idp_id}"),
137 };
138 provider.idp_id = Some(idp_id.clone());
139 out.insert(idp_id, provider);
140 }
141
142 out
143 }
144
145 #[must_use]
147 pub fn adjust_mas_config(
148 self,
149 mut mas_config: mas_config::RootConfig,
150 rng: &mut impl Rng,
151 now: DateTime<Utc>,
152 ) -> mas_config::RootConfig {
153 let providers = self.all_oidc_providers();
154 for provider in providers.into_values() {
155 let Some(mas_provider_config) = provider.into_mas_config(rng, now) else {
156 warn!("Could not convert OIDC provider to MAS config");
158 continue;
159 };
160
161 mas_config
162 .upstream_oauth2
163 .providers
164 .push(mas_provider_config);
165 }
166
167 if let Some(enable_3pid_changes) = self.enable_3pid_changes {
169 mas_config.account.email_change_allowed = enable_3pid_changes;
170 }
171 mas_config.account.displayname_change_allowed = self.enable_set_display_name;
172 if self.password_config.enabled {
173 mas_config.passwords.enabled = true;
174 mas_config.passwords.schemes = vec![
175 PasswordHashingScheme {
177 version: 1,
178 algorithm: PasswordAlgorithm::Bcrypt,
179 cost: self.bcrypt_rounds,
180 secret: self.password_config.pepper,
181 secret_file: None,
182 },
183 PasswordHashingScheme {
186 version: 2,
187 algorithm: PasswordAlgorithm::default(),
188 cost: None,
189 secret: None,
190 secret_file: None,
191 },
192 ];
193
194 mas_config.account.password_registration_enabled = self.enable_registration;
195 } else {
196 mas_config.passwords.enabled = false;
197 }
198
199 if self.enable_registration_captcha {
200 mas_config.captcha.service = Some(mas_config::CaptchaServiceKind::RecaptchaV2);
201 mas_config.captcha.site_key = self.recaptcha_public_key;
202 mas_config.captcha.secret_key = self.recaptcha_private_key;
203 }
204
205 mas_config.matrix.homeserver = self.server_name;
206 if let Some(public_baseurl) = self.public_baseurl {
207 mas_config.matrix.endpoint = public_baseurl;
208 }
209
210 mas_config
211 }
212}
213
214#[derive(Deserialize)]
218pub struct DatabaseSection {
219 pub name: String,
223 #[serde(default)]
224 pub args: DatabaseArgsSuboption,
225}
226
227pub const SYNAPSE_DATABASE_DRIVER_NAME_PSYCOPG2: &str = "psycopg2";
229pub const SYNAPSE_DATABASE_DRIVER_NAME_SQLITE3: &str = "sqlite3";
231
232impl DatabaseSection {
233 pub fn to_sqlx_postgres(&self) -> Result<PgConnectOptions, anyhow::Error> {
246 if self.name != SYNAPSE_DATABASE_DRIVER_NAME_PSYCOPG2 {
247 anyhow::bail!("syn2mas does not support the {} database driver", self.name);
248 }
249
250 if self.args.database.is_some() && self.args.dbname.is_some() {
251 anyhow::bail!(
252 "Only one of `database` and `dbname` may be specified in the Synapse database configuration, not both."
253 );
254 }
255
256 let mut opts = PgConnectOptions::new().application_name("syn2mas-synapse");
257
258 if let Some(host) = &self.args.host {
259 opts = opts.host(host);
260 }
261 if let Some(port) = self.args.port {
262 opts = opts.port(port);
263 }
264 if let Some(dbname) = &self.args.dbname {
265 opts = opts.database(dbname);
266 }
267 if let Some(database) = &self.args.database {
268 opts = opts.database(database);
269 }
270 if let Some(user) = &self.args.user {
271 opts = opts.username(user);
272 }
273 if let Some(password) = &self.args.password {
274 opts = opts.password(password);
275 }
276
277 Ok(opts)
278 }
279}
280
281#[derive(Deserialize, Default)]
285pub struct DatabaseArgsSuboption {
286 pub user: Option<String>,
287 pub password: Option<String>,
288 pub dbname: Option<String>,
289 pub database: Option<String>,
291 pub host: Option<String>,
292 pub port: Option<u16>,
293}
294
295#[derive(Deserialize)]
299pub struct PasswordSection {
300 #[serde(default = "default_true")]
301 pub enabled: bool,
302 #[serde(default = "default_true")]
303 pub localdb_enabled: bool,
304 pub pepper: Option<String>,
305}
306
307impl Default for PasswordSection {
308 fn default() -> Self {
309 PasswordSection {
310 enabled: true,
311 localdb_enabled: true,
312 pepper: None,
313 }
314 }
315}
316
317#[derive(Default, Deserialize)]
320pub struct EnableableSection {
321 #[serde(default)]
322 pub enabled: bool,
323}
324
325fn default_true() -> bool {
326 true
327}
328
329#[cfg(test)]
330mod test {
331 use sqlx::postgres::PgConnectOptions;
332
333 use super::{DatabaseArgsSuboption, DatabaseSection};
334
335 #[test]
336 fn test_to_sqlx_postgres() {
337 #[track_caller]
338 #[expect(clippy::needless_pass_by_value)]
339 fn assert_eq_options(config: DatabaseSection, uri: &str) {
340 let config_connect_options = config
341 .to_sqlx_postgres()
342 .expect("no connection options generated by config");
343 let uri_connect_options: PgConnectOptions = uri
344 .parse()
345 .expect("example URI did not parse as PgConnectionOptions");
346
347 assert_eq!(
348 config_connect_options.get_host(),
349 uri_connect_options.get_host()
350 );
351 assert_eq!(
352 config_connect_options.get_port(),
353 uri_connect_options.get_port()
354 );
355 assert_eq!(
356 config_connect_options.get_username(),
357 uri_connect_options.get_username()
358 );
359 assert_eq!(
361 config_connect_options.get_database(),
362 uri_connect_options.get_database()
363 );
364 }
365
366 assert!(
368 DatabaseSection {
369 name: "sqlite3".to_owned(),
370 args: DatabaseArgsSuboption::default(),
371 }
372 .to_sqlx_postgres()
373 .is_err()
374 );
375
376 assert!(
378 DatabaseSection {
379 name: "psycopg2".to_owned(),
380 args: DatabaseArgsSuboption {
381 user: Some("synapse_user".to_owned()),
382 password: Some("verysecret".to_owned()),
383 dbname: Some("synapse_db".to_owned()),
384 database: Some("synapse_db".to_owned()),
385 host: Some("synapse-db.example.com".to_owned()),
386 port: Some(42),
387 },
388 }
389 .to_sqlx_postgres()
390 .is_err()
391 );
392
393 assert_eq_options(
394 DatabaseSection {
395 name: "psycopg2".to_owned(),
396 args: DatabaseArgsSuboption::default(),
397 },
398 "postgresql:///",
399 );
400 assert_eq_options(
401 DatabaseSection {
402 name: "psycopg2".to_owned(),
403 args: DatabaseArgsSuboption {
404 user: Some("synapse_user".to_owned()),
405 password: Some("verysecret".to_owned()),
406 dbname: Some("synapse_db".to_owned()),
407 database: None,
408 host: Some("synapse-db.example.com".to_owned()),
409 port: Some(42),
410 },
411 },
412 "postgresql://synapse_user:verysecret@synapse-db.example.com:42/synapse_db",
413 );
414 }
415}
416
417#[derive(Deserialize)]
420pub struct UserConsentSection {}