|
| 1 | +// Copyright 2024 The Matrix.org Foundation C.I.C. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +use std::{num::NonZero, time::Duration}; |
| 16 | + |
| 17 | +use governor::Quota; |
| 18 | +use schemars::JsonSchema; |
| 19 | +use serde::{de::Error as _, Deserialize, Serialize}; |
| 20 | + |
| 21 | +use crate::ConfigurationSection; |
| 22 | + |
| 23 | +/// Configuration related to sending emails |
| 24 | +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] |
| 25 | +pub struct RateLimitingConfig { |
| 26 | + /// Login-specific rate limits |
| 27 | + #[serde(default)] |
| 28 | + pub login: LoginRateLimitingConfig, |
| 29 | +} |
| 30 | + |
| 31 | +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] |
| 32 | +pub struct LoginRateLimitingConfig { |
| 33 | + /// Controls how many login attempts are permitted |
| 34 | + /// based on source address. |
| 35 | + /// This can protect against brute force login attempts. |
| 36 | + /// |
| 37 | + /// Note: this limit also applies to password checks when a user attempts to |
| 38 | + /// change their own password. |
| 39 | + #[serde(default = "default_login_per_address")] |
| 40 | + pub per_address: RateLimiterConfiguration, |
| 41 | + /// Controls how many login attempts are permitted |
| 42 | + /// based on the account that is being attempted to be logged into. |
| 43 | + /// This can protect against a distributed brute force attack |
| 44 | + /// but should be set high enough to prevent someone's account being |
| 45 | + /// casually locked out. |
| 46 | + /// |
| 47 | + /// Note: this limit also applies to password checks when a user attempts to |
| 48 | + /// change their own password. |
| 49 | + #[serde(default = "default_login_per_account")] |
| 50 | + pub per_account: RateLimiterConfiguration, |
| 51 | +} |
| 52 | + |
| 53 | +#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] |
| 54 | +pub struct RateLimiterConfiguration { |
| 55 | + /// A one-off burst of actions that the user can perform |
| 56 | + /// in one go without waiting. |
| 57 | + /// Replenishes at the rate. |
| 58 | + pub burst: u32, |
| 59 | + /// How quickly the allowance replenishes, in number of actions per second. |
| 60 | + /// Can be fractional to replenish slower. |
| 61 | + pub per_second: f64, |
| 62 | +} |
| 63 | + |
| 64 | +impl ConfigurationSection for RateLimitingConfig { |
| 65 | + const PATH: Option<&'static str> = Some("rate_limiting"); |
| 66 | + |
| 67 | + fn validate(&self, figment: &figment::Figment) -> Result<(), figment::Error> { |
| 68 | + let metadata = figment.find_metadata(Self::PATH.unwrap()); |
| 69 | + |
| 70 | + let error_on_nested_field = |
| 71 | + |mut error: figment::error::Error, container: &'static str, field: &'static str| { |
| 72 | + error.metadata = metadata.cloned(); |
| 73 | + error.profile = Some(figment::Profile::Default); |
| 74 | + error.path = vec![ |
| 75 | + Self::PATH.unwrap().to_owned(), |
| 76 | + container.to_owned(), |
| 77 | + field.to_owned(), |
| 78 | + ]; |
| 79 | + error |
| 80 | + }; |
| 81 | + |
| 82 | + // Check one limiter's configuration for errors |
| 83 | + let error_on_limiter = |
| 84 | + |limiter: &RateLimiterConfiguration| -> Option<figment::error::Error> { |
| 85 | + if limiter.burst == 0 { |
| 86 | + return Some(figment::error::Error::custom("`burst` must not be zero, as this would mean the action could never be performed")); |
| 87 | + } |
| 88 | + |
| 89 | + let recip = limiter.per_second.recip(); |
| 90 | + // period must be at least 1 nanosecond according to the governor library |
| 91 | + if recip < 1.0e-9 || !recip.is_finite() { |
| 92 | + return Some(figment::error::Error::custom( |
| 93 | + "`per_second` must be a number that is more than zero and less than 1_000_000_000 (1e9)", |
| 94 | + )); |
| 95 | + } |
| 96 | + |
| 97 | + None |
| 98 | + }; |
| 99 | + |
| 100 | + if let Some(error) = error_on_limiter(&self.login.per_address) { |
| 101 | + return Err(error_on_nested_field(error, "login", "per_address")); |
| 102 | + } |
| 103 | + if let Some(error) = error_on_limiter(&self.login.per_account) { |
| 104 | + return Err(error_on_nested_field(error, "login", "per_account")); |
| 105 | + } |
| 106 | + |
| 107 | + Ok(()) |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +impl RateLimitingConfig { |
| 112 | + pub(crate) fn is_default(config: &RateLimitingConfig) -> bool { |
| 113 | + config == &RateLimitingConfig::default() |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +impl RateLimiterConfiguration { |
| 118 | + pub fn to_quota(self) -> Option<Quota> { |
| 119 | + let reciprocal = self.per_second.recip(); |
| 120 | + if !reciprocal.is_finite() { |
| 121 | + return None; |
| 122 | + } |
| 123 | + let burst = NonZero::new(self.burst)?; |
| 124 | + Some(Quota::with_period(Duration::from_secs_f64(reciprocal))?.allow_burst(burst)) |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +fn default_login_per_address() -> RateLimiterConfiguration { |
| 129 | + RateLimiterConfiguration { |
| 130 | + burst: 3, |
| 131 | + per_second: 3.0 / 60.0, |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +fn default_login_per_account() -> RateLimiterConfiguration { |
| 136 | + RateLimiterConfiguration { |
| 137 | + burst: 1800, |
| 138 | + per_second: 1800.0 / 3600.0, |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +#[allow(clippy::derivable_impls)] // when we add some top-level ratelimiters this will not be derivable anymore |
| 143 | +impl Default for RateLimitingConfig { |
| 144 | + fn default() -> Self { |
| 145 | + RateLimitingConfig { |
| 146 | + login: LoginRateLimitingConfig::default(), |
| 147 | + } |
| 148 | + } |
| 149 | +} |
| 150 | + |
| 151 | +impl Default for LoginRateLimitingConfig { |
| 152 | + fn default() -> Self { |
| 153 | + LoginRateLimitingConfig { |
| 154 | + per_address: default_login_per_address(), |
| 155 | + per_account: default_login_per_account(), |
| 156 | + } |
| 157 | + } |
| 158 | +} |
0 commit comments