| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | use crate::secret; |
| 7 | use crate::store::{self, Result, Store, backend}; |
| 8 | |
| 9 | |
| 10 | |
| 11 | #[derive(Debug, Clone, Default)] |
| 12 | pub struct Smtp { |
| 13 | pub host: String, |
| 14 | pub port: u16, |
| 15 | pub username: String, |
| 16 | |
| 17 | pub from: String, |
| 18 | |
| 19 | |
| 20 | |
| 21 | pub from_name: String, |
| 22 | pub password: Option<String>, |
| 23 | } |
| 24 | |
| 25 | impl Smtp { |
| 26 | pub fn configured(&self) -> bool { |
| 27 | !self.host.is_empty() && self.port > 0 && !self.from.is_empty() |
| 28 | } |
| 29 | |
| 30 | |
| 31 | |
| 32 | pub fn from_header(&self) -> String { |
| 33 | match self.from_name.trim() { |
| 34 | "" => self.from.clone(), |
| 35 | name => format!("{name} <{}>", self.from), |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | async fn get(store: &Store, key: &str) -> Result<Option<String>> { |
| 41 | let conn = store.conn.lock().await; |
| 42 | let mut rows = conn |
| 43 | .query( |
| 44 | "SELECT value FROM settings WHERE key = ?1", |
| 45 | turso::params![key], |
| 46 | ) |
| 47 | .await |
| 48 | .map_err(backend)?; |
| 49 | let Some(row) = rows.next().await.map_err(backend)? else { |
| 50 | return Ok(None); |
| 51 | }; |
| 52 | store::opt_text(&row, 0) |
| 53 | } |
| 54 | |
| 55 | async fn set(store: &Store, key: &str, value: &str) -> Result<()> { |
| 56 | let conn = store.conn.lock().await; |
| 57 | conn.execute( |
| 58 | "INSERT INTO settings (key, value) VALUES (?1, ?2) \ |
| 59 | ON CONFLICT(key) DO UPDATE SET value = excluded.value", |
| 60 | turso::params![key, value], |
| 61 | ) |
| 62 | .await |
| 63 | .map_err(backend)?; |
| 64 | Ok(()) |
| 65 | } |
| 66 | |
| 67 | async fn remove(store: &Store, key: &str) -> Result<()> { |
| 68 | let conn = store.conn.lock().await; |
| 69 | conn.execute("DELETE FROM settings WHERE key = ?1", turso::params![key]) |
| 70 | .await |
| 71 | .map_err(backend)?; |
| 72 | Ok(()) |
| 73 | } |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | pub async fn smtp(store: &Store) -> Result<Smtp> { |
| 79 | let host = get(store, "smtp_host").await?.unwrap_or_default(); |
| 80 | let port = get(store, "smtp_port") |
| 81 | .await? |
| 82 | .and_then(|raw| raw.parse().ok()) |
| 83 | .unwrap_or(587); |
| 84 | let username = get(store, "smtp_username").await?.unwrap_or_default(); |
| 85 | let from = get(store, "smtp_from").await?.unwrap_or_default(); |
| 86 | let from_name = get(store, "smtp_from_name").await?.unwrap_or_default(); |
| 87 | let password = get(store, "smtp_password") |
| 88 | .await? |
| 89 | .and_then(|sealed| secret::open(store.key(), &sealed)) |
| 90 | .and_then(|bytes| String::from_utf8(bytes).ok()); |
| 91 | Ok(Smtp { |
| 92 | host, |
| 93 | port, |
| 94 | username, |
| 95 | from, |
| 96 | from_name, |
| 97 | password, |
| 98 | }) |
| 99 | } |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 105 | pub struct SenderCheck { |
| 106 | pub at: time::OffsetDateTime, |
| 107 | pub took_ms: u64, |
| 108 | pub error: Option<String>, |
| 109 | } |
| 110 | |
| 111 | |
| 112 | |
| 113 | |
| 114 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 115 | pub enum Standing { |
| 116 | NotConfigured, |
| 117 | Unchecked, |
| 118 | Connected { |
| 119 | at: time::OffsetDateTime, |
| 120 | took_ms: u64, |
| 121 | }, |
| 122 | Refused { |
| 123 | at: time::OffsetDateTime, |
| 124 | said: String, |
| 125 | }, |
| 126 | } |
| 127 | |
| 128 | |
| 129 | pub async fn standing(store: &Store) -> Result<Standing> { |
| 130 | if !smtp(store).await?.configured() { |
| 131 | return Ok(Standing::NotConfigured); |
| 132 | } |
| 133 | let Some(check) = last_check(store).await? else { |
| 134 | return Ok(Standing::Unchecked); |
| 135 | }; |
| 136 | Ok(match check.error { |
| 137 | None => Standing::Connected { |
| 138 | at: check.at, |
| 139 | took_ms: check.took_ms, |
| 140 | }, |
| 141 | Some(said) => Standing::Refused { at: check.at, said }, |
| 142 | }) |
| 143 | } |
| 144 | |
| 145 | |
| 146 | |
| 147 | pub async fn record_check(store: &Store, check: &SenderCheck) -> Result<()> { |
| 148 | set( |
| 149 | store, |
| 150 | "smtp_check_at", |
| 151 | &check |
| 152 | .at |
| 153 | .format(&time::format_description::well_known::Rfc3339) |
| 154 | .map_err(backend)?, |
| 155 | ) |
| 156 | .await?; |
| 157 | set(store, "smtp_check_ms", &check.took_ms.to_string()).await?; |
| 158 | set( |
| 159 | store, |
| 160 | "smtp_check_error", |
| 161 | check.error.as_deref().unwrap_or(""), |
| 162 | ) |
| 163 | .await?; |
| 164 | Ok(()) |
| 165 | } |
| 166 | |
| 167 | |
| 168 | pub async fn last_check(store: &Store) -> Result<Option<SenderCheck>> { |
| 169 | let Some(at) = get(store, "smtp_check_at").await? else { |
| 170 | return Ok(None); |
| 171 | }; |
| 172 | let at = time::OffsetDateTime::parse(&at, &time::format_description::well_known::Rfc3339) |
| 173 | .map_err(backend)?; |
| 174 | let took_ms = get(store, "smtp_check_ms") |
| 175 | .await? |
| 176 | .and_then(|raw| raw.parse().ok()) |
| 177 | .unwrap_or(0); |
| 178 | let error = get(store, "smtp_check_error") |
| 179 | .await? |
| 180 | .filter(|said| !said.is_empty()); |
| 181 | Ok(Some(SenderCheck { at, took_ms, error })) |
| 182 | } |
| 183 | |
| 184 | |
| 185 | |
| 186 | async fn clear_check(store: &Store) -> Result<()> { |
| 187 | let conn = store.conn.lock().await; |
| 188 | for key in ["smtp_check_at", "smtp_check_ms", "smtp_check_error"] { |
| 189 | conn.execute("DELETE FROM settings WHERE key = ?1", turso::params![key]) |
| 190 | .await |
| 191 | .map_err(backend)?; |
| 192 | } |
| 193 | Ok(()) |
| 194 | } |
| 195 | |
| 196 | |
| 197 | |
| 198 | pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Result<()> { |
| 199 | if smtp.host.is_empty() { |
| 200 | for key in [ |
| 201 | "smtp_host", |
| 202 | "smtp_port", |
| 203 | "smtp_username", |
| 204 | "smtp_from", |
| 205 | "smtp_from_name", |
| 206 | "smtp_check_at", |
| 207 | "smtp_check_ms", |
| 208 | "smtp_check_error", |
| 209 | ] { |
| 210 | remove(store, key).await?; |
| 211 | } |
| 212 | return Ok(()); |
| 213 | } |
| 214 | |
| 215 | clear_check(store).await?; |
| 216 | set(store, "smtp_host", &smtp.host).await?; |
| 217 | set(store, "smtp_port", &smtp.port.to_string()).await?; |
| 218 | set(store, "smtp_username", &smtp.username).await?; |
| 219 | set(store, "smtp_from", &smtp.from).await?; |
| 220 | set(store, "smtp_from_name", &smtp.from_name).await?; |
| 221 | if let Some(password) = password |
| 222 | && !password.is_empty() |
| 223 | { |
| 224 | set( |
| 225 | store, |
| 226 | "smtp_password", |
| 227 | &secret::seal(store.key(), password.as_bytes()), |
| 228 | ) |
| 229 | .await?; |
| 230 | } |
| 231 | Ok(()) |
| 232 | } |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 238 | pub struct Policy { |
| 239 | pub invite_days: i64, |
| 240 | pub session_days: i64, |
| 241 | pub max_sessions: i64, |
| 242 | pub pending_minutes: i64, |
| 243 | pub reset_minutes: i64, |
| 244 | pub login_attempts_per_hour: i64, |
| 245 | } |
| 246 | |
| 247 | impl Default for Policy { |
| 248 | fn default() -> Self { |
| 249 | Self { |
| 250 | invite_days: 7, |
| 251 | session_days: 30, |
| 252 | max_sessions: 5, |
| 253 | pending_minutes: 10, |
| 254 | reset_minutes: 60, |
| 255 | login_attempts_per_hour: 10, |
| 256 | } |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | async fn number(store: &Store, key: &str, default: i64) -> Result<i64> { |
| 261 | Ok(get(store, key) |
| 262 | .await? |
| 263 | .and_then(|raw| raw.parse().ok()) |
| 264 | .unwrap_or(default)) |
| 265 | } |
| 266 | |
| 267 | |
| 268 | pub async fn policy(store: &Store) -> Result<Policy> { |
| 269 | let defaults = Policy::default(); |
| 270 | Ok(Policy { |
| 271 | invite_days: number(store, "invite_days", defaults.invite_days).await?, |
| 272 | session_days: number(store, "session_days", defaults.session_days).await?, |
| 273 | max_sessions: number(store, "max_sessions", defaults.max_sessions).await?, |
| 274 | pending_minutes: number(store, "pending_minutes", defaults.pending_minutes).await?, |
| 275 | reset_minutes: number(store, "reset_minutes", defaults.reset_minutes).await?, |
| 276 | login_attempts_per_hour: number( |
| 277 | store, |
| 278 | "login_attempts_per_hour", |
| 279 | defaults.login_attempts_per_hour, |
| 280 | ) |
| 281 | .await?, |
| 282 | }) |
| 283 | } |
| 284 | |
| 285 | |
| 286 | |
| 287 | |
| 288 | pub async fn set_policy(store: &Store, policy: &Policy) -> Result<()> { |
| 289 | let defaults = Policy::default(); |
| 290 | let clamp = |value: i64, default: i64| if value >= 1 { value } else { default }; |
| 291 | set( |
| 292 | store, |
| 293 | "invite_days", |
| 294 | &clamp(policy.invite_days, defaults.invite_days).to_string(), |
| 295 | ) |
| 296 | .await?; |
| 297 | set( |
| 298 | store, |
| 299 | "session_days", |
| 300 | &clamp(policy.session_days, defaults.session_days).to_string(), |
| 301 | ) |
| 302 | .await?; |
| 303 | set( |
| 304 | store, |
| 305 | "max_sessions", |
| 306 | &clamp(policy.max_sessions, defaults.max_sessions).to_string(), |
| 307 | ) |
| 308 | .await?; |
| 309 | set( |
| 310 | store, |
| 311 | "pending_minutes", |
| 312 | &clamp(policy.pending_minutes, defaults.pending_minutes).to_string(), |
| 313 | ) |
| 314 | .await?; |
| 315 | set( |
| 316 | store, |
| 317 | "reset_minutes", |
| 318 | &clamp(policy.reset_minutes, defaults.reset_minutes).to_string(), |
| 319 | ) |
| 320 | .await?; |
| 321 | set( |
| 322 | store, |
| 323 | "login_attempts_per_hour", |
| 324 | &clamp( |
| 325 | policy.login_attempts_per_hour, |
| 326 | defaults.login_attempts_per_hour, |
| 327 | ) |
| 328 | .to_string(), |
| 329 | ) |
| 330 | .await?; |
| 331 | Ok(()) |
| 332 | } |
| 333 | |
| 334 | |
| 335 | pub async fn invite_days(store: &Store) -> Result<i64> { |
| 336 | number(store, "invite_days", Policy::default().invite_days).await |
| 337 | } |
| 338 | |
| 339 | |
| 340 | pub async fn pending_minutes(store: &Store) -> Result<i64> { |
| 341 | number(store, "pending_minutes", Policy::default().pending_minutes).await |
| 342 | } |
| 343 | |
| 344 | |
| 345 | pub async fn reset_minutes(store: &Store) -> Result<i64> { |
| 346 | number(store, "reset_minutes", Policy::default().reset_minutes).await |
| 347 | } |
| 348 | |
| 349 | |
| 350 | pub async fn login_attempts_per_hour(store: &Store) -> Result<i64> { |
| 351 | number( |
| 352 | store, |
| 353 | "login_attempts_per_hour", |
| 354 | Policy::default().login_attempts_per_hour, |
| 355 | ) |
| 356 | .await |
| 357 | } |
| 358 | |
| 359 | #[cfg(test)] |
| 360 | mod tests { |
| 361 | use super::*; |
| 362 | use std::path::Path; |
| 363 | |
| 364 | #[tokio::test] |
| 365 | async fn smtp_roundtrip_with_sealed_password() { |
| 366 | let store = Store::open(Path::new(":memory:")).await.unwrap(); |
| 367 | assert!(!smtp(&store).await.unwrap().configured()); |
| 368 | assert_eq!(smtp(&store).await.unwrap().port, 587); |
| 369 | |
| 370 | let value = Smtp { |
| 371 | host: "smtp.example.com".into(), |
| 372 | port: 465, |
| 373 | username: "im".into(), |
| 374 | from: "auth@example.com".into(), |
| 375 | from_name: "im".into(), |
| 376 | password: None, |
| 377 | }; |
| 378 | set_smtp(&store, &value, Some("s3cret")).await.unwrap(); |
| 379 | let read = smtp(&store).await.unwrap(); |
| 380 | assert!(read.configured()); |
| 381 | assert_eq!(read.password.as_deref(), Some("s3cret")); |
| 382 | |
| 383 | |
| 384 | set_smtp(&store, &value, None).await.unwrap(); |
| 385 | assert_eq!( |
| 386 | smtp(&store).await.unwrap().password.as_deref(), |
| 387 | Some("s3cret") |
| 388 | ); |
| 389 | |
| 390 | |
| 391 | set_smtp(&store, &Smtp::default(), None).await.unwrap(); |
| 392 | |
| 393 | assert!(!smtp(&store).await.unwrap().configured()); |
| 394 | } |
| 395 | |
| 396 | #[tokio::test] |
| 397 | async fn sealed_password_needs_the_key() { |
| 398 | let dir = tempfile::tempdir().unwrap(); |
| 399 | let path = dir.path().join("im.db"); |
| 400 | { |
| 401 | let store = Store::open(&path).await.unwrap(); |
| 402 | let value = Smtp { |
| 403 | host: "smtp.example.com".into(), |
| 404 | port: 465, |
| 405 | username: String::new(), |
| 406 | from: "a@b.c".into(), |
| 407 | from_name: String::new(), |
| 408 | password: None, |
| 409 | }; |
| 410 | set_smtp(&store, &value, Some("s3cret")).await.unwrap(); |
| 411 | } |
| 412 | |
| 413 | let sealed = { |
| 414 | let store = Store::open(&path).await.unwrap(); |
| 415 | super::get(&store, "smtp_password").await.unwrap().unwrap() |
| 416 | }; |
| 417 | assert!(secret::is_sealed(&sealed)); |
| 418 | let wrong_key = [9u8; 32]; |
| 419 | assert!(secret::open(&wrong_key, &sealed).is_none()); |
| 420 | } |
| 421 | |
| 422 | #[tokio::test] |
| 423 | async fn check_records_and_a_save_wipes_it() { |
| 424 | let store = Store::open(Path::new(":memory:")).await.unwrap(); |
| 425 | assert_eq!(standing(&store).await.unwrap(), Standing::NotConfigured); |
| 426 | |
| 427 | let value = Smtp { |
| 428 | host: "smtp.example.com".into(), |
| 429 | port: 587, |
| 430 | username: "auth@example.com".into(), |
| 431 | from: "auth@example.com".into(), |
| 432 | from_name: "im".into(), |
| 433 | password: None, |
| 434 | }; |
| 435 | set_smtp(&store, &value, Some("s3cret")).await.unwrap(); |
| 436 | assert_eq!(standing(&store).await.unwrap(), Standing::Unchecked); |
| 437 | |
| 438 | record_check( |
| 439 | &store, |
| 440 | &SenderCheck { |
| 441 | at: time::OffsetDateTime::now_utc(), |
| 442 | took_ms: 142, |
| 443 | error: None, |
| 444 | }, |
| 445 | ) |
| 446 | .await |
| 447 | .unwrap(); |
| 448 | assert!(matches!( |
| 449 | standing(&store).await.unwrap(), |
| 450 | Standing::Connected { took_ms: 142, .. } |
| 451 | )); |
| 452 | |
| 453 | record_check( |
| 454 | &store, |
| 455 | &SenderCheck { |
| 456 | at: time::OffsetDateTime::now_utc(), |
| 457 | took_ms: 0, |
| 458 | error: Some("the mail server did not answer in time".into()), |
| 459 | }, |
| 460 | ) |
| 461 | .await |
| 462 | .unwrap(); |
| 463 | assert!(matches!( |
| 464 | standing(&store).await.unwrap(), |
| 465 | Standing::Refused { .. } |
| 466 | )); |
| 467 | |
| 468 | |
| 469 | set_smtp(&store, &value, None).await.unwrap(); |
| 470 | assert_eq!(standing(&store).await.unwrap(), Standing::Unchecked); |
| 471 | assert!(last_check(&store).await.unwrap().is_none()); |
| 472 | } |
| 473 | |
| 474 | #[tokio::test] |
| 475 | async fn policy_defaults_roundtrip_and_zero_clamps_to_default() { |
| 476 | let store = Store::open(Path::new(":memory:")).await.unwrap(); |
| 477 | |
| 478 | |
| 479 | assert_eq!(policy(&store).await.unwrap(), Policy::default()); |
| 480 | assert_eq!(policy(&store).await.unwrap().max_sessions, 5); |
| 481 | |
| 482 | |
| 483 | let value = Policy { max_sessions: 2, ..Policy::default() }; |
| 484 | set_policy(&store, &value).await.unwrap(); |
| 485 | assert_eq!(policy(&store).await.unwrap().max_sessions, 2); |
| 486 | |
| 487 | |
| 488 | |
| 489 | let value = Policy { max_sessions: 0, ..Policy::default() }; |
| 490 | set_policy(&store, &value).await.unwrap(); |
| 491 | assert_eq!(policy(&store).await.unwrap().max_sessions, 5); |
| 492 | let value = Policy { max_sessions: -3, ..Policy::default() }; |
| 493 | set_policy(&store, &value).await.unwrap(); |
| 494 | assert_eq!(policy(&store).await.unwrap().max_sessions, 5); |
| 495 | } |
| 496 | } |