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), if the
146 /// soft limit is reached, it will display a policy violation screen
147 /// (web UI) to remove sessions before creating the new session.
148 ///
149 /// This is not enforced in non-interactive contexts (like the legacy
150 /// compability login API) as there is no opportunity for us to show
151 /// some UI for people remove some sessions. See [`hard_limit`] for
152 /// enforcement on that side.
153 ///
154 /// [`hard_limit`]: Self::hard_limit
155 pub soft_limit: NonZeroU64,
156 /// Upon login, when `dangerous_hard_limit_eviction: false`, will refuse the
157 /// new login (policy violation error), otherwise, see
158 /// [`dangerous_hard_limit_eviction`].
159 ///
160 /// The hard limit is enforced in all contexts
161 /// (interactive/non-interactive).
162 ///
163 /// [`dangerous_hard_limit_eviction`]: Self::dangerous_hard_limit_eviction
164 pub hard_limit: NonZeroU64,
165 /// Whether we should automatically choose the least recently used devices
166 /// to remove when the [`Self::hard_limit`] is reached; in order to
167 /// allow the new login to continue.
168 ///
169 /// Disabled by default
170 ///
171 /// WARNING: Removing sessions is a potentially damaging operation. Any
172 /// end-to-end encrypted history on the device will be lost and can only
173 /// be recovered if you have another verified active device or have a
174 /// recovery key setup.
175 ///
176 /// When using [`dangerous_hard_limit_eviction`], the [`hard_limit`] must be
177 /// at least 2 to avoid catastrophically losing encrypted history and
178 /// digital identity in pathological cases. Keep in mind this is a bare
179 /// minimum restriction and you can still run into trouble.
180 ///
181 /// This is most applicable in scenarios where your homeserver has many
182 /// legacy bots/scripts that login over and over (which ideally should
183 /// be using [personal access
184 /// tokens](https://github.com/element-hq/matrix-authentication-service/issues/4492))
185 /// and you want to avoid breaking their operation while maintaining some
186 /// level of sanity with the number of devices that people can have.
187 ///
188 /// [`hard_limit`]: Self::hard_limit
189 /// [`dangerous_hard_limit_eviction`]: Self::dangerous_hard_limit_eviction
190 #[serde(default = "default_false")]
191 pub dangerous_hard_limit_eviction: bool,
192}
193
194impl SessionLimitConfig {
195 fn validate(&self) -> Result<(), Box<figment::error::Error>> {
196 // See [`SessionLimitConfig::dangerous_hard_limit_eviction`] docstring
197 if self.dangerous_hard_limit_eviction && self.hard_limit.get() < 2 {
198 return Err(figment::error::Error::from(
199 "Session `hard_limit` must be at least 2 when automatic `dangerous_hard_limit_eviction` is set. \
200 See configuration docs for more info.",
201 ).with_path("hard_limit").into());
202 }
203
204 Ok(())
205 }
206}