diff --git a/Cargo.toml b/Cargo.toml index 55e4a28..11266cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -63,6 +63,7 @@ derive_more = "0.99.17" dashmap = "5.5" tokio = "1.38" ctor = "0.2.8" +better_default = "1.0.5" # optional dependencies openssl = { version = "0.10.64", optional = true } diff --git a/src/errors.rs b/src/errors.rs index 28cd2f8..76d292d 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -260,6 +260,12 @@ pub enum RvError { source: actix_web::http::header::ToStrError, }, + #[error("Some url error happened, {:?}", .source)] + UrlError { + #[from] + source: url::ParseError, + }, + /// Database Errors Begin /// #[error("Database type is not support now. Please try postgressql or mysql again.")] @@ -391,3 +397,17 @@ impl From>> for RvError { RvError::ErrRwLockReadPoison } } + +#[macro_export] +macro_rules! rv_error_response { + ($message:expr) => { + RvError::ErrResponse($message.to_string()) + }; +} + +#[macro_export] +macro_rules! rv_error_response_status { + ($status:expr, $message:expr) => { + RvError::ErrResponseStatus($status, $message.to_string()) + }; +} diff --git a/src/http/logical.rs b/src/http/logical.rs index bd7fc52..41ef429 100644 --- a/src/http/logical.rs +++ b/src/http/logical.rs @@ -30,7 +30,7 @@ struct Auth { renewable: bool, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] struct LogicalResponse { renewable: bool, lease_id: String, @@ -39,12 +39,6 @@ struct LogicalResponse { data: HashMap, } -impl Default for LogicalResponse { - fn default() -> Self { - Self { renewable: false, lease_id: String::new(), lease_duration: 0, auth: None, data: HashMap::new() } - } -} - async fn logical_request_handler( req: HttpRequest, mut body: web::Bytes, diff --git a/src/logical/auth.rs b/src/logical/auth.rs index 35f8dcb..fd21be6 100644 --- a/src/logical/auth.rs +++ b/src/logical/auth.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize}; use super::lease::Lease; -#[derive(Debug, Clone, Serialize, Deserialize, Deref, DerefMut)] +#[derive(Debug, Clone, Default, Serialize, Deserialize, Deref, DerefMut)] pub struct Auth { #[deref] #[deref_mut] @@ -18,16 +18,3 @@ pub struct Auth { pub internal_data: HashMap, pub metadata: HashMap, } - -impl Default for Auth { - fn default() -> Self { - Self { - lease: Lease::default(), - client_token: String::new(), - display_name: String::new(), - policies: Vec::new(), - internal_data: HashMap::new(), - metadata: HashMap::new(), - } - } -} diff --git a/src/logical/connection.rs b/src/logical/connection.rs index 6779aeb..e9d69ac 100644 --- a/src/logical/connection.rs +++ b/src/logical/connection.rs @@ -1,12 +1,7 @@ use openssl::x509::X509; +#[derive(Default)] pub struct Connection { pub peer_addr: String, pub peer_tls_cert: Option>, } - -impl Default for Connection { - fn default() -> Self { - Self { peer_addr: String::new(), peer_tls_cert: None } - } -} diff --git a/src/logical/lease.rs b/src/logical/lease.rs index bdc40b0..cd554e7 100644 --- a/src/logical/lease.rs +++ b/src/logical/lease.rs @@ -1,32 +1,23 @@ use std::time::{Duration, SystemTime}; use serde::{Deserialize, Serialize}; +use better_default::Default; -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct Lease { #[serde(rename = "lease")] pub ttl: Duration, #[serde(skip)] pub max_ttl: Duration, + #[default(true)] pub renewable: bool, #[serde(skip)] pub increment: Duration, #[serde(skip)] + #[default(Some(SystemTime::now()))] pub issue_time: Option, } -impl Default for Lease { - fn default() -> Self { - Self { - ttl: Duration::new(0, 0), - max_ttl: Duration::new(0, 0), - renewable: true, - increment: Duration::new(0, 0), - issue_time: Some(SystemTime::now()), - } - } -} - impl Lease { pub fn new() -> Self { Self { ..Default::default() } diff --git a/src/logical/request.rs b/src/logical/request.rs index af66778..a4970ac 100644 --- a/src/logical/request.rs +++ b/src/logical/request.rs @@ -2,6 +2,7 @@ use std::{collections::HashMap, sync::Arc}; use serde_json::{Map, Value}; use tokio::task::JoinHandle; +use better_default::Default; use super::{Operation, Path}; use crate::{ @@ -10,9 +11,11 @@ use crate::{ storage::{Storage, StorageEntry}, }; +#[derive(Default)] pub struct Request { pub id: String, pub name: String, + #[default(Operation::Read)] pub operation: Operation, pub path: String, pub match_path: Option>, @@ -27,27 +30,6 @@ pub struct Request { pub tasks: Vec>, } -impl Default for Request { - fn default() -> Self { - Request { - id: String::new(), - name: String::new(), - operation: Operation::Read, - path: String::new(), - match_path: None, - headers: None, - body: None, - data: None, - client_token: String::new(), - storage: None, - connection: None, - secret: None, - auth: None, - tasks: Vec::new(), - } - } -} - impl Request { pub fn new(path: &str) -> Self { Self { path: path.to_string(), ..Default::default() } diff --git a/src/logical/response.rs b/src/logical/response.rs index e4c7f11..c9a88fe 100644 --- a/src/logical/response.rs +++ b/src/logical/response.rs @@ -3,6 +3,7 @@ use std::collections::HashMap; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; +use better_default::Default; use crate::{ errors::RvError, @@ -15,7 +16,7 @@ lazy_static! { static ref HTTP_STATUS_CODE: &'static str = "http_status_code"; } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct Response { #[serde(default)] pub request_id: String, @@ -30,20 +31,6 @@ pub struct Response { pub warnings: Vec, } -impl Default for Response { - fn default() -> Self { - Response { - request_id: String::new(), - headers: None, - data: None, - auth: None, - secret: None, - redirect: String::new(), - warnings: Vec::new(), - } - } -} - impl Response { pub fn new() -> Self { Self { ..Default::default() } diff --git a/src/modules/auth/expiration.rs b/src/modules/auth/expiration.rs index af742a6..6ddb6cc 100644 --- a/src/modules/auth/expiration.rs +++ b/src/modules/auth/expiration.rs @@ -9,6 +9,7 @@ use delay_timer::prelude::*; use derive_more::Deref; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; +use better_default::Default; use super::TokenStore; use crate::{ @@ -44,6 +45,7 @@ struct LeaseEntry { pub expire_time: SystemTime, } +#[derive(Default)] pub struct ExpirationTask { pub last_task_id: u64, pub task_id_map: HashMap, @@ -51,49 +53,24 @@ pub struct ExpirationTask { pub task_timer: DelayTimer, } +#[derive(Default)] pub struct ExpirationManagerInner { pub router: Option>, pub id_view: Option>, pub token_view: Option>, + #[default(Arc::new(RwLock::new(None)))] pub token_store: Arc>>>, + #[default(RwLock::new(ExpirationTask::default()))] pub task: RwLock, } -#[derive(Deref)] +#[derive(Default, Deref)] pub struct ExpirationManager { #[deref] + #[default(Arc::new(ExpirationManagerInner::default()))] pub inner: Arc, } -impl Default for ExpirationTask { - fn default() -> Self { - Self { - last_task_id: 0, - task_id_map: HashMap::new(), - task_id_remove_pending: Vec::new(), - task_timer: DelayTimerBuilder::default().build(), - } - } -} - -impl Default for ExpirationManagerInner { - fn default() -> Self { - Self { - router: None, - id_view: None, - token_view: None, - token_store: Arc::new(RwLock::new(None)), - task: RwLock::new(ExpirationTask::default()), - } - } -} - -impl Default for ExpirationManager { - fn default() -> Self { - Self { inner: Arc::new(ExpirationManagerInner::default()) } - } -} - impl LeaseEntry { fn renewable(&self) -> bool { let now = SystemTime::now(); diff --git a/src/modules/auth/token_store.rs b/src/modules/auth/token_store.rs index db6ffa8..95e24f0 100644 --- a/src/modules/auth/token_store.rs +++ b/src/modules/auth/token_store.rs @@ -60,7 +60,7 @@ struct TokenReqData { renewable: bool, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct TokenEntry { pub id: String, pub parent: String, @@ -72,6 +72,7 @@ pub struct TokenEntry { pub ttl: u64, } +#[derive(Default)] pub struct TokenStoreInner { pub router: Arc, pub view: Option>, @@ -79,46 +80,12 @@ pub struct TokenStoreInner { pub expiration: Arc, } -#[derive(Deref)] +#[derive(Default, Deref)] pub struct TokenStore { #[deref] pub inner: Arc, } -impl Default for TokenEntry { - fn default() -> Self { - Self { - id: String::new(), - parent: String::new(), - policies: Vec::new(), - path: String::new(), - meta: HashMap::new(), - display_name: String::new(), - num_uses: 0, - ttl: 0, - } - } -} - -impl Default for TokenStoreInner { - fn default() -> Self { - Self { - router: Arc::new(Router::new()), - view: None, - salt: String::new(), - expiration: Arc::new(ExpirationManager::default()), - } - } -} - -impl Default for TokenStore { - fn default() -> Self { - let inner = TokenStoreInner { ..TokenStoreInner::default() }; - - Self { inner: Arc::new(inner) } - } -} - impl TokenStore { pub fn new(core: &Core, expiration: Arc) -> Result { if core.system_view.is_none() { diff --git a/src/modules/credential/approle/path_role.rs b/src/modules/credential/approle/path_role.rs index 6b56cff..34d01aa 100644 --- a/src/modules/credential/approle/path_role.rs +++ b/src/modules/credential/approle/path_role.rs @@ -3,6 +3,7 @@ use std::{collections::HashMap, mem, sync::Arc, time::Duration}; use derive_more::{Deref, DerefMut}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; +use better_default::Default; use super::{ validation::{create_hmac, verify_cidr_role_secret_id_subset, SecretIdStorageEntry}, @@ -23,7 +24,7 @@ use crate::{ }, }; -#[derive(Debug, Clone, Serialize, Deserialize, Deref, DerefMut)] +#[derive(Debug, Clone, Default, Serialize, Deserialize, Deref, DerefMut)] pub struct RoleEntry { // Name of the role. This field is not persisted on disk. After the role is read out of disk, // the sanitized version of name is set in this field for subsequent use of role name @@ -41,6 +42,7 @@ pub struct RoleEntry { pub policies: Vec, // lower_case_role_name enforces the lower casing of role names for all the + #[default(true)] pub lower_case_role_name: bool, // A constraint, if set, requires 'secret_id' credential to be presented during login @@ -83,38 +85,11 @@ pub struct RoleEntry { pub token_params: TokenParams, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct RoleIdEntry { pub name: String, } -impl Default for RoleEntry { - fn default() -> Self { - Self { - name: String::new(), - role_id: String::new(), - hmac_key: String::new(), - policies: Vec::new(), - lower_case_role_name: true, - bind_secret_id: false, - secret_id_num_uses: 0, - secret_id_prefix: String::new(), - bound_cidr_list_old: String::new(), - bound_cidr_list: Vec::new(), - secret_id_bound_cidrs: Vec::new(), - secret_id_ttl: Duration::from_secs(0), - period: Duration::from_secs(0), - token_params: TokenParams::default(), - } - } -} - -impl Default for RoleIdEntry { - fn default() -> Self { - Self { name: String::new() } - } -} - impl RoleEntry { pub fn validate_role_constraints(&self) -> Result<(), RvError> { if self.bind_secret_id diff --git a/src/modules/credential/approle/validation.rs b/src/modules/credential/approle/validation.rs index 53052f0..f562379 100644 --- a/src/modules/credential/approle/validation.rs +++ b/src/modules/credential/approle/validation.rs @@ -8,6 +8,7 @@ use std::{ use openssl::{hash::MessageDigest, pkey::PKey, sign::Signer}; use serde::{Deserialize, Serialize}; +use better_default::Default; use super::{AppRoleBackendInner, SECRET_ID_ACCESSOR_LOCAL_PREFIX, SECRET_ID_ACCESSOR_PREFIX, SECRET_ID_LOCAL_PREFIX}; use crate::{ @@ -22,7 +23,7 @@ const MAX_HMAC_INPUT_LENGTH: usize = 4096; // secretIDStorageEntry represents the information stored in storage // when a secret_id is created. The structure of the secret_id storage // entry is the same for all the types of secret_ids generated. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct SecretIdStorageEntry { // Accessor for the secret_id. It is a random uuid serving as // a secondary index for the secret_id. This uniquely identifies @@ -42,16 +43,19 @@ pub struct SecretIdStorageEntry { // The time when the secret_id was created #[serde(serialize_with = "serialize_system_time", deserialize_with = "deserialize_system_time")] + #[default(SystemTime::now())] pub creation_time: SystemTime, // The time when the secret_id becomes eligible for tidy operation. // Tidying is performed by the PeriodicFunc of the backend which is 1 // minute apart. #[serde(serialize_with = "serialize_system_time", deserialize_with = "deserialize_system_time")] + #[default(SystemTime::now())] pub expiration_time: SystemTime, // The time representing the last time this storage entry was modified #[serde(serialize_with = "serialize_system_time", deserialize_with = "deserialize_system_time")] + #[default(SystemTime::now())] pub last_updated_time: SystemTime, // metadata that belongs to the secret_id @@ -70,35 +74,13 @@ pub struct SecretIdStorageEntry { // unique secret_id. Note that secret_id should never be stored in plaintext // anywhere in the backend. secret_id_hmac will be used as an index to fetch the // properties of the secret_id and to delete the secret_id. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct SecretIdAccessorStorageEntry { // Hash of the secret_id which can be used to find the storage index at which // properties of secret_id is stored. pub secret_id_hmac: String, } -impl Default for SecretIdStorageEntry { - fn default() -> Self { - Self { - secret_id_accessor: String::new(), - secret_id_num_uses: 0, - secret_id_ttl: Duration::from_secs(0), - creation_time: SystemTime::now(), - expiration_time: SystemTime::now(), - last_updated_time: SystemTime::now(), - metadata: HashMap::new(), - cidr_list: Vec::new(), - token_cidr_list: Vec::new(), - } - } -} - -impl Default for SecretIdAccessorStorageEntry { - fn default() -> Self { - Self { secret_id_hmac: String::new() } - } -} - impl AppRoleBackendInner { // get_secret_id_storage_entry fetches the secret ID properties from physical // storage. The entry will be indexed based on the given HMACs of both role diff --git a/src/modules/credential/userpass/path_users.rs b/src/modules/credential/userpass/path_users.rs index 885a2fa..80ffca7 100644 --- a/src/modules/credential/userpass/path_users.rs +++ b/src/modules/credential/userpass/path_users.rs @@ -14,7 +14,7 @@ use crate::{ //const DEFAULT_MAX_TTL: Duration = Duration::from_secs(365*24*60*60 as u64); -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct UserEntry { pub password_hash: String, pub policies: Vec, @@ -24,17 +24,6 @@ pub struct UserEntry { pub max_ttl: Duration, } -impl Default for UserEntry { - fn default() -> Self { - Self { - password_hash: String::new(), - policies: Vec::new(), - ttl: Duration::from_secs(0), - max_ttl: Duration::from_secs(0), - } - } -} - impl UserPassBackend { pub fn users_path(&self) -> Path { let userpass_backend_ref1 = Arc::clone(&self.inner); diff --git a/src/modules/pki/path_roles.rs b/src/modules/pki/path_roles.rs index 7d88c84..1579e6c 100644 --- a/src/modules/pki/path_roles.rs +++ b/src/modules/pki/path_roles.rs @@ -2,6 +2,7 @@ use std::{collections::HashMap, sync::Arc, time::Duration}; use humantime::parse_duration; use serde::{Deserialize, Serialize}; +use better_default::Default; use super::{util::DEFAULT_MAX_TTL, PkiBackend, PkiBackendInner}; use crate::{ @@ -13,26 +14,37 @@ use crate::{ utils::{deserialize_duration, serialize_duration}, }; -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct RoleEntry { #[serde(serialize_with = "serialize_duration", deserialize_with = "deserialize_duration")] pub ttl: Duration, #[serde(serialize_with = "serialize_duration", deserialize_with = "deserialize_duration")] + #[default(DEFAULT_MAX_TTL)] pub max_ttl: Duration, #[serde(serialize_with = "serialize_duration", deserialize_with = "deserialize_duration")] pub not_before_duration: Duration, + #[default("rsa".to_string())] pub key_type: String, + #[default(2048)] pub key_bits: u32, + #[default(256)] pub signature_bits: u32, pub use_pss: bool, + #[default(true)] pub allow_localhost: bool, + #[default(true)] pub allow_bare_domains: bool, + #[default(true)] pub allow_subdomains: bool, + #[default(true)] pub allow_any_name: bool, + #[default(true)] pub allow_ip_sans: bool, pub server_flag: bool, pub client_flag: bool, + #[default(true)] pub use_csr_sans: bool, + #[default(true)] pub use_csr_common_name: bool, pub country: String, pub province: String, @@ -41,44 +53,12 @@ pub struct RoleEntry { pub ou: String, pub street_address: String, pub postal_code: String, + #[default(true)] pub no_store: bool, pub generate_lease: bool, pub not_after: String, } -impl Default for RoleEntry { - fn default() -> Self { - Self { - ttl: Duration::from_secs(0), - max_ttl: DEFAULT_MAX_TTL, - not_before_duration: Duration::from_secs(0), - key_type: "rsa".to_string(), - key_bits: 2048, - signature_bits: 256, - use_pss: false, - allow_localhost: true, - allow_bare_domains: true, - allow_subdomains: true, - allow_any_name: true, - allow_ip_sans: true, - server_flag: false, - client_flag: false, - use_csr_sans: true, - use_csr_common_name: true, - country: "".to_string(), - province: "".to_string(), - locality: "".to_string(), - organization: "".to_string(), - ou: "".to_string(), - street_address: "".to_string(), - postal_code: "".to_string(), - no_store: true, - generate_lease: false, - not_after: "".to_string(), - } - } -} - impl PkiBackend { pub fn roles_path(&self) -> Path { let pki_backend_ref1 = Arc::clone(&self.inner); diff --git a/src/router.rs b/src/router.rs index a88984d..b5e3467 100644 --- a/src/router.rs +++ b/src/router.rs @@ -23,6 +23,7 @@ struct RouterEntry { mount_entry: Arc>, } +#[derive(Default)] pub struct Router { root: Arc>>, } @@ -35,7 +36,7 @@ impl RouterEntry { impl Router { pub fn new() -> Self { - Self { root: Arc::new(RwLock::new(Trie::new())) } + Router::default() } pub fn mount( diff --git a/src/storage/mod.rs b/src/storage/mod.rs index bfc5362..50ca2fe 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -37,19 +37,13 @@ pub trait Storage: Send + Sync { } /// This struct is used to describe a specific storage entry -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct StorageEntry { pub key: String, pub value: Vec, } -impl Default for StorageEntry { - fn default() -> Self { - Self { key: String::new(), value: Vec::new() } - } -} - impl StorageEntry { pub fn new(k: &str, v: &impl Serialize) -> Result { let data = serde_json::to_string(v)?; diff --git a/src/utils/cert.rs b/src/utils/cert.rs index 84c0331..3fa900e 100644 --- a/src/utils/cert.rs +++ b/src/utils/cert.rs @@ -21,6 +21,7 @@ use openssl::{ }; use serde::{ser::SerializeTuple, Deserialize, Deserializer, Serialize, Serializer}; use serde_bytes::ByteBuf; +use better_default::Default; use crate::errors::RvError; @@ -33,13 +34,15 @@ extern "C" { pub fn X509_check_ca(x509: *mut openssl_sys::X509) -> c_int; } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct CertBundle { #[serde(serialize_with = "serialize_x509", deserialize_with = "deserialize_x509")] + #[default(X509_DEFAULT.clone())] pub certificate: X509, #[serde(serialize_with = "serialize_vec_x509", deserialize_with = "deserialize_vec_x509")] pub ca_chain: Vec, #[serde(serialize_with = "serialize_pkey", deserialize_with = "deserialize_pkey")] + #[default(PKEY_DEFAULT.clone())] pub private_key: PKey, #[serde(default)] pub private_key_type: String, @@ -106,16 +109,10 @@ pub fn is_ca_cert(cert: &X509) -> bool { unsafe { X509_check_ca(cert.as_ptr()) != 0 } } -impl Default for CertBundle { - fn default() -> Self { - CertBundle { - certificate: X509_DEFAULT.clone(), - ca_chain: Vec::new(), - private_key: PKEY_DEFAULT.clone(), - private_key_type: String::new(), - serial_number: String::new(), - } - } +pub fn generate_serial_number() -> BigNum { + let mut sn = BigNum::new().unwrap(); + sn.rand(159, MsbOption::MAYBE_ZERO, false).unwrap(); + sn } impl CertBundle { @@ -169,50 +166,36 @@ impl CertBundle { } } +#[derive(Default)] pub struct Certificate { + #[default(3)] pub version: i32, + #[default(generate_serial_number())] pub serial_number: BigNum, + #[default(X509NameBuilder::new().unwrap().build())] pub issuer: X509Name, + #[default(X509NameBuilder::new().unwrap().build())] pub subject: X509Name, + #[default(SystemTime::now())] pub not_before: SystemTime, + #[default(SystemTime::now())] pub not_after: SystemTime, pub extensions: Vec, + #[default(Asn1OctetString::new_from_bytes("".as_bytes()).unwrap())] pub subject_key_id: Asn1OctetString, + #[default(Asn1OctetString::new_from_bytes("".as_bytes()).unwrap())] pub authority_key_id: Asn1OctetString, pub dns_sans: Vec, pub email_sans: Vec, pub ip_sans: Vec, pub uri_sans: Vec, pub is_ca: bool, + #[default("rsa".to_string())] pub key_type: String, + #[default(2048)] pub key_bits: u32, } -impl Default for Certificate { - fn default() -> Self { - let mut sn = BigNum::new().unwrap(); - sn.rand(159, MsbOption::MAYBE_ZERO, false).unwrap(); - Self { - version: 3, - serial_number: sn, - issuer: X509NameBuilder::new().unwrap().build(), - subject: X509NameBuilder::new().unwrap().build(), - not_before: SystemTime::now(), - not_after: SystemTime::now(), - extensions: Vec::new(), - subject_key_id: Asn1OctetString::new_from_bytes("".as_bytes()).unwrap(), - authority_key_id: Asn1OctetString::new_from_bytes("".as_bytes()).unwrap(), - dns_sans: Vec::new(), - email_sans: Vec::new(), - ip_sans: Vec::new(), - uri_sans: Vec::new(), - is_ca: false, - key_type: "rsa".to_string(), - key_bits: 2048, - } - } -} - impl Certificate { pub fn to_x509( &mut self, diff --git a/src/utils/key.rs b/src/utils/key.rs index b27141d..cee7a05 100644 --- a/src/utils/key.rs +++ b/src/utils/key.rs @@ -9,11 +9,13 @@ use openssl::{ symm::{decrypt, decrypt_aead, encrypt, encrypt_aead, Cipher}, }; use serde::{Deserialize, Serialize}; +use better_default::Default; use crate::{errors::RvError, utils::generate_uuid}; -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct KeyBundle { + #[default(generate_uuid())] pub id: String, pub name: String, pub key_type: String, @@ -29,19 +31,6 @@ pub enum EncryptExtraData<'a> { Flag(bool), } -impl Default for KeyBundle { - fn default() -> Self { - KeyBundle { - id: generate_uuid(), - name: String::new(), - key_type: String::new(), - key: Vec::new(), - iv: Vec::new(), - bits: 0, - } - } -} - fn key_bits_default(key_type: &str) -> u32 { return match key_type { "rsa" => 2048, diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 54849ce..45bf24f 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -23,6 +23,7 @@ pub mod sock_addr; pub mod string; pub mod token_util; pub mod unix_sock_addr; +pub mod ocsp; pub fn generate_uuid() -> String { let mut buf = [0u8; 16]; diff --git a/src/utils/ocsp.rs b/src/utils/ocsp.rs index 1e769b8..ab9d4d3 100644 --- a/src/utils/ocsp.rs +++ b/src/utils/ocsp.rs @@ -1,30 +1,23 @@ +use better_default::Default; + use openssl::{ x509::X509, }; #[repr(u32)] +#[derive(Debug)] pub enum FailureMode { OcspFailOpenNotSet = 0, FailOpenTrue = 1, FailOpenFalse = 2, } +#[derive(Default, Debug)] pub struct OcspConfig { pub enable: bool, pub extra_ca: Vec, pub servers_override: Vec, + #[default(FailureMode::OcspFailOpenNotSet)] pub failure_mode: FailureMode, pub query_all_servers: bool, } - -impl Default for OcspConfig { - fn default() -> Self { - OcspConfig { - enable: false, - extra_ca: Vec::new(), - servers_override: Vec::new(), - failure_mode: FailureMode::OcspFailOpenNotSet, - query_all_servers: false, - } - } -} diff --git a/src/utils/salt.rs b/src/utils/salt.rs index 10c02b2..770f84d 100644 --- a/src/utils/salt.rs +++ b/src/utils/salt.rs @@ -2,6 +2,7 @@ //! use derivative::Derivative; +use better_default::Default; use openssl::{ hash::{hash, MessageDigest}, nid::Nid, @@ -17,39 +18,28 @@ use crate::{ static DEFAULT_LOCATION: &str = "salt"; -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Default)] pub struct Salt { pub config: Config, + #[default(generate_uuid())] pub salt: String, + #[default(true)] pub generated: bool, } -#[derive(Derivative)] +#[derive(Derivative, Default)] #[derivative(Debug, Clone)] pub struct Config { + #[default(DEFAULT_LOCATION.to_string())] pub location: String, #[derivative(Debug = "ignore")] + #[default(MessageDigest::sha256())] pub hash_type: MessageDigest, #[derivative(Debug = "ignore")] + #[default(MessageDigest::sha256())] pub hmac_type: MessageDigest, } -impl Default for Salt { - fn default() -> Self { - Self { salt: generate_uuid(), generated: true, config: Config::default() } - } -} - -impl Default for Config { - fn default() -> Self { - Self { - location: DEFAULT_LOCATION.to_string(), - hash_type: MessageDigest::sha256(), - hmac_type: MessageDigest::sha256(), - } - } -} - impl Salt { pub fn new(storage: Option<&dyn Storage>, config: Option<&Config>) -> Result { let mut salt = Salt::default();