mas_config/sections/
matrix.rs1use 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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
31#[serde(rename_all = "snake_case")]
32pub enum HomeserverKind {
33 #[default]
35 Synapse,
36
37 SynapseReadOnly,
42
43 SynapseLegacy,
45
46 SynapseModern,
48}
49
50#[derive(Clone, Debug)]
55pub enum Secret {
56 File(Utf8PathBuf),
57 Value(String),
58}
59
60#[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#[serde_as]
100#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
101pub struct MatrixConfig {
102 #[serde(default)]
104 pub kind: HomeserverKind,
105
106 #[serde(default = "default_homeserver")]
108 pub homeserver: String,
109
110 #[schemars(with = "SecretRaw")]
112 #[serde_as(as = "serde_with::TryFromInto<SecretRaw>")]
113 #[serde(flatten)]
114 pub secret: Secret,
115
116 #[serde(default = "default_endpoint")]
118 pub endpoint: Url,
119
120 #[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 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 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 #![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}