config.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. use once_cell::sync::Lazy;
  2. use std::process::exit;
  3. use std::sync::RwLock;
  4. use reqwest::Url;
  5. use crate::error::Error;
  6. use crate::util::{get_env, get_env_bool};
  7. static CONFIG_FILE: Lazy<String> = Lazy::new(|| {
  8. let data_folder = get_env("DATA_FOLDER").unwrap_or_else(|| String::from("data"));
  9. get_env("CONFIG_FILE").unwrap_or_else(|| format!("{}/config.json", data_folder))
  10. });
  11. pub static CONFIG: Lazy<Config> = Lazy::new(|| {
  12. Config::load().unwrap_or_else(|e| {
  13. println!("Error loading config:\n\t{:?}\n", e);
  14. exit(12)
  15. })
  16. });
  17. pub type Pass = String;
  18. macro_rules! make_config {
  19. ($(
  20. $(#[doc = $groupdoc:literal])?
  21. $group:ident $(: $group_enabled:ident)? {
  22. $(
  23. $(#[doc = $doc:literal])+
  24. $name:ident : $ty:ident, $editable:literal, $none_action:ident $(, $default:expr)?;
  25. )+},
  26. )+) => {
  27. pub struct Config { inner: RwLock<Inner> }
  28. struct Inner {
  29. templates: Handlebars<'static>,
  30. config: ConfigItems,
  31. _env: ConfigBuilder,
  32. _usr: ConfigBuilder,
  33. }
  34. #[derive(Debug, Clone, Default, Deserialize, Serialize)]
  35. pub struct ConfigBuilder {
  36. $($(
  37. #[serde(skip_serializing_if = "Option::is_none")]
  38. $name: Option<$ty>,
  39. )+)+
  40. }
  41. impl ConfigBuilder {
  42. fn from_env() -> Self {
  43. dotenv::from_path(".env").ok();
  44. let mut builder = ConfigBuilder::default();
  45. $($(
  46. builder.$name = make_config! { @getenv &stringify!($name).to_uppercase(), $ty };
  47. )+)+
  48. builder
  49. }
  50. fn from_file(path: &str) -> Result<Self, Error> {
  51. use crate::util::read_file_string;
  52. let config_str = read_file_string(path)?;
  53. serde_json::from_str(&config_str).map_err(Into::into)
  54. }
  55. /// Merges the values of both builders into a new builder.
  56. /// If both have the same element, `other` wins.
  57. fn merge(&self, other: &Self, show_overrides: bool) -> Self {
  58. let mut overrides = Vec::new();
  59. let mut builder = self.clone();
  60. $($(
  61. if let v @Some(_) = &other.$name {
  62. builder.$name = v.clone();
  63. if self.$name.is_some() {
  64. overrides.push(stringify!($name).to_uppercase());
  65. }
  66. }
  67. )+)+
  68. if show_overrides && !overrides.is_empty() {
  69. // We can't use warn! here because logging isn't setup yet.
  70. println!("[WARNING] The following environment variables are being overriden by the config file,");
  71. println!("[WARNING] please use the admin panel to make changes to them:");
  72. println!("[WARNING] {}\n", overrides.join(", "));
  73. }
  74. builder
  75. }
  76. /// Returns a new builder with all the elements from self,
  77. /// except those that are equal in both sides
  78. fn _remove(&self, other: &Self) -> Self {
  79. let mut builder = ConfigBuilder::default();
  80. $($(
  81. if &self.$name != &other.$name {
  82. builder.$name = self.$name.clone();
  83. }
  84. )+)+
  85. builder
  86. }
  87. fn build(&self) -> ConfigItems {
  88. let mut config = ConfigItems::default();
  89. let _domain_set = self.domain.is_some();
  90. $($(
  91. config.$name = make_config!{ @build self.$name.clone(), &config, $none_action, $($default)? };
  92. )+)+
  93. config.domain_set = _domain_set;
  94. config
  95. }
  96. }
  97. #[derive(Debug, Clone, Default)]
  98. pub struct ConfigItems { $($(pub $name: make_config!{@type $ty, $none_action}, )+)+ }
  99. #[allow(unused)]
  100. impl Config {
  101. $($(
  102. pub fn $name(&self) -> make_config!{@type $ty, $none_action} {
  103. self.inner.read().unwrap().config.$name.clone()
  104. }
  105. )+)+
  106. pub fn prepare_json(&self) -> serde_json::Value {
  107. let (def, cfg) = {
  108. let inner = &self.inner.read().unwrap();
  109. (inner._env.build(), inner.config.clone())
  110. };
  111. fn _get_form_type(rust_type: &str) -> &'static str {
  112. match rust_type {
  113. "Pass" => "password",
  114. "String" => "text",
  115. "bool" => "checkbox",
  116. _ => "number"
  117. }
  118. }
  119. fn _get_doc(doc: &str) -> serde_json::Value {
  120. let mut split = doc.split("|>").map(str::trim);
  121. json!({
  122. "name": split.next(),
  123. "description": split.next()
  124. })
  125. }
  126. json!([ $({
  127. "group": stringify!($group),
  128. "grouptoggle": stringify!($($group_enabled)?),
  129. "groupdoc": make_config!{ @show $($groupdoc)? },
  130. "elements": [
  131. $( {
  132. "editable": $editable,
  133. "name": stringify!($name),
  134. "value": cfg.$name,
  135. "default": def.$name,
  136. "type": _get_form_type(stringify!($ty)),
  137. "doc": _get_doc(concat!($($doc),+)),
  138. }, )+
  139. ]}, )+ ])
  140. }
  141. }
  142. };
  143. // Group or empty string
  144. ( @show ) => { "" };
  145. ( @show $lit:literal ) => { $lit };
  146. // Wrap the optionals in an Option type
  147. ( @type $ty:ty, option) => { Option<$ty> };
  148. ( @type $ty:ty, $id:ident) => { $ty };
  149. // Generate the values depending on none_action
  150. ( @build $value:expr, $config:expr, option, ) => { $value };
  151. ( @build $value:expr, $config:expr, def, $default:expr ) => { $value.unwrap_or($default) };
  152. ( @build $value:expr, $config:expr, auto, $default_fn:expr ) => {{
  153. match $value {
  154. Some(v) => v,
  155. None => {
  156. let f: &dyn Fn(&ConfigItems) -> _ = &$default_fn;
  157. f($config)
  158. }
  159. }
  160. }};
  161. ( @build $value:expr, $config:expr, gen, $default_fn:expr ) => {{
  162. let f: &dyn Fn(&ConfigItems) -> _ = &$default_fn;
  163. f($config)
  164. }};
  165. ( @getenv $name:expr, bool ) => { get_env_bool($name) };
  166. ( @getenv $name:expr, $ty:ident ) => { get_env($name) };
  167. }
  168. //STRUCTURE:
  169. // /// Short description (without this they won't appear on the list)
  170. // group {
  171. // /// Friendly Name |> Description (Optional)
  172. // name: type, is_editable, action, <default_value (Optional)>
  173. // }
  174. //
  175. // Where action applied when the value wasn't provided and can be:
  176. // def: Use a default value
  177. // auto: Value is auto generated based on other values
  178. // option: Value is optional
  179. // gen: Value is always autogenerated and it's original value ignored
  180. make_config! {
  181. folders {
  182. /// Data folder |> Main data folder
  183. data_folder: String, false, def, "data".to_string();
  184. /// Database URL
  185. database_url: String, false, auto, |c| format!("{}/{}", c.data_folder, "db.sqlite3");
  186. /// Icon cache folder
  187. icon_cache_folder: String, false, auto, |c| format!("{}/{}", c.data_folder, "icon_cache");
  188. /// Attachments folder
  189. attachments_folder: String, false, auto, |c| format!("{}/{}", c.data_folder, "attachments");
  190. /// Templates folder
  191. templates_folder: String, false, auto, |c| format!("{}/{}", c.data_folder, "templates");
  192. /// Session JWT key
  193. rsa_key_filename: String, false, auto, |c| format!("{}/{}", c.data_folder, "rsa_key");
  194. /// Web vault folder
  195. web_vault_folder: String, false, def, "web-vault/".to_string();
  196. },
  197. ws {
  198. /// Enable websocket notifications
  199. websocket_enabled: bool, false, def, false;
  200. /// Websocket address
  201. websocket_address: String, false, def, "0.0.0.0".to_string();
  202. /// Websocket port
  203. websocket_port: u16, false, def, 3012;
  204. },
  205. /// General settings
  206. settings {
  207. /// Domain URL |> This needs to be set to the URL used to access the server, including 'http[s]://'
  208. /// and port, if it's different than the default. Some server functions don't work correctly without this value
  209. domain: String, true, def, "http://localhost".to_string();
  210. /// Domain Set |> Indicates if the domain is set by the admin. Otherwise the default will be used.
  211. domain_set: bool, false, def, false;
  212. /// Domain origin |> Domain URL origin (in https://example.com:8443/path, https://example.com:8443 is the origin)
  213. domain_origin: String, false, auto, |c| extract_url_origin(&c.domain);
  214. /// Domain path |> Domain URL path (in https://example.com:8443/path, /path is the path)
  215. domain_path: String, false, auto, |c| extract_url_path(&c.domain);
  216. /// Enable web vault
  217. web_vault_enabled: bool, false, def, true;
  218. /// HIBP Api Key |> HaveIBeenPwned API Key, request it here: https://haveibeenpwned.com/API/Key
  219. hibp_api_key: Pass, true, option;
  220. /// Per-user attachment limit (KB) |> Limit in kilobytes for a users attachments, once the limit is exceeded it won't be possible to upload more
  221. user_attachment_limit: i64, true, option;
  222. /// Per-organization attachment limit (KB) |> Limit in kilobytes for an organization attachments, once the limit is exceeded it won't be possible to upload more
  223. org_attachment_limit: i64, true, option;
  224. /// Disable icon downloads |> Set to true to disable icon downloading, this would still serve icons from
  225. /// $ICON_CACHE_FOLDER, but it won't produce any external network request. Needs to set $ICON_CACHE_TTL to 0,
  226. /// otherwise it will delete them and they won't be downloaded again.
  227. disable_icon_download: bool, true, def, false;
  228. /// Allow new signups |> Controls if new users can register. Note that while this is disabled, users could still be invited
  229. signups_allowed: bool, true, def, true;
  230. /// Require email verification on signups. This will prevent logins from succeeding until the address has been verified
  231. signups_verify: bool, true, def, false;
  232. /// If signups require email verification, automatically re-send verification email if it hasn't been sent for a while (in seconds)
  233. signups_verify_resend_time: u64, true, def, 3_600;
  234. /// If signups require email verification, limit how many emails are automatically sent when login is attempted (0 means no limit)
  235. signups_verify_resend_limit: u32, true, def, 6;
  236. /// Allow signups only from this list of comma-separated domains
  237. signups_domains_whitelist: String, true, def, "".to_string();
  238. /// Allow invitations |> Controls whether users can be invited by organization admins, even when signups are disabled
  239. invitations_allowed: bool, true, def, true;
  240. /// Password iterations |> Number of server-side passwords hashing iterations.
  241. /// The changes only apply when a user changes their password. Not recommended to lower the value
  242. password_iterations: i32, true, def, 100_000;
  243. /// Show password hints |> Controls if the password hint should be shown directly in the web page.
  244. /// Otherwise, if email is disabled, there is no way to see the password hint
  245. show_password_hint: bool, true, def, true;
  246. /// Admin page token |> The token used to authenticate in this very same page. Changing it here won't deauthorize the current session
  247. admin_token: Pass, true, option;
  248. /// Invitation organization name |> Name shown in the invitation emails that don't come from a specific organization
  249. invitation_org_name: String, true, def, "Bitwarden_RS".to_string();
  250. },
  251. /// Advanced settings
  252. advanced {
  253. /// Client IP header |> If not present, the remote IP is used.
  254. /// Set to the string "none" (without quotes), to disable any headers and just use the remote IP
  255. ip_header: String, true, def, "X-Real-IP".to_string();
  256. /// Internal IP header property, used to avoid recomputing each time
  257. _ip_header_enabled: bool, false, gen, |c| &c.ip_header.trim().to_lowercase() != "none";
  258. /// Positive icon cache expiry |> Number of seconds to consider that an already cached icon is fresh. After this period, the icon will be redownloaded
  259. icon_cache_ttl: u64, true, def, 2_592_000;
  260. /// Negative icon cache expiry |> Number of seconds before trying to download an icon that failed again.
  261. icon_cache_negttl: u64, true, def, 259_200;
  262. /// Icon download timeout |> Number of seconds when to stop attempting to download an icon.
  263. icon_download_timeout: u64, true, def, 10;
  264. /// Icon blacklist Regex |> Any domains or IPs that match this regex won't be fetched by the icon service.
  265. /// Useful to hide other servers in the local network. Check the WIKI for more details
  266. icon_blacklist_regex: String, true, option;
  267. /// Icon blacklist non global IPs |> Any IP which is not defined as a global IP will be blacklisted.
  268. /// Usefull to secure your internal environment: See https://en.wikipedia.org/wiki/Reserved_IP_addresses for a list of IPs which it will block
  269. icon_blacklist_non_global_ips: bool, true, def, true;
  270. /// Disable Two-Factor remember |> Enabling this would force the users to use a second factor to login every time.
  271. /// Note that the checkbox would still be present, but ignored.
  272. disable_2fa_remember: bool, true, def, false;
  273. /// Disable authenticator time drifted codes to be valid |> Enabling this only allows the current TOTP code to be valid
  274. /// TOTP codes of the previous and next 30 seconds will be invalid.
  275. authenticator_disable_time_drift: bool, true, def, false;
  276. /// Require new device emails |> When a user logs in an email is required to be sent.
  277. /// If sending the email fails the login attempt will fail.
  278. require_device_email: bool, true, def, false;
  279. /// Reload templates (Dev) |> When this is set to true, the templates get reloaded with every request.
  280. /// ONLY use this during development, as it can slow down the server
  281. reload_templates: bool, true, def, false;
  282. /// Enable extended logging
  283. extended_logging: bool, false, def, true;
  284. /// Enable the log to output to Syslog
  285. use_syslog: bool, false, def, false;
  286. /// Log file path
  287. log_file: String, false, option;
  288. /// Log level
  289. log_level: String, false, def, "Info".to_string();
  290. /// Enable DB WAL |> Turning this off might lead to worse performance, but might help if using bitwarden_rs on some exotic filesystems,
  291. /// that do not support WAL. Please make sure you read project wiki on the topic before changing this setting.
  292. enable_db_wal: bool, false, def, true;
  293. /// Bypass admin page security (Know the risks!) |> Disables the Admin Token for the admin page so you may use your own auth in-front
  294. disable_admin_token: bool, true, def, false;
  295. /// Allowed iframe ancestors (Know the risks!) |> Allows other domains to embed the web vault into an iframe, useful for embedding into secure intranets
  296. allowed_iframe_ancestors: String, true, def, String::new();
  297. },
  298. /// Yubikey settings
  299. yubico: _enable_yubico {
  300. /// Enabled
  301. _enable_yubico: bool, true, def, true;
  302. /// Client ID
  303. yubico_client_id: String, true, option;
  304. /// Secret Key
  305. yubico_secret_key: Pass, true, option;
  306. /// Server
  307. yubico_server: String, true, option;
  308. },
  309. /// Global Duo settings (Note that users can override them)
  310. duo: _enable_duo {
  311. /// Enabled
  312. _enable_duo: bool, true, def, false;
  313. /// Integration Key
  314. duo_ikey: String, true, option;
  315. /// Secret Key
  316. duo_skey: Pass, true, option;
  317. /// Host
  318. duo_host: String, true, option;
  319. /// Application Key (generated automatically)
  320. _duo_akey: Pass, false, option;
  321. },
  322. /// SMTP Email Settings
  323. smtp: _enable_smtp {
  324. /// Enabled
  325. _enable_smtp: bool, true, def, true;
  326. /// Host
  327. smtp_host: String, true, option;
  328. /// Enable SSL
  329. smtp_ssl: bool, true, def, true;
  330. /// Use explicit TLS |> Enabling this would force the use of an explicit TLS connection, instead of upgrading an insecure one with STARTTLS
  331. smtp_explicit_tls: bool, true, def, false;
  332. /// Port
  333. smtp_port: u16, true, auto, |c| if c.smtp_explicit_tls {465} else if c.smtp_ssl {587} else {25};
  334. /// From Address
  335. smtp_from: String, true, def, String::new();
  336. /// From Name
  337. smtp_from_name: String, true, def, "Bitwarden_RS".to_string();
  338. /// Username
  339. smtp_username: String, true, option;
  340. /// Password
  341. smtp_password: Pass, true, option;
  342. /// Json form auth mechanism |> Defaults for ssl is "Plain" and "Login" and nothing for non-ssl connections. Possible values: ["Plain", "Login", "Xoauth2"]
  343. smtp_auth_mechanism: String, true, option;
  344. /// SMTP connection timeout |> Number of seconds when to stop trying to connect to the SMTP server
  345. smtp_timeout: u64, true, def, 15;
  346. },
  347. /// Email 2FA Settings
  348. email_2fa: _enable_email_2fa {
  349. /// Enabled |> Disabling will prevent users from setting up new email 2FA and using existing email 2FA configured
  350. _enable_email_2fa: bool, true, auto, |c| c._enable_smtp && c.smtp_host.is_some();
  351. /// Token number length |> Length of the numbers in an email token. Minimum of 6. Maximum is 19.
  352. email_token_size: u32, true, def, 6;
  353. /// Token expiration time |> Maximum time in seconds a token is valid. The time the user has to open email client and copy token.
  354. email_expiration_time: u64, true, def, 600;
  355. /// Maximum attempts |> Maximum attempts before an email token is reset and a new email will need to be sent
  356. email_attempts_limit: u64, true, def, 3;
  357. },
  358. }
  359. fn validate_config(cfg: &ConfigItems) -> Result<(), Error> {
  360. let db_url = cfg.database_url.to_lowercase();
  361. if cfg!(feature = "sqlite") && (db_url.starts_with("mysql:") || db_url.starts_with("postgresql:")) {
  362. err!("`DATABASE_URL` is meant for MySQL or Postgres, while this server is meant for SQLite")
  363. }
  364. if cfg!(feature = "mysql") && !db_url.starts_with("mysql:") {
  365. err!("`DATABASE_URL` should start with mysql: when using the MySQL server")
  366. }
  367. if cfg!(feature = "postgresql") && !db_url.starts_with("postgresql:") {
  368. err!("`DATABASE_URL` should start with postgresql: when using the PostgreSQL server")
  369. }
  370. let dom = cfg.domain.to_lowercase();
  371. if !dom.starts_with("http://") && !dom.starts_with("https://") {
  372. err!("DOMAIN variable needs to contain the protocol (http, https). Use 'http[s]://bw.example.com' instead of 'bw.example.com'");
  373. }
  374. if let Some(ref token) = cfg.admin_token {
  375. if token.trim().is_empty() && !cfg.disable_admin_token {
  376. println!("[WARNING] `ADMIN_TOKEN` is enabled but has an empty value, so the admin page will be disabled.");
  377. println!("[WARNING] To enable the admin page without a token, use `DISABLE_ADMIN_TOKEN`.");
  378. }
  379. }
  380. if cfg._enable_duo
  381. && (cfg.duo_host.is_some() || cfg.duo_ikey.is_some() || cfg.duo_skey.is_some())
  382. && !(cfg.duo_host.is_some() && cfg.duo_ikey.is_some() && cfg.duo_skey.is_some())
  383. {
  384. err!("All Duo options need to be set for global Duo support")
  385. }
  386. if cfg._enable_yubico && cfg.yubico_client_id.is_some() != cfg.yubico_secret_key.is_some() {
  387. err!("Both `YUBICO_CLIENT_ID` and `YUBICO_SECRET_KEY` need to be set for Yubikey OTP support")
  388. }
  389. if cfg._enable_smtp {
  390. if cfg.smtp_host.is_some() == cfg.smtp_from.is_empty() {
  391. err!("Both `SMTP_HOST` and `SMTP_FROM` need to be set for email support")
  392. }
  393. if cfg.smtp_username.is_some() != cfg.smtp_password.is_some() {
  394. err!("Both `SMTP_USERNAME` and `SMTP_PASSWORD` need to be set to enable email authentication")
  395. }
  396. if cfg._enable_email_2fa && (!cfg._enable_smtp || cfg.smtp_host.is_none()) {
  397. err!("To enable email 2FA, SMTP must be configured")
  398. }
  399. if cfg._enable_email_2fa && cfg.email_token_size < 6 {
  400. err!("`EMAIL_TOKEN_SIZE` has a minimum size of 6")
  401. }
  402. if cfg._enable_email_2fa && cfg.email_token_size > 19 {
  403. err!("`EMAIL_TOKEN_SIZE` has a maximum size of 19")
  404. }
  405. }
  406. Ok(())
  407. }
  408. /// Extracts an RFC 6454 web origin from a URL.
  409. fn extract_url_origin(url: &str) -> String {
  410. match Url::parse(url) {
  411. Ok(u) => u.origin().ascii_serialization(),
  412. Err(e) => {
  413. println!("Error validating domain: {}", e);
  414. String::new()
  415. }
  416. }
  417. }
  418. /// Extracts the path from a URL.
  419. /// All trailing '/' chars are trimmed, even if the path is a lone '/'.
  420. fn extract_url_path(url: &str) -> String {
  421. match Url::parse(url) {
  422. Ok(u) => u.path().trim_end_matches('/').to_string(),
  423. Err(_) => {
  424. // We already print it in the method above, no need to do it again
  425. String::new()
  426. }
  427. }
  428. }
  429. impl Config {
  430. pub fn load() -> Result<Self, Error> {
  431. // Loading from env and file
  432. let _env = ConfigBuilder::from_env();
  433. let _usr = ConfigBuilder::from_file(&CONFIG_FILE).unwrap_or_default();
  434. // Create merged config, config file overwrites env
  435. let builder = _env.merge(&_usr, true);
  436. // Fill any missing with defaults
  437. let config = builder.build();
  438. validate_config(&config)?;
  439. Ok(Config {
  440. inner: RwLock::new(Inner { templates: load_templates(&config.templates_folder), config, _env, _usr }),
  441. })
  442. }
  443. pub fn update_config(&self, other: ConfigBuilder) -> Result<(), Error> {
  444. // Remove default values
  445. //let builder = other.remove(&self.inner.read().unwrap()._env);
  446. // TODO: Remove values that are defaults, above only checks those set by env and not the defaults
  447. let builder = other;
  448. // Serialize now before we consume the builder
  449. let config_str = serde_json::to_string_pretty(&builder)?;
  450. // Prepare the combined config
  451. let config = {
  452. let env = &self.inner.read().unwrap()._env;
  453. env.merge(&builder, false).build()
  454. };
  455. validate_config(&config)?;
  456. // Save both the user and the combined config
  457. {
  458. let mut writer = self.inner.write().unwrap();
  459. writer.config = config;
  460. writer._usr = builder;
  461. }
  462. //Save to file
  463. use std::{fs::File, io::Write};
  464. let mut file = File::create(&*CONFIG_FILE)?;
  465. file.write_all(config_str.as_bytes())?;
  466. Ok(())
  467. }
  468. pub fn update_config_partial(&self, other: ConfigBuilder) -> Result<(), Error> {
  469. let builder = {
  470. let usr = &self.inner.read().unwrap()._usr;
  471. usr.merge(&other, false)
  472. };
  473. self.update_config(builder)
  474. }
  475. pub fn can_signup_user(&self, email: &str) -> bool {
  476. let e: Vec<&str> = email.rsplitn(2, '@').collect();
  477. if e.len() != 2 || e[0].is_empty() || e[1].is_empty() {
  478. warn!("Failed to parse email address '{}'", email);
  479. return false;
  480. }
  481. // Allow signups if the whitelist is empty/not configured
  482. // (it doesn't contain any domains), or if it matches at least
  483. // one domain.
  484. let whitelist_str = self.signups_domains_whitelist();
  485. ( whitelist_str.is_empty() && CONFIG.signups_allowed() )|| whitelist_str.split(',').filter(|s| !s.is_empty()).any(|d| d == e[0])
  486. }
  487. pub fn delete_user_config(&self) -> Result<(), Error> {
  488. crate::util::delete_file(&CONFIG_FILE)?;
  489. // Empty user config
  490. let usr = ConfigBuilder::default();
  491. // Config now is env + defaults
  492. let config = {
  493. let env = &self.inner.read().unwrap()._env;
  494. env.build()
  495. };
  496. // Save configs
  497. {
  498. let mut writer = self.inner.write().unwrap();
  499. writer.config = config;
  500. writer._usr = usr;
  501. }
  502. Ok(())
  503. }
  504. pub fn private_rsa_key(&self) -> String {
  505. format!("{}.der", CONFIG.rsa_key_filename())
  506. }
  507. pub fn private_rsa_key_pem(&self) -> String {
  508. format!("{}.pem", CONFIG.rsa_key_filename())
  509. }
  510. pub fn public_rsa_key(&self) -> String {
  511. format!("{}.pub.der", CONFIG.rsa_key_filename())
  512. }
  513. pub fn mail_enabled(&self) -> bool {
  514. let inner = &self.inner.read().unwrap().config;
  515. inner._enable_smtp && inner.smtp_host.is_some()
  516. }
  517. pub fn get_duo_akey(&self) -> String {
  518. if let Some(akey) = self._duo_akey() {
  519. akey
  520. } else {
  521. let akey = crate::crypto::get_random_64();
  522. let akey_s = data_encoding::BASE64.encode(&akey);
  523. // Save the new value
  524. let mut builder = ConfigBuilder::default();
  525. builder._duo_akey = Some(akey_s.clone());
  526. self.update_config_partial(builder).ok();
  527. akey_s
  528. }
  529. }
  530. /// Tests whether the admin token is set to a non-empty value.
  531. pub fn is_admin_token_set(&self) -> bool {
  532. let token = self.admin_token();
  533. !token.is_none() && !token.unwrap().trim().is_empty()
  534. }
  535. pub fn render_template<T: serde::ser::Serialize>(
  536. &self,
  537. name: &str,
  538. data: &T,
  539. ) -> Result<String, crate::error::Error> {
  540. if CONFIG.reload_templates() {
  541. warn!("RELOADING TEMPLATES");
  542. let hb = load_templates(CONFIG.templates_folder());
  543. hb.render(name, data).map_err(Into::into)
  544. } else {
  545. let hb = &CONFIG.inner.read().unwrap().templates;
  546. hb.render(name, data).map_err(Into::into)
  547. }
  548. }
  549. }
  550. use handlebars::{Context, Handlebars, Helper, HelperResult, Output, RenderContext, RenderError, Renderable};
  551. fn load_templates<P>(path: P) -> Handlebars<'static>
  552. where
  553. P: AsRef<std::path::Path>,
  554. {
  555. let mut hb = Handlebars::new();
  556. // Error on missing params
  557. hb.set_strict_mode(true);
  558. // Register helpers
  559. hb.register_helper("case", Box::new(case_helper));
  560. hb.register_helper("jsesc", Box::new(js_escape_helper));
  561. macro_rules! reg {
  562. ($name:expr) => {{
  563. let template = include_str!(concat!("static/templates/", $name, ".hbs"));
  564. hb.register_template_string($name, template).unwrap();
  565. }};
  566. ($name:expr, $ext:expr) => {{
  567. reg!($name);
  568. reg!(concat!($name, $ext));
  569. }};
  570. }
  571. // First register default templates here
  572. reg!("email/change_email", ".html");
  573. reg!("email/delete_account", ".html");
  574. reg!("email/invite_accepted", ".html");
  575. reg!("email/invite_confirmed", ".html");
  576. reg!("email/new_device_logged_in", ".html");
  577. reg!("email/pw_hint_none", ".html");
  578. reg!("email/pw_hint_some", ".html");
  579. reg!("email/send_org_invite", ".html");
  580. reg!("email/twofactor_email", ".html");
  581. reg!("email/verify_email", ".html");
  582. reg!("email/welcome", ".html");
  583. reg!("email/welcome_must_verify", ".html");
  584. reg!("email/smtp_test", ".html");
  585. reg!("admin/base");
  586. reg!("admin/login");
  587. reg!("admin/page");
  588. // And then load user templates to overwrite the defaults
  589. // Use .hbs extension for the files
  590. // Templates get registered with their relative name
  591. hb.register_templates_directory(".hbs", path).unwrap();
  592. hb
  593. }
  594. fn case_helper<'reg, 'rc>(
  595. h: &Helper<'reg, 'rc>,
  596. r: &'reg Handlebars,
  597. ctx: &'rc Context,
  598. rc: &mut RenderContext<'reg, 'rc>,
  599. out: &mut dyn Output,
  600. ) -> HelperResult {
  601. let param = h
  602. .param(0)
  603. .ok_or_else(|| RenderError::new("Param not found for helper \"case\""))?;
  604. let value = param.value().clone();
  605. if h.params().iter().skip(1).any(|x| x.value() == &value) {
  606. h.template().map(|t| t.render(r, ctx, rc, out)).unwrap_or(Ok(()))
  607. } else {
  608. Ok(())
  609. }
  610. }
  611. fn js_escape_helper<'reg, 'rc>(
  612. h: &Helper<'reg, 'rc>,
  613. _r: &'reg Handlebars,
  614. _ctx: &'rc Context,
  615. _rc: &mut RenderContext<'reg, 'rc>,
  616. out: &mut dyn Output,
  617. ) -> HelperResult {
  618. let param = h
  619. .param(0)
  620. .ok_or_else(|| RenderError::new("Param not found for helper \"js_escape\""))?;
  621. let value = param
  622. .value()
  623. .as_str()
  624. .ok_or_else(|| RenderError::new("Param for helper \"js_escape\" is not a String"))?;
  625. let escaped_value = value.replace('\\', "").replace('\'', "\\x22").replace('\"', "\\x27");
  626. let quoted_value = format!("&quot;{}&quot;", escaped_value);
  627. out.write(&quoted_value)?;
  628. Ok(())
  629. }