mas_config/sections/experimental.rs
1// Copyright 2024, 2025 New Vector Ltd.
2// Copyright 2023, 2024 The Matrix.org Foundation C.I.C.
3//
4// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
5// Please see LICENSE files in the repository root for full details.
6
7use std::num::NonZeroU64;
8
9use chrono::Duration;
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12use serde_with::serde_as;
13
14use crate::ConfigurationSection;
15
16fn default_true() -> bool {
17 true
18}
19
20fn default_false() -> bool {
21 false
22}
23
24fn default_token_ttl() -> Duration {
25 Duration::microseconds(5 * 60 * 1000 * 1000)
26}
27
28fn is_default_token_ttl(value: &Duration) -> bool {
29 *value == default_token_ttl()
30}
31
32/// Configuration options for the inactive session expiration feature
33#[serde_as]
34#[derive(Clone, Debug, Deserialize, JsonSchema, Serialize)]
35pub struct InactiveSessionExpirationConfig {
36 /// Time after which an inactive session is automatically finished
37 #[schemars(with = "u64", range(min = 600, max = 7_776_000))]
38 #[serde_as(as = "serde_with::DurationSeconds<i64>")]
39 pub ttl: Duration,
40
41 /// Should compatibility sessions expire after inactivity
42 #[serde(default = "default_true")]
43 pub expire_compat_sessions: bool,
44
45 /// Should OAuth 2.0 sessions expire after inactivity
46 #[serde(default = "default_true")]
47 pub expire_oauth_sessions: bool,
48
49 /// Should user sessions expire after inactivity
50 #[serde(default = "default_true")]
51 pub expire_user_sessions: bool,
52}
53
54/// Configuration sections for experimental options
55///
56/// Do not change these options unless you know what you are doing.
57#[serde_as]
58#[derive(Clone, Debug, Deserialize, JsonSchema, Serialize)]
59pub struct ExperimentalConfig {
60 /// Time-to-live of access tokens in seconds. Defaults to 5 minutes.
61 #[schemars(with = "u64", range(min = 60, max = 86400))]
62 #[serde(
63 default = "default_token_ttl",
64 skip_serializing_if = "is_default_token_ttl"
65 )]
66 #[serde_as(as = "serde_with::DurationSeconds<i64>")]
67 pub access_token_ttl: Duration,
68
69 /// Time-to-live of compatibility access tokens in seconds. Defaults to 5
70 /// minutes.
71 #[schemars(with = "u64", range(min = 60, max = 86400))]
72 #[serde(
73 default = "default_token_ttl",
74 skip_serializing_if = "is_default_token_ttl"
75 )]
76 #[serde_as(as = "serde_with::DurationSeconds<i64>")]
77 pub compat_token_ttl: Duration,
78
79 /// Experimetal feature to automatically expire inactive sessions
80 ///
81 /// Disabled by default
82 #[serde(skip_serializing_if = "Option::is_none")]
83 pub inactive_session_expiration: Option<InactiveSessionExpirationConfig>,
84
85 /// Experimental feature to show a plan management tab and iframe.
86 /// This value is passed through "as is" to the client without any
87 /// validation.
88 #[serde(skip_serializing_if = "Option::is_none")]
89 pub plan_management_iframe_uri: Option<String>,
90
91 /// Experimental feature to limit the number of application sessions per
92 /// user.
93 ///
94 /// Disabled by default.
95 #[serde(skip_serializing_if = "Option::is_none")]
96 pub session_limit: Option<SessionLimitConfig>,
97}
98
99impl Default for ExperimentalConfig {
100 fn default() -> Self {
101 Self {
102 access_token_ttl: default_token_ttl(),
103 compat_token_ttl: default_token_ttl(),
104 inactive_session_expiration: None,
105 plan_management_iframe_uri: None,
106 session_limit: None,
107 }
108 }
109}
110
111impl ExperimentalConfig {
112 pub(crate) fn is_default(&self) -> bool {
113 is_default_token_ttl(&self.access_token_ttl)
114 && is_default_token_ttl(&self.compat_token_ttl)
115 && self.inactive_session_expiration.is_none()
116 && self.plan_management_iframe_uri.is_none()
117 && self.session_limit.is_none()
118 }
119}
120
121impl ConfigurationSection for ExperimentalConfig {
122 const PATH: Option<&'static str> = Some("experimental");
123
124 fn validate(
125 &self,
126 figment: &figment::Figment,
127 ) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
128 if let Some(session_limit) = &self.session_limit {
129 session_limit.validate().map_err(|mut err| {
130 // Save the error location information in the error
131 err.metadata = figment.find_metadata(Self::PATH.unwrap()).cloned();
132 err.profile = Some(figment::Profile::Default);
133 err.path.insert(0, Self::PATH.unwrap().to_owned());
134 err.path.insert(1, "session_limit".to_owned());
135 err
136 })?;
137 }
138 Ok(())
139 }
140}
141
142/// Configuration options for the session limit feature
143#[derive(Clone, Debug, Deserialize, JsonSchema, Serialize)]
144pub struct SessionLimitConfig {
145 /// Upon login in interactive contexts (like OAuth 2.0 sessions, or
146 /// `m.login.sso` compatibility login flow), if the soft limit is reached,
147 /// it will display a policy violation screen (web UI) to remove
148 /// sessions before creating the new session.
149 ///
150 /// This is not enforced in non-interactive contexts (like
151 /// `m.login.password` login with the compatibility API) as there is no
152 /// opportunity for us to show some UI for people remove some sessions.
153 /// See [`hard_limit`] for enforcement on that side.
154 ///
155 /// This is the limit that is displayed in the UI
156 ///
157 /// [`hard_limit`]: Self::hard_limit
158 pub soft_limit: NonZeroU64,
159 /// Upon login, when `dangerous_hard_limit_eviction: false`, will refuse the
160 /// new login (policy violation error), otherwise, see
161 /// [`dangerous_hard_limit_eviction`].
162 ///
163 /// The hard limit is enforced in all contexts
164 /// (interactive/non-interactive).
165 ///
166 /// [`dangerous_hard_limit_eviction`]: Self::dangerous_hard_limit_eviction
167 pub hard_limit: NonZeroU64,
168 /// When set, only accounts with <= `max_session_threshold` sessions have
169 /// the session limits applied.
170 ///
171 /// This is most applicable in scenarios where your homeserver has many
172 /// legacy bots/scripts that login over and over (which ideally should
173 /// be using [personal access
174 /// tokens](https://github.com/element-hq/matrix-authentication-service/issues/4492))
175 /// and you want to avoid breaking their operation while maintaining some
176 /// level of sanity with the number of devices that people can have.
177 /// This will prevent anyone else from crossing the limit.
178 pub max_session_threshold: Option<NonZeroU64>,
179 /// Whether we should automatically choose the least recently used devices
180 /// to remove when the [`Self::hard_limit`] is reached; in order to
181 /// allow the new login to continue.
182 ///
183 /// Disabled by default
184 ///
185 /// WARNING: Removing sessions is a potentially damaging operation. Any
186 /// end-to-end encrypted history on the device will be lost and can only
187 /// be recovered if you have another verified active device or have a
188 /// recovery key setup.
189 ///
190 /// When using [`dangerous_hard_limit_eviction`], the [`hard_limit`] must be
191 /// at least 2 to avoid catastrophically losing encrypted history and
192 /// digital identity in pathological cases. Keep in mind this is a bare
193 /// minimum restriction and you can still run into trouble.
194 ///
195 /// This is most applicable in scenarios where your homeserver has many
196 /// legacy bots/scripts that login over and over (which ideally should
197 /// be using [personal access
198 /// tokens](https://github.com/element-hq/matrix-authentication-service/issues/4492))
199 /// and you want to avoid breaking their operation while maintaining some
200 /// level of sanity with the number of devices that people can have.
201 ///
202 /// Removing devices is a non-trivial task for some homeservers to tackle
203 /// and can cause lots of device list changes, `/sync`, federation, and
204 /// replication traffic. Consider using [`max_session_threshold`] to
205 /// limit the size of accounts that are acted upon.
206 ///
207 /// [`hard_limit`]: Self::hard_limit
208 /// [`dangerous_hard_limit_eviction`]: Self::dangerous_hard_limit_eviction
209 /// [`max_session_threshold`]: Self::max_session_threshold
210 #[serde(default = "default_false")]
211 pub dangerous_hard_limit_eviction: bool,
212}
213
214impl SessionLimitConfig {
215 fn validate(&self) -> Result<(), Box<figment::error::Error>> {
216 // We assume the `hard_limit` is >= the `soft_limit`
217 //
218 // Why? The UI only shows the soft_limit to users. If hard_limit were smaller
219 // than soft_limit, users could hit the hard_limit without ever reaching the
220 // visible soft_limit threshold — making the actual limit invisible and the
221 // failure confusing.
222 if self.hard_limit < self.soft_limit {
223 return Err(figment::error::Error::from(
224 "Session `hard_limit` must be greater than or equal to the user-facing `soft_limit`.",
225 )
226 .with_path("hard_limit")
227 .into());
228 }
229
230 // See [`SessionLimitConfig::dangerous_hard_limit_eviction`] docstring
231 if self.dangerous_hard_limit_eviction && self.hard_limit.get() < 2 {
232 return Err(figment::error::Error::from(
233 "Session `hard_limit` must be at least 2 when automatic `dangerous_hard_limit_eviction` is set. \
234 See configuration docs for more info.",
235 ).with_path("hard_limit").into());
236 }
237
238 Ok(())
239 }
240}