//! The state shared by every route. Topcoat hands it to each handler through the app context. use std::sync::{Arc, PoisonError, RwLock}; use std::time::{Duration, Instant}; use im_core::config::{Config, PolicyConfig}; use im_core::store::Store; use tokio::sync::{Semaphore, watch}; use crate::api::directory::StreamSlots; use crate::backups::BackupTrigger; use crate::live::LiveHub; use crate::throttle::{TWO_FACTOR_DAY_LIMIT, TWO_FACTOR_USER_LIMIT, Throttle, two_factor_key}; /// Everything a request handler reaches through the app context. Every field is cheap to clone. #[derive(Clone)] pub struct AppState { /// The configuration the process booted with. pub config: Arc, /// The sign-in policy in effect: the file values, with the settings saved in the admin UI layered on /// top. Read it through [`AppState::policy`]; the admin settings page replaces it while the server /// runs. pub policy_live: Arc>, /// The database. Reads go to a pooled reader and writes to the single writer. pub store: Store, /// The instance key (`im.key`). Seals secrets at rest. pub key: Arc<[u8; 32]>, /// The change counters of the live pages. pub live: Arc, /// Asks the backup worker for a run now (the admin health page). Shared with the worker. pub backup: Arc, /// Failed sign-in and second-factor counters. pub throttle: Arc, /// Failed second-factor checks per account, one day window (see `throttle::TWO_FACTOR_DAY_LIMIT`). pub two_factor_days: Arc, /// Profile photo uploads per account, one hour window (see `throttle::PHOTO_UPLOAD_LIMIT`). pub photo_uploads: Arc, /// Email-change requests per account, one hour window (see `throttle::EMAIL_CHANGE_LIMIT`). pub email_changes: Arc, /// Per-minute counters: code issuances per session, token requests per client, and the audit of /// failed sign-ins (see the limits in `throttle`). pub per_minute: Arc, /// The open directory streams of each machine client. pub stream_slots: Arc, /// The open anonymous `/-/alive` streams, at most [`MAX_ANONYMOUS_STREAMS`]. pub anonymous_streams: Arc, /// Set when the process is stopping. Long-lived streams end when it is, so the server can drain. pub stop: watch::Receiver, /// Held by every change to the saved policy, from the write to the refresh of `policy_live`. Two saves /// then run one after the other, and the in-memory policy always matches what the database last committed. pub settings_lock: Arc>, /// Held by every profile photo change, from the row write to the file write or removal, so that a /// removal cannot delete the file a parallel upload has just put in place. pub photo_lock: Arc>, } impl AppState { /// A copy of the policy in effect now. Cheap: the policy is a handful of numbers. pub fn policy(&self) -> PolicyConfig { self.policy_live .read() .unwrap_or_else(PoisonError::into_inner) .clone() } /// Replaces the policy in effect. Used when an administrator saves the settings page. pub fn set_policy(&self, policy: PolicyConfig) { *self .policy_live .write() .unwrap_or_else(PoisonError::into_inner) = policy; } /// Counts one second-factor attempt of `user_id` against both the short and the day window. Nothing /// is counted when either refuses; the wait of the refusing window comes back. pub fn reserve_second_factor(&self, user_id: &str) -> Result<(), Duration> { let key = two_factor_key(user_id); let now = Instant::now(); self.two_factor_days .reserve(&key, TWO_FACTOR_DAY_LIMIT, now)?; self.throttle .reserve(&key, TWO_FACTOR_USER_LIMIT, now) .inspect_err(|_| self.two_factor_days.refund(&key)) } /// Forgets the second-factor failures of `user_id` after a correct code: the short window is cleared, /// and the day window gives back the attempt just counted. pub fn clear_second_factor(&self, user_id: &str) { let key = two_factor_key(user_id); self.throttle.clear(&key); self.two_factor_days.refund(&key); } /// Gives back the attempt just counted in both windows, for a correct code that keeps the short /// window as it was. pub fn refund_second_factor(&self, user_id: &str) { let key = two_factor_key(user_id); self.throttle.refund(&key); self.two_factor_days.refund(&key); } }