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