Implemented config form and fixed config priority

This commit is contained in:
Daniel García
2019-02-03 00:22:18 +01:00
parent ade293cf52
commit 3db815b969
6 changed files with 259 additions and 154 deletions

View File

@@ -1,8 +1,6 @@
use std::process::exit;
use std::sync::RwLock;
use handlebars::Handlebars;
use crate::error::Error;
lazy_static! {
@@ -14,18 +12,24 @@ lazy_static! {
}
macro_rules! make_config {
( $( $name:ident : $ty:ty $(, $default_fn:expr)? );+ $(;)? ) => {
( $( $name:ident : $ty:ty, $editable:literal, $none_action:ident $(, $default:expr)? );+ $(;)? ) => {
pub struct Config { inner: RwLock<Inner> }
struct Inner {
templates: Handlebars,
config: ConfigItems,
_env: ConfigBuilder,
_usr: ConfigBuilder,
}
#[derive(Debug, Default, Deserialize)]
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ConfigBuilder {
$($name: Option<$ty>),+
$(
#[serde(skip_serializing_if = "Option::is_none")]
$name: Option<$ty>
),+
}
impl ConfigBuilder {
@@ -35,8 +39,7 @@ macro_rules! make_config {
let mut builder = ConfigBuilder::default();
$(
let $name = stringify!($name).to_uppercase();
builder.$name = make_config!{ @env &$name, $($default_fn)? };
builder.$name = get_env(&stringify!($name).to_uppercase());
)+
builder
@@ -48,19 +51,36 @@ macro_rules! make_config {
serde_json::from_str(&config_str).map_err(Into::into)
}
fn merge(&mut self, other: Self) {
/// Merges the values of both builders into a new builder.
/// If both have the same element, `other` wins.
fn merge(&self, other: &Self) -> Self {
let mut builder = self.clone();
$(
if let v @Some(_) = other.$name {
self.$name = v;
if let v @Some(_) = &other.$name {
builder.$name = v.clone();
}
)+
builder
}
fn build(self) -> ConfigItems {
/// Returns a new builder with all the elements from self,
/// except those that are equal in both sides
fn remove(&self, other: &Self) -> Self {
let mut builder = ConfigBuilder::default();
$(
if &self.$name != &other.$name {
builder.$name = self.$name.clone();
}
)+
builder
}
fn build(&self) -> ConfigItems {
let mut config = ConfigItems::default();
let _domain_set = self.domain.is_some();
$(
config.$name = make_config!{ @build self.$name, &config, $($default_fn)? };
config.$name = make_config!{ @build self.$name.clone(), &config, $none_action, $($default)? };
)+
config.domain_set = _domain_set;
@@ -68,33 +88,28 @@ macro_rules! make_config {
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConfigItems { $(pub $name: $ty),+ }
#[derive(Debug, Clone, Default)]
pub struct ConfigItems { $(pub $name: make_config!{@type $ty, $none_action} ),+ }
paste::item! {
#[allow(unused)]
impl Config {
$(
pub fn $name(&self) -> $ty {
pub fn $name(&self) -> make_config!{@type $ty, $none_action} {
self.inner.read().unwrap().config.$name.clone()
}
pub fn [<set_ $name>](&self, value: $ty) {
self.inner.write().unwrap().config.$name = value;
}
)+
pub fn load() -> Result<Self, Error> {
// TODO: Get config.json from CONFIG_PATH env var or -c <CONFIG> console option
// Loading from file
let mut builder = match ConfigBuilder::from_file(&CONFIG_PATH) {
Ok(builder) => builder,
Err(_) => ConfigBuilder::default()
};
// Loading from env and file
let _env = ConfigBuilder::from_env();
let _usr = ConfigBuilder::from_file(&CONFIG_PATH).unwrap_or_default();
// Env variables overwrite config file
builder.merge(ConfigBuilder::from_env());
// Create merged config, config file overwrites env
let builder = _env.merge(&_usr);
// Fill any missing with defaults
let config = builder.build();
validate_config(&config)?;
@@ -102,24 +117,46 @@ macro_rules! make_config {
inner: RwLock::new(Inner {
templates: load_templates(&config.templates_folder),
config,
_env,
_usr,
}),
})
}
}
}
};
pub fn prepare_json(&self) -> serde_json::Value {
let cfg = {
let inner = &self.inner.read().unwrap();
inner._env.merge(&inner._usr)
};
( @env $name:expr, $default_fn:expr ) => { get_env($name) };
( @env $name:expr, ) => {
match get_env($name) {
v @ Some(_) => Some(v),
None => None
fn _get_form_type(rust_type: &str) -> &'static str {
match rust_type {
"String" => "text",
"bool" => "checkbox",
_ => "number"
}
}
json!([ $( {
"editable": $editable,
"name": stringify!($name),
"value": cfg.$name,
"default": make_config!{ @default &cfg, $none_action, $($default)? },
"type": _get_form_type(stringify!($ty)),
}, )+ ])
}
}
};
( @build $value:expr,$config:expr, $default_fn:expr ) => {
// Wrap the optionals in an Option type
( @type $ty:ty, option) => { Option<$ty> };
( @type $ty:ty, $id:ident) => { $ty };
// Generate the values depending on none_action
( @build $value:expr, $config:expr, option, ) => { $value };
( @build $value:expr, $config:expr, def, $default:expr ) => { $value.unwrap_or($default) };
( @build $value:expr, $config:expr, auto, $default_fn:expr ) => {{
match $value {
Some(v) => v,
None => {
@@ -127,61 +164,70 @@ macro_rules! make_config {
f($config)
}
}
};
}};
// Get a default value
( @default $config:expr, option, ) => { serde_json::Value::Null };
( @default $config:expr, def, $default:expr ) => { $default };
( @default $config:expr, auto, $default_fn:expr ) => {{
let f: &Fn(ConfigItems) -> _ = &$default_fn;
f($config.build())
}};
( @build $value:expr, $config:expr, ) => { $value.unwrap_or(None) };
}
//STRUCTURE: name: type, is_editable, none_action, <default_value (Optional)>
// Where none_action applied when the value wasn't provided and can be:
// def: Use a default value
// auto: Value is auto generated based on other values
// option: Value is optional
make_config! {
data_folder: String, |_| "data".to_string();
database_url: String, |c| format!("{}/{}", c.data_folder, "db.sqlite3");
icon_cache_folder: String, |c| format!("{}/{}", c.data_folder, "icon_cache");
attachments_folder: String, |c| format!("{}/{}", c.data_folder, "attachments");
templates_folder: String, |c| format!("{}/{}", c.data_folder, "templates");
data_folder: String, false, def, "data".to_string();
rsa_key_filename: String, |c| format!("{}/{}", c.data_folder, "rsa_key");
private_rsa_key: String, |c| format!("{}.der", c.rsa_key_filename);
private_rsa_key_pem: String, |c| format!("{}.pem", c.rsa_key_filename);
public_rsa_key: String, |c| format!("{}.pub.der", c.rsa_key_filename);
database_url: String, false, auto, |c| format!("{}/{}", c.data_folder, "db.sqlite3");
icon_cache_folder: String, false, auto, |c| format!("{}/{}", c.data_folder, "icon_cache");
attachments_folder: String, false, auto, |c| format!("{}/{}", c.data_folder, "attachments");
templates_folder: String, false, auto, |c| format!("{}/{}", c.data_folder, "templates");
rsa_key_filename: String, false, auto, |c| format!("{}/{}", c.data_folder, "rsa_key");
websocket_enabled: bool, |_| false;
websocket_address: String, |_| "0.0.0.0".to_string();
websocket_port: u16, |_| 3012;
websocket_enabled: bool, false, def, false;
websocket_address: String, false, def, "0.0.0.0".to_string();
websocket_port: u16, false, def, 3012;
web_vault_folder: String, |_| "web-vault/".to_string();
web_vault_enabled: bool, |_| true;
web_vault_folder: String, false, def, "web-vault/".to_string();
web_vault_enabled: bool, true, def, true;
icon_cache_ttl: u64, |_| 2_592_000;
icon_cache_negttl: u64, |_| 259_200;
icon_cache_ttl: u64, true, def, 2_592_000;
icon_cache_negttl: u64, true, def, 259_200;
disable_icon_download: bool, |_| false;
signups_allowed: bool, |_| true;
invitations_allowed: bool, |_| true;
password_iterations: i32, |_| 100_000;
show_password_hint: bool, |_| true;
disable_icon_download: bool, true, def, false;
signups_allowed: bool, true, def, true;
invitations_allowed: bool, true, def, true;
password_iterations: i32, true, def, 100_000;
show_password_hint: bool, true, def, true;
domain: String, |_| "http://localhost".to_string();
domain_set: bool, |_| false;
domain: String, true, def, "http://localhost".to_string();
domain_set: bool, false, def, false;
reload_templates: bool, |_| false;
reload_templates: bool, true, def, false;
extended_logging: bool, |_| true;
log_file: Option<String>;
extended_logging: bool, false, def, true;
log_file: String, false, option;
admin_token: Option<String>;
admin_token: String, true, option;
yubico_client_id: Option<String>;
yubico_secret_key: Option<String>;
yubico_server: Option<String>;
yubico_client_id: String, true, option;
yubico_secret_key: String, true, option;
yubico_server: String, true, option;
// Mail settings
smtp_host: Option<String>;
smtp_ssl: bool, |_| true;
smtp_port: u16, |c| if c.smtp_ssl {587} else {25};
smtp_from: String, |_| String::new();
smtp_from_name: String, |_| "Bitwarden_RS".to_string();
smtp_username: Option<String>;
smtp_password: Option<String>;
smtp_host: String, true, option;
smtp_ssl: bool, true, def, true;
smtp_port: u16, true, auto, |c| if c.smtp_ssl {587} else {25};
smtp_from: String, true, def, String::new();
smtp_from_name: String, true, def, "Bitwarden_RS".to_string();
smtp_username: String, true, option;
smtp_password: String, true, option;
}
fn validate_config(cfg: &ConfigItems) -> Result<(), Error> {
@@ -201,18 +247,26 @@ fn validate_config(cfg: &ConfigItems) -> Result<(), Error> {
}
impl Config {
pub fn get_config(&self) -> String {
let cfg = &self.inner.read().unwrap().config;
serde_json::to_string_pretty(cfg).unwrap()
}
pub fn update_config(&self, other: ConfigBuilder) -> Result<(), Error> {
let config = other.build();
// Remove default values
let builder = other.remove(&self.inner.read().unwrap()._env);
// Serialize now before we consume the builder
let config_str = serde_json::to_string_pretty(&builder)?;
// Prepare the combined config
let config = {
let env = &self.inner.read().unwrap()._env;
env.merge(&builder).build()
};
validate_config(&config)?;
let config_str = serde_json::to_string_pretty(&config)?;
self.inner.write().unwrap().config = config.clone();
// Save both the user and the combined config
{
let mut writer = self.inner.write().unwrap();
writer.config = config;
writer._usr = builder;
}
//Save to file
use std::{fs::File, io::Write};
@@ -222,6 +276,15 @@ impl Config {
Ok(())
}
pub fn private_rsa_key(&self) -> String {
format!("{}.der", CONFIG.rsa_key_filename())
}
pub fn private_rsa_key_pem(&self) -> String {
format!("{}.pem", CONFIG.rsa_key_filename())
}
pub fn public_rsa_key(&self) -> String {
format!("{}.pub.der", CONFIG.rsa_key_filename())
}
pub fn mail_enabled(&self) -> bool {
self.inner.read().unwrap().config.smtp_host.is_some()
}
@@ -242,10 +305,15 @@ impl Config {
}
}
use handlebars::{
Context, Handlebars, Helper, HelperDef, HelperResult, Output, RenderContext, RenderError, Renderable,
};
fn load_templates(path: &str) -> Handlebars {
let mut hb = Handlebars::new();
// Error on missing params
hb.set_strict_mode(true);
hb.register_helper("case", Box::new(CaseHelper));
macro_rules! reg {
($name:expr) => {{
@@ -272,3 +340,28 @@ fn load_templates(path: &str) -> Handlebars {
hb
}
#[derive(Clone, Copy)]
pub struct CaseHelper;
impl HelperDef for CaseHelper {
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Handlebars,
ctx: &Context,
rc: &mut RenderContext<'reg>,
out: &mut Output,
) -> HelperResult {
let param = h
.param(0)
.ok_or_else(|| RenderError::new("Param not found for helper \"case\""))?;
let value = param.value().clone();
if h.params().iter().skip(1).any(|x| x.value() == &value) {
h.template().map(|t| t.render(r, ctx, rc, out)).unwrap_or(Ok(()))
} else {
Ok(())
}
}
}