Skip to main content

lockbook_server_lib/
config.rs

1use crate::config::Environment::{Local, Prod, Unknown};
2use lb_rs::model::account::Username;
3use lb_rs::model::meta::Meta;
4use lb_rs::model::signed_meta::SignedMeta;
5use semver::VersionReq;
6use std::collections::HashSet;
7use std::fmt::Display;
8use std::net::SocketAddr;
9use std::path::PathBuf;
10use std::time::Duration;
11use std::{env, fmt, fs};
12
13#[derive(Clone, Debug)]
14pub struct Config {
15    pub server: ServerConfig,
16    pub index_db: IndexDbConf,
17    pub files: FilesConfig,
18    pub metrics: MetricsConfig,
19    pub billing: BillingConfig,
20    pub admin: AdminConfig,
21    pub features: FeatureFlags,
22}
23
24impl Config {
25    pub fn from_env_vars() -> Self {
26        Self {
27            index_db: IndexDbConf::from_env_vars(),
28            files: FilesConfig::from_env_vars(),
29            server: ServerConfig::from_env_vars(),
30            metrics: MetricsConfig::from_env_vars(),
31            billing: BillingConfig::from_env_vars(),
32            admin: AdminConfig::from_env_vars(),
33            features: FeatureFlags::from_env_vars(),
34        }
35    }
36
37    pub fn is_prod(&self) -> bool {
38        self.server.env == Prod
39    }
40}
41
42#[derive(Clone, Debug)]
43pub struct IndexDbConf {
44    pub db_location: String,
45    pub time_between_compacts: Duration,
46}
47
48impl IndexDbConf {
49    pub fn from_env_vars() -> Self {
50        Self {
51            db_location: env_or_panic("INDEX_DB_LOCATION"),
52            time_between_compacts: Duration::from_secs(
53                env_or_panic("MINUTES_BETWEEN_BACKGROUND_COMPACTS")
54                    .parse::<u64>()
55                    .unwrap()
56                    * 60,
57            ),
58        }
59    }
60}
61
62#[derive(Clone, Debug, Default)]
63pub struct AdminConfig {
64    pub admins: HashSet<Username>,
65}
66
67impl AdminConfig {
68    pub fn from_env_vars() -> Self {
69        Self {
70            admins: env::var("ADMINS")
71                .unwrap_or_else(|_| "".to_string())
72                .split(", ")
73                .map(|part| part.to_string())
74                .collect(),
75        }
76    }
77}
78
79#[derive(Clone, Debug)]
80pub struct FeatureFlags {
81    pub new_accounts: bool,
82    pub new_account_rate_limit: bool,
83    pub bandwidth_controls: bool,
84    /// Accept metadata V2 (attachments). Set from [lb_rs::ATTACHMENTS_FOLDERS]; only turn that on
85    /// while also forcing clients, with `MIN_CORE_VERSION`, to upgrade to the version that
86    /// introduced this flag.
87    pub meta_v2: bool,
88}
89
90impl FeatureFlags {
91    pub fn from_env_vars() -> Self {
92        Self {
93            new_accounts: env::var("FEATURE_NEW_ACCOUNTS")
94                .unwrap_or_else(|_| "true".to_string())
95                .parse()
96                .unwrap(),
97            new_account_rate_limit: env::var("FEATURE_NEW_ACCOUNT_LIMITS")
98                .unwrap_or_else(|_| "false".to_string())
99                .parse()
100                .unwrap(),
101            bandwidth_controls: env::var("FEATURE_BANDWIDTH_CONTROLS")
102                .unwrap_or_else(|_| "true".to_string())
103                .parse()
104                .unwrap(),
105            meta_v2: lb_rs::ATTACHMENTS_FOLDERS,
106        }
107    }
108
109    /// Whether `file` is more recent than the max version supported by all the server's clients
110    /// (via forced upgrades)
111    pub fn refuses(&self, file: &SignedMeta) -> bool {
112        match file.timestamped_value.value {
113            Meta::V1 { .. } => false,
114            Meta::V2 { .. } => !self.meta_v2,
115        }
116    }
117}
118
119#[derive(Clone, Debug)]
120pub struct FilesConfig {
121    pub path: PathBuf,
122}
123
124impl FilesConfig {
125    pub fn from_env_vars() -> Self {
126        let path = env_or_panic("FILES_PATH");
127        let path = PathBuf::from(path);
128        fs::create_dir_all(&path).unwrap();
129        Self { path }
130    }
131}
132
133#[derive(Clone, Debug, PartialEq, Eq)]
134pub enum Environment {
135    Prod,
136    Local,
137    Unknown,
138}
139
140impl Environment {
141    pub fn from_env_vars() -> Self {
142        match env::var("ENVIRONMENT") {
143            Ok(var) => match var.to_lowercase().as_str() {
144                "production" | "prod" => Prod,
145                "local" | "localhost" => Local,
146                _ => Unknown,
147            },
148            Err(_) => Unknown,
149        }
150    }
151}
152
153impl Display for Environment {
154    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
155        write!(f, "{:?}", self)
156    }
157}
158
159#[derive(Clone, Debug)]
160pub struct ServerConfig {
161    pub env: Environment,
162    pub port: u16,
163    pub max_auth_delay: u128,
164    pub log_path: String,
165    pub pd_api_key: Option<String>,
166    pub discord_webhook_url: Option<String>,
167    pub ssl_cert_location: Option<String>,
168    pub ssl_private_key_location: Option<String>,
169    pub min_core_version: VersionReq,
170}
171
172impl ServerConfig {
173    pub fn from_env_vars() -> Self {
174        let env = Environment::from_env_vars();
175        let port = env_or_panic("SERVER_PORT").parse().unwrap();
176        let max_auth_delay = env_or_panic("MAX_AUTH_DELAY").parse().unwrap();
177        let log_path = env_or_panic("LOG_PATH").parse().unwrap();
178        let pd_api_key = env_or_empty("PD_KEY");
179        let discord_webhook_url = env_or_empty("DISCORD_WEBHOOK_URL");
180        let ssl_cert_location = env_or_empty("SSL_CERT_LOCATION");
181        let ssl_private_key_location = env_or_empty("SSL_PRIVATE_KEY_LOCATION");
182        let min_core_version = VersionReq::parse(&env_or_panic("MIN_CORE_VERSION")).unwrap();
183
184        match (&discord_webhook_url, &pd_api_key, &ssl_cert_location, &ssl_private_key_location) {
185            (Some(_), Some(_), Some(_), Some(_)) | (None, None, None, None) => {}
186            _ => panic!(
187                "Invalid config, discord & pd & ssl must all be Some (production) or all be None (local)"
188            ),
189        }
190
191        Self {
192            env,
193            port,
194            max_auth_delay,
195            log_path,
196            pd_api_key,
197            discord_webhook_url,
198            ssl_cert_location,
199            ssl_private_key_location,
200            min_core_version,
201        }
202    }
203}
204
205#[derive(Clone, Debug)]
206pub struct MetricsConfig {
207    pub addr: SocketAddr,
208    pub time_between_metrics_refresh: Duration,
209    pub time_between_metrics: Duration,
210}
211
212impl MetricsConfig {
213    pub fn from_env_vars() -> Self {
214        Self {
215            addr: env_or_empty("METRICS_ADDR")
216                .map(|addr| addr.parse().unwrap())
217                .unwrap_or(([127, 0, 0, 1], 8080).into()),
218            time_between_metrics_refresh: Duration::from_secs(
219                env_or_panic("MINUTES_BETWEEN_METRICS_REFRESH")
220                    .parse::<u64>()
221                    .unwrap()
222                    * 60,
223            ),
224            time_between_metrics: Duration::from_millis(
225                env_or_panic("MILLIS_BETWEEN_METRICS")
226                    .parse::<u64>()
227                    .unwrap(),
228            ),
229        }
230    }
231}
232
233#[derive(Clone, Debug)]
234pub struct BillingConfig {
235    pub millis_between_user_payment_flows: u64,
236    pub time_between_lock_attempts: Duration,
237    pub google: GoogleConfig,
238    pub stripe: StripeConfig,
239    pub apple: AppleConfig,
240}
241
242impl BillingConfig {
243    pub fn from_env_vars() -> Self {
244        Self {
245            millis_between_user_payment_flows: env_or_panic("MILLIS_BETWEEN_PAYMENT_FLOWS")
246                .parse()
247                .unwrap(),
248            time_between_lock_attempts: Duration::from_millis(
249                env_or_panic("MILLIS_BETWEEN_LOCK_ATTEMPTS")
250                    .parse::<u64>()
251                    .unwrap(),
252            ),
253            google: GoogleConfig::from_env_vars(),
254            stripe: StripeConfig::from_env_vars(),
255            apple: AppleConfig::from_env_vars(),
256        }
257    }
258}
259
260#[derive(Clone, Debug)]
261pub struct AppleConfig {
262    pub iap_key: String,
263    pub iap_key_id: String,
264    pub asc_public_key: String,
265    pub issuer_id: String,
266    pub subscription_product_id: String,
267    pub asc_shared_secret: String,
268    pub apple_root_cert: Vec<u8>,
269    pub monthly_sub_group_id: String,
270}
271
272impl AppleConfig {
273    pub fn from_env_vars() -> Self {
274        let is_apple_prod = env_or_empty("IS_APPLE_PROD")
275            .map(|is_apple_prod| is_apple_prod.parse().unwrap())
276            .unwrap_or(false);
277
278        let apple_root_cert =
279            env_or_empty("APPLE_ROOT_CERT_PATH").map(|cert_path| fs::read(cert_path).unwrap());
280        let apple_iap_key = env_or_empty("APPLE_IAP_KEY_PATH")
281            .map(|key_path| fs::read_to_string(key_path).unwrap());
282        let apple_asc_pub_key = env_or_empty("APPLE_ASC_PUB_KEY_PATH")
283            .map(|key_path| fs::read_to_string(key_path).unwrap());
284
285        Self {
286            iap_key: if is_apple_prod {
287                apple_iap_key.unwrap()
288            } else {
289                apple_iap_key.unwrap_or_default()
290            },
291            iap_key_id: env_or_panic("APPLE_IAP_KEY_ID"),
292            asc_public_key: if is_apple_prod {
293                apple_asc_pub_key.unwrap()
294            } else {
295                apple_asc_pub_key.unwrap_or_default()
296            },
297            issuer_id: env_or_panic("APPLE_ISSUER_ID"),
298            subscription_product_id: env_or_panic("APPLE_SUB_PROD_ID"),
299            asc_shared_secret: env_or_panic("APPLE_ASC_SHARED_SECRET"),
300            apple_root_cert: if is_apple_prod {
301                apple_root_cert.unwrap()
302            } else {
303                apple_root_cert.unwrap_or_default()
304            },
305            monthly_sub_group_id: env_or_panic("APPLE_MONTHLY_SUB_GROUP_ID"),
306        }
307    }
308}
309
310#[derive(Clone, Debug)]
311pub struct GoogleConfig {
312    pub service_account_key: Option<String>,
313    pub premium_subscription_product_id: String,
314    pub premium_subscription_offer_id: String,
315    pub pubsub_token: String,
316}
317
318impl GoogleConfig {
319    pub fn from_env_vars() -> Self {
320        Self {
321            service_account_key: env_or_empty("GOOGLE_CLOUD_SERVICE_ACCOUNT_KEY"),
322            premium_subscription_product_id: env_or_panic(
323                "GOOGLE_PLAY_PREMIUM_SUBSCRIPTION_PRODUCT_ID",
324            ),
325            premium_subscription_offer_id: env_or_panic(
326                "GOOGLE_PLAY_PREMIUM_SUBSCRIPTION_OFFER_ID",
327            ),
328            pubsub_token: env_or_panic("GOOGLE_CLOUD_PUBSUB_NOTIFICATION_TOKEN"),
329        }
330    }
331}
332
333#[derive(Clone, Debug)]
334pub struct StripeConfig {
335    pub stripe_secret: String,
336    pub signing_secret: String,
337    pub premium_price_id: String,
338}
339
340impl StripeConfig {
341    pub fn from_env_vars() -> Self {
342        Self {
343            stripe_secret: env_or_panic("STRIPE_SECRET").parse().unwrap(),
344            signing_secret: env_or_panic("STRIPE_SIGNING_SECRET").parse().unwrap(),
345            premium_price_id: env_or_panic("STRIPE_PREMIUM_PRICE_ID").parse().unwrap(),
346        }
347    }
348}
349
350fn env_or_panic(var_name: &str) -> String {
351    env::var(var_name).unwrap_or_else(|_| panic!("Missing environment variable {var_name}"))
352}
353
354fn env_or_empty(var_name: &str) -> Option<String> {
355    env::var(var_name).ok()
356}