forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

state.rs101 lines, 4.6 KiBHistoryRawDownload
1//! The state shared by every route. Topcoat hands it to each handler through the app context.
2
3use std::sync::{Arc, PoisonError, RwLock};
4use std::time::{Duration, Instant};
5
6use im_core::config::{Config, PolicyConfig};
7use im_core::store::Store;
8use tokio::sync::{Semaphore, watch};
9
10use crate::api::directory::StreamSlots;
11use crate::backups::BackupTrigger;
12use crate::live::LiveHub;
13use crate::throttle::{TWO_FACTOR_DAY_LIMIT, TWO_FACTOR_USER_LIMIT, Throttle, two_factor_key};
14
15/// Everything a request handler reaches through the app context. Every field is cheap to clone.
16#[derive(Clone)]
17pub struct AppState {
18 /// The configuration the process booted with.
19 pub config: Arc<Config>,
20 /// The sign-in policy in effect: the file values, with the settings saved in the admin UI layered on
21 /// top. Read it through [`AppState::policy`]; the admin settings page replaces it while the server
22 /// runs.
23 pub policy_live: Arc<RwLock<PolicyConfig>>,
24 /// The database. Reads go to a pooled reader and writes to the single writer.
25 pub store: Store,
26 /// The instance key (`im.key`). Seals secrets at rest.
27 pub key: Arc<[u8; 32]>,
28 /// The change counters of the live pages.
29 pub live: Arc<LiveHub>,
30 /// Asks the backup worker for a run now (the admin health page). Shared with the worker.
31 pub backup: Arc<BackupTrigger>,
32 /// Failed sign-in and second-factor counters.
33 pub throttle: Arc<Throttle>,
34 /// Failed second-factor checks per account, one day window (see `throttle::TWO_FACTOR_DAY_LIMIT`).
35 pub two_factor_days: Arc<Throttle>,
36 /// Profile photo uploads per account, one hour window (see `throttle::PHOTO_UPLOAD_LIMIT`).
37 pub photo_uploads: Arc<Throttle>,
38 /// Email-change requests per account, one hour window (see `throttle::EMAIL_CHANGE_LIMIT`).
39 pub email_changes: Arc<Throttle>,
40 /// Per-minute counters: code issuances per session, token requests per client, and the audit of
41 /// failed sign-ins (see the limits in `throttle`).
42 pub per_minute: Arc<Throttle>,
43 /// The open directory streams of each machine client.
44 pub stream_slots: Arc<StreamSlots>,
45 /// The open anonymous `/-/alive` streams, at most [`MAX_ANONYMOUS_STREAMS`].
46 pub anonymous_streams: Arc<Semaphore>,
47 /// Set when the process is stopping. Long-lived streams end when it is, so the server can drain.
48 pub stop: watch::Receiver<bool>,
49 /// Held by every change to the saved policy, from the write to the refresh of `policy_live`. Two saves
50 /// then run one after the other, and the in-memory policy always matches what the database last committed.
51 pub settings_lock: Arc<tokio::sync::Mutex<()>>,
52 /// Held by every profile photo change, from the row write to the file write or removal, so that a
53 /// removal cannot delete the file a parallel upload has just put in place.
54 pub photo_lock: Arc<tokio::sync::Mutex<()>>,
55}
56
57impl AppState {
58 /// A copy of the policy in effect now. Cheap: the policy is a handful of numbers.
59 pub fn policy(&self) -> PolicyConfig {
60 self.policy_live
61 .read()
62 .unwrap_or_else(PoisonError::into_inner)
63 .clone()
64 }
65
66 /// Replaces the policy in effect. Used when an administrator saves the settings page.
67 pub fn set_policy(&self, policy: PolicyConfig) {
68 *self
69 .policy_live
70 .write()
71 .unwrap_or_else(PoisonError::into_inner) = policy;
72 }
73
74 /// Counts one second-factor attempt of `user_id` against both the short and the day window. Nothing
75 /// is counted when either refuses; the wait of the refusing window comes back.
76 pub fn reserve_second_factor(&self, user_id: &str) -> Result<(), Duration> {
77 let key = two_factor_key(user_id);
78 let now = Instant::now();
79 self.two_factor_days
80 .reserve(&key, TWO_FACTOR_DAY_LIMIT, now)?;
81 self.throttle
82 .reserve(&key, TWO_FACTOR_USER_LIMIT, now)
83 .inspect_err(|_| self.two_factor_days.refund(&key))
84 }
85
86 /// Forgets the second-factor failures of `user_id` after a correct code: the short window is cleared,
87 /// and the day window gives back the attempt just counted.
88 pub fn clear_second_factor(&self, user_id: &str) {
89 let key = two_factor_key(user_id);
90 self.throttle.clear(&key);
91 self.two_factor_days.refund(&key);
92 }
93
94 /// Gives back the attempt just counted in both windows, for a correct code that keeps the short
95 /// window as it was.
96 pub fn refund_second_factor(&self, user_id: &str) {
97 let key = two_factor_key(user_id);
98 self.throttle.refund(&key);
99 self.two_factor_days.refund(&key);
100 }
101}