Skip to main content

mas_config/sections/
matrix.rs

1// Copyright 2026 Element Creations Ltd.
2// Copyright 2024, 2025 New Vector Ltd.
3// Copyright 2022-2024 The Matrix.org Foundation C.I.C.
4//
5// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
6// Please see LICENSE files in the repository root for full details.
7
8use anyhow::bail;
9use camino::Utf8PathBuf;
10use rand::{
11    RngExt,
12    distr::{Alphanumeric, SampleString},
13};
14use schemars::JsonSchema;
15use serde::{Deserialize, Serialize};
16use serde_with::serde_as;
17use url::Url;
18
19use super::ConfigurationSection;
20
21fn default_homeserver() -> String {
22    "localhost:8008".to_owned()
23}
24
25fn default_endpoint() -> Url {
26    Url::parse("http://localhost:8008/").unwrap()
27}
28
29/// The kind of homeserver it is.
30#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
31#[serde(rename_all = "snake_case")]
32pub enum HomeserverKind {
33    /// Homeserver is Synapse, version 1.135.0 or newer
34    #[default]
35    Synapse,
36
37    /// Homeserver is Synapse, version 1.135.0 or newer, in read-only mode
38    ///
39    /// This is meant for testing rolling out Matrix Authentication Service with
40    /// no risk of writing data to the homeserver.
41    SynapseReadOnly,
42
43    /// Homeserver is Synapse, using the legacy API
44    SynapseLegacy,
45
46    /// Homeserver is Synapse, with the modern API available (>= 1.135.0)
47    SynapseModern,
48}
49
50/// Shared secret between MAS and the homeserver.
51///
52/// It either holds the secret value directly or references a file where the
53/// secret is stored.
54#[derive(Clone, Debug)]
55pub enum Secret {
56    File(Utf8PathBuf),
57    Value(String),
58}
59
60/// Secret fields as serialized in JSON.
61#[derive(JsonSchema, Serialize, Deserialize, Clone, Debug)]
62struct SecretRaw {
63    #[schemars(with = "Option<String>")]
64    #[serde(skip_serializing_if = "Option::is_none")]
65    secret_file: Option<Utf8PathBuf>,
66    #[serde(skip_serializing_if = "Option::is_none")]
67    secret: Option<String>,
68}
69
70impl TryFrom<SecretRaw> for Secret {
71    type Error = anyhow::Error;
72
73    fn try_from(value: SecretRaw) -> Result<Self, Self::Error> {
74        match (value.secret, value.secret_file) {
75            (None, None) => bail!("Missing `secret` or `secret_file`"),
76            (None, Some(path)) => Ok(Secret::File(path)),
77            (Some(secret), None) => Ok(Secret::Value(secret)),
78            (Some(_), Some(_)) => bail!("Cannot specify both `secret` and `secret_file`"),
79        }
80    }
81}
82
83impl From<Secret> for SecretRaw {
84    fn from(value: Secret) -> Self {
85        match value {
86            Secret::File(path) => SecretRaw {
87                secret_file: Some(path),
88                secret: None,
89            },
90            Secret::Value(secret) => SecretRaw {
91                secret_file: None,
92                secret: Some(secret),
93            },
94        }
95    }
96}
97
98/// Configuration related to the Matrix homeserver
99#[serde_as]
100#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
101pub struct MatrixConfig {
102    /// The kind of homeserver it is.
103    #[serde(default)]
104    pub kind: HomeserverKind,
105
106    /// The server name of the homeserver.
107    #[serde(default = "default_homeserver")]
108    pub homeserver: String,
109
110    /// Shared secret to use for calls to the admin API
111    #[schemars(with = "SecretRaw")]
112    #[serde_as(as = "serde_with::TryFromInto<SecretRaw>")]
113    #[serde(flatten)]
114    pub secret: Secret,
115
116    /// The base URL of the homeserver's client API
117    #[serde(default = "default_endpoint")]
118    pub endpoint: Url,
119
120    /// Path to a Unix socket through which to connect to the homeserver
121    ///
122    /// When set, `endpoint` is not used to locate the homeserver. It still
123    /// determines the scheme, the `Host` header and the base path of the
124    /// requests.
125    #[serde(skip_serializing_if = "Option::is_none")]
126    #[schemars(with = "Option<String>")]
127    pub socket: Option<Utf8PathBuf>,
128}
129
130impl ConfigurationSection for MatrixConfig {
131    const PATH: Option<&'static str> = Some("matrix");
132}
133
134impl MatrixConfig {
135    /// Returns the shared secret.
136    ///
137    /// If `secret_file` was given, the secret is read from that file.
138    ///
139    /// # Errors
140    ///
141    /// Returns an error when the shared secret could not be read from file.
142    pub async fn secret(&self) -> anyhow::Result<String> {
143        Ok(match &self.secret {
144            Secret::File(path) => {
145                let raw = tokio::fs::read_to_string(path).await?;
146                // Trim the secret when read from file to match Synapse's behaviour
147                raw.trim().to_string()
148            }
149            Secret::Value(secret) => secret.clone(),
150        })
151    }
152
153    pub(crate) fn generate<R>(mut rng: R) -> Self
154    where
155        R: RngExt + Send,
156    {
157        Self {
158            kind: HomeserverKind::default(),
159            homeserver: default_homeserver(),
160            secret: Secret::Value(Alphanumeric.sample_string(&mut rng, 32)),
161            endpoint: default_endpoint(),
162            socket: None,
163        }
164    }
165
166    pub(crate) fn test() -> Self {
167        Self {
168            kind: HomeserverKind::default(),
169            homeserver: default_homeserver(),
170            secret: Secret::Value("test".to_owned()),
171            endpoint: default_endpoint(),
172            socket: None,
173        }
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    // The closures passed to `Jail::expect_with` return `figment::Error`, which is
180    // large, and we can't change figment's API.
181    #![expect(clippy::result_large_err)]
182
183    use figment::{
184        Figment, Jail,
185        providers::{Format, Yaml},
186    };
187    use tokio::{runtime::Handle, task};
188
189    use super::*;
190
191    #[tokio::test]
192    async fn load_config() {
193        task::spawn_blocking(|| {
194            Jail::expect_with(|jail| {
195                jail.create_file(
196                    "config.yaml",
197                    r"
198                        matrix:
199                          homeserver: matrix.org
200                          secret_file: secret
201                    ",
202                )?;
203                jail.create_file("secret", r"m472!x53c237")?;
204
205                let config = Figment::new()
206                    .merge(Yaml::file("config.yaml"))
207                    .extract_inner::<MatrixConfig>("matrix")?;
208
209                Handle::current().block_on(async move {
210                    assert_eq!(&config.homeserver, "matrix.org");
211                    assert!(matches!(config.secret, Secret::File(ref p) if p == "secret"));
212                    assert_eq!(config.socket, None);
213                    assert_eq!(config.secret().await.unwrap(), "m472!x53c237");
214                });
215
216                Ok(())
217            });
218        })
219        .await
220        .unwrap();
221    }
222
223    #[tokio::test]
224    async fn load_config_inline_secrets() {
225        task::spawn_blocking(|| {
226            Jail::expect_with(|jail| {
227                jail.create_file(
228                    "config.yaml",
229                    r"
230                        matrix:
231                          homeserver: matrix.org
232                          secret: m472!x53c237
233                          socket: /run/synapse/main.sock
234                    ",
235                )?;
236
237                let config = Figment::new()
238                    .merge(Yaml::file("config.yaml"))
239                    .extract_inner::<MatrixConfig>("matrix")?;
240
241                Handle::current().block_on(async move {
242                    assert_eq!(&config.homeserver, "matrix.org");
243                    assert!(matches!(config.secret, Secret::Value(ref v) if v == "m472!x53c237"));
244                    assert_eq!(
245                        config.socket.as_deref(),
246                        Some("/run/synapse/main.sock".into())
247                    );
248                    assert_eq!(config.secret().await.unwrap(), "m472!x53c237");
249                });
250
251                Ok(())
252            });
253        })
254        .await
255        .unwrap();
256    }
257}