From d2fd6e80731e1814243483113dcb3d9350731349 Mon Sep 17 00:00:00 2001 From: Jin Jiu Date: Mon, 27 Nov 2023 08:24:10 +0800 Subject: [PATCH 1/3] Fix code formatting. --- src/modules/auth/expiration.rs | 10 +- src/modules/auth/token_store.rs | 2 +- src/modules/pki/mod.rs | 146 +++++++++++++++--------------- src/modules/pki/path_config_ca.rs | 2 +- src/modules/pki/path_roles.rs | 2 +- src/storage/mod.rs | 18 ++-- src/utils/cert.rs | 18 ++-- src/utils/key.rs | 12 +-- 8 files changed, 102 insertions(+), 108 deletions(-) diff --git a/src/modules/auth/expiration.rs b/src/modules/auth/expiration.rs index b1a9691..6b0c3ec 100644 --- a/src/modules/auth/expiration.rs +++ b/src/modules/auth/expiration.rs @@ -9,7 +9,7 @@ use serde_json::{Value, Map}; use serde::{Serialize, Deserialize}; use delay_timer::prelude::*; use crate::{ - utils::{generate_uuid, serialize_system_time, deserialize_system_time}, + utils::{generate_uuid, serialize_system_time, deserialize_system_time}, logical::{ Auth, SecretData, Request, Response, }, @@ -163,7 +163,7 @@ impl ExpirationTask { } fn remove_task(&mut self, lease_id: &str) -> Result<(), RvError> { - log::debug!("remove task, lease_id: {}", lease_id); + log::debug!("remove task, lease_id: {}", lease_id); if let Some(task_id) = self.task_id_map.remove(lease_id) { self.task_id_remove_pending.push(task_id); } @@ -172,7 +172,7 @@ impl ExpirationTask { fn clean_finish_task(&mut self) -> Result<(), RvError> { for task_id in self.task_id_remove_pending.iter() { - log::debug!("clean finish task, task_id: {}", *task_id); + log::debug!("clean finish task, task_id: {}", *task_id); self.task_timer.remove_task(*task_id)?; } self.task_id_remove_pending.clear(); @@ -182,8 +182,8 @@ impl ExpirationTask { impl Drop for ExpirationTask { fn drop(&mut self) { - log::debug!("expiration task timer stopping!"); - let _ = self.task_timer.stop_delay_timer(); + log::debug!("expiration task timer stopping!"); + let _ = self.task_timer.stop_delay_timer(); } } diff --git a/src/modules/auth/token_store.rs b/src/modules/auth/token_store.rs index b2816e3..0263672 100644 --- a/src/modules/auth/token_store.rs +++ b/src/modules/auth/token_store.rs @@ -10,7 +10,7 @@ use serde_json::{json, Value}; use serde::{Serialize, Deserialize}; use humantime::parse_duration; use crate::{ - utils::{generate_uuid, sha1, is_str_subset}, + utils::{generate_uuid, sha1, is_str_subset}, new_path, new_path_internal, new_logical_backend, new_logical_backend_internal, logical::{ diff --git a/src/modules/pki/mod.rs b/src/modules/pki/mod.rs index bb4cc11..fc37f94 100644 --- a/src/modules/pki/mod.rs +++ b/src/modules/pki/mod.rs @@ -98,122 +98,122 @@ impl PkiBackend { { pattern: r"roles/(?P\w[\w-]+\w)", fields: { - "name": { + "name": { field_type: FieldType::Str, required: true, - description: r#"Name of the role."# - }, - "ttl": { + description: r#"Name of the role."# + }, + "ttl": { field_type: FieldType::Str, - description: r#" + description: r#" The lease duration (validity period of the certificate) if no specific lease duration is requested. The lease duration controls the expiration of certificates issued by this backend. defaults to the system default value or the value of max_ttl, whichever is shorter."# - }, - "max_ttl": { + }, + "max_ttl": { field_type: FieldType::Str, required: true, - description: r#" + description: r#" The maximum allowed lease duration. If not set, defaults to the system maximum lease TTL."# - }, - "allow_localhost": { + }, + "allow_localhost": { field_type: FieldType::Bool, - default: true, - description: r#" + default: true, + description: r#" Whether to allow "localhost" and "localdomain" as a valid common name in a request, independent of allowed_domains value."# - }, - "allowed_domains": { - field_type: FieldType::Str, - description: r#" + }, + "allowed_domains": { + field_type: FieldType::Str, + description: r#" Specifies the domains this role is allowed to issue certificates for. This is used with the allow_bare_domains, allow_subdomains, and allow_glob_domains to determine matches for the common name, DNS-typed SAN entries, and Email-typed SAN entries of certificates. See the documentation for more information. This parameter accepts a comma-separated string or list of domains."# - }, - "allow_bare_domains": { - field_type: FieldType::Bool, + }, + "allow_bare_domains": { + field_type: FieldType::Bool, default: false, - description: r#" + description: r#" If set, clients can request certificates for the base domains themselves, e.g. "example.com" of domains listed in allowed_domains. This is a separate option as in some cases this can be considered a security threat. See the documentation for more information."# - }, - "allow_subdomains": { - field_type: FieldType::Bool, + }, + "allow_subdomains": { + field_type: FieldType::Bool, default: false, - description: r#" + description: r#" If set, clients can request certificates for subdomains of domains listed in allowed_domains, including wildcard subdomains. See the documentation for more information."# - }, - "allow_any_name": { - field_type: FieldType::Bool, + }, + "allow_any_name": { + field_type: FieldType::Bool, default: false, - description: r#" + description: r#" If set, clients can request certificates for any domain, regardless of allowed_domains restrictions. See the documentation for more information."# - }, - "allow_ip_sans": { - field_type: FieldType::Bool, - default: true, - description: r#" + }, + "allow_ip_sans": { + field_type: FieldType::Bool, + default: true, + description: r#" If set, IP Subject Alternative Names are allowed. Any valid IP is accepted and No authorization checking is performed."# - }, - "server_flag": { - field_type: FieldType::Bool, - default: true, - description: r#" + }, + "server_flag": { + field_type: FieldType::Bool, + default: true, + description: r#" If set, certificates are flagged for server auth use. defaults to true. See also RFC 5280 Section 4.2.1.12."# - }, - "client_flag": { - field_type: FieldType::Bool, - default: true, - description: r#" + }, + "client_flag": { + field_type: FieldType::Bool, + default: true, + description: r#" If set, certificates are flagged for client auth use. defaults to true. See also RFC 5280 Section 4.2.1.12."# - }, - "code_signing_flag": { - field_type: FieldType::Bool, - description: r#" + }, + "code_signing_flag": { + field_type: FieldType::Bool, + description: r#" If set, certificates are flagged for code signing use. defaults to false. See also RFC 5280 Section 4.2.1.12."# - }, - "key_type": { - field_type: FieldType::Str, - default: "rsa", - description: r#" + }, + "key_type": { + field_type: FieldType::Str, + default: "rsa", + description: r#" The type of key to use; defaults to RSA. "rsa" "ec", "ed25519" and "any" are the only valid values."# - }, - "key_bits": { - field_type: FieldType::Int, - default: 0, - description: r#" + }, + "key_bits": { + field_type: FieldType::Int, + default: 0, + description: r#" The number of bits to use. Allowed values are 0 (universal default); with rsa key_type: 2048 (default), 3072, or 4096; with ec key_type: 224, 256 (default), 384, or 521; ignored with ed25519."# - }, - "signature_bits": { - field_type: FieldType::Int, - default: 0, - description: r#" + }, + "signature_bits": { + field_type: FieldType::Int, + default: 0, + description: r#" The number of bits to use in the signature algorithm; accepts 256 for SHA-2-256, 384 for SHA-2-384, and 512 for SHA-2-512. defaults to 0 to automatically detect based on key length (SHA-2-256 for RSA keys, and matching the curve size for NIST P-Curves)."# - }, - "not_before_duration": { - field_type: FieldType::Int, - default: 30, - description: r#" + }, + "not_before_duration": { + field_type: FieldType::Int, + default: 30, + description: r#" The duration before now which the certificate needs to be backdated by."# - }, - "not_after": { - field_type: FieldType::Str, + }, + "not_after": { + field_type: FieldType::Str, default: "", - description: r#" + description: r#" Set the not after field of the certificate with specified date value. The value format should be given in UTC format YYYY-MM-ddTHH:MM:SSZ."# - }, + }, "ou": { required: false, field_type: FieldType::Str, @@ -282,7 +282,7 @@ or revoked, so this option is recommended only for certificates that are non-sensitive, or extremely short-lived. This option implies a value of "false" for "generate_lease"."# } - }, + }, operations: [ {op: Operation::Read, handler: pki_backend_ref1.read_path_role}, {op: Operation::Write, handler: pki_backend_ref2.create_path_role}, diff --git a/src/modules/pki/path_config_ca.rs b/src/modules/pki/path_config_ca.rs index 38ae06b..bec61bc 100644 --- a/src/modules/pki/path_config_ca.rs +++ b/src/modules/pki/path_config_ca.rs @@ -21,7 +21,7 @@ impl PkiBackendInner { let pem_bundle_value = req.get_data("pem_bundle")?; let pem_bundle = pem_bundle_value.as_str().unwrap(); - let items = pem::parse_many(pem_bundle)?; + let items = pem::parse_many(pem_bundle)?; let mut key_found = false; let mut i = 0; diff --git a/src/modules/pki/path_roles.rs b/src/modules/pki/path_roles.rs index 2be6b5a..7ef491e 100644 --- a/src/modules/pki/path_roles.rs +++ b/src/modules/pki/path_roles.rs @@ -4,7 +4,7 @@ use std::{ use humantime::parse_duration; use serde::{Serialize, Deserialize}; use crate::{ - utils::{serialize_duration, deserialize_duration}, + utils::{serialize_duration, deserialize_duration}, logical::{ Backend, Request, Response, }, diff --git a/src/storage/mod.rs b/src/storage/mod.rs index fa49abb..09a7c45 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -30,18 +30,12 @@ impl Default for StorageEntry { } impl StorageEntry { - pub fn new(k: &str, v: &impl Serialize) -> Result { - /* - let mut buf = Vec::new(); - let mut enc = serde_json::Serializer::new(&mut buf); - - v.serialize(&mut enc)?; - */ + pub fn new(k: &str, v: &impl Serialize) -> Result { let data = serde_json::to_string(v)?; - Ok(StorageEntry { - key: k.to_string(), - value: data.into_bytes(), - }) - } + Ok(StorageEntry { + key: k.to_string(), + value: data.into_bytes(), + }) + } } diff --git a/src/utils/cert.rs b/src/utils/cert.rs index 5bac6fb..ac7b6c2 100644 --- a/src/utils/cert.rs +++ b/src/utils/cert.rs @@ -13,8 +13,8 @@ use openssl::{ ec::{EcGroup, EcKey}, bn::{BigNum, MsbOption}, hash::MessageDigest, - nid::Nid, - asn1::{Asn1OctetString, Asn1Time}, + nid::Nid, + asn1::{Asn1OctetString, Asn1Time}, }; use libc::c_int; use lazy_static::lazy_static; @@ -104,16 +104,16 @@ where } pub fn is_ca_cert(cert: &X509) -> bool { - unsafe { - X509_check_ca(cert.as_ptr()) != 0 - } + unsafe { + X509_check_ca(cert.as_ptr()) != 0 + } } impl Default for CertBundle { fn default() -> Self { CertBundle { certificate: X509_DEFAULT.clone(), - ca_chain: Vec::new(), + ca_chain: Vec::new(), private_key: PKEY_DEFAULT.clone(), private_key_type: String::new(), serial_number: String::new(), @@ -259,12 +259,12 @@ impl Certificate { builder.append_extension(san_ext.build(&builder.x509v3_context(Some(ca_cert), None))?)?; - for ext in &self.extensions { + for ext in &self.extensions { builder.append_extension2(ext)?; } if self.is_ca { - builder.append_extension(BasicConstraints::new().critical().ca().build()?)?; + builder.append_extension(BasicConstraints::new().critical().ca().build()?)?; } builder.append_extension(KeyUsage::new() @@ -335,7 +335,7 @@ impl Certificate { let cert_bundle = CertBundle { certificate: cert, - ca_chain: vec![ca_cert.clone()], + ca_chain: vec![ca_cert.clone()], private_key: priv_key.clone(), private_key_type: self.key_type.clone(), serial_number: serial_number_hex.to_lowercase(), diff --git a/src/utils/key.rs b/src/utils/key.rs index 058b7a5..473feda 100644 --- a/src/utils/key.rs +++ b/src/utils/key.rs @@ -2,7 +2,7 @@ use openssl::{ pkey::{PKey}, rsa::{Rsa, Padding}, ec::{EcGroup, EcKey}, - nid::Nid, + nid::Nid, rand::rand_bytes, hash::MessageDigest, sign::{Signer, Verifier}, @@ -31,8 +31,8 @@ impl Default for KeyBundle { id: generate_uuid(), name: String::new(), key_type: String::new(), - key: Vec::new(), - iv: Vec::new(), + key: Vec::new(), + iv: Vec::new(), bits: 0, } } @@ -110,9 +110,9 @@ impl KeyBundle { return Ok(signer.sign_to_vec()?); }, "ec" => { - let ec_key = EcKey::private_key_from_pem(&self.key)?; + let ec_key = EcKey::private_key_from_pem(&self.key)?; let pkey = PKey::from_ec_key(ec_key)?; - let mut signer = Signer::new(MessageDigest::sha256(), &pkey)?; + let mut signer = Signer::new(MessageDigest::sha256(), &pkey)?; signer.update(data)?; return Ok(signer.sign_to_vec()?); }, @@ -133,7 +133,7 @@ impl KeyBundle { return Ok(verifier.verify(signature).unwrap_or(false)); }, "ec" => { - let ec_key = EcKey::private_key_from_pem(&self.key)?; + let ec_key = EcKey::private_key_from_pem(&self.key)?; let pkey = PKey::from_ec_key(ec_key)?; let mut verifier = Verifier::new(MessageDigest::sha256(), &pkey)?; verifier.update(data)?; From 5ded21315759370c902bab52092ef58cc3825fcb Mon Sep 17 00:00:00 2001 From: Jin Jiu Date: Mon, 27 Nov 2023 17:21:56 +0800 Subject: [PATCH 2/3] Fix the bug causing compilation errors on Windows. 1. Fix the bug causing compilation errors on Windows. 2. Add Windows CI. --- .github/workflows/rust.yml | 27 +++++++++++++++++++++++++-- Cargo.toml | 4 +++- src/cli/command/server.rs | 7 +++---- src/storage/barrier_aes_gcm.rs | 15 ++++++++------- src/storage/physical/mod.rs | 6 ++---- 5 files changed, 41 insertions(+), 18 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 31000a2..a7534ff 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -10,12 +10,35 @@ env: CARGO_TERM_COLOR: always jobs: - build: + unix-test: + strategy: + matrix: + os: + - ubuntu-latest + - macos-latest + runs-on: ${{matrix.os}} - runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Build + run: cargo build --verbose + - name: Run tests + run: cargo test --verbose + windows-test: + strategy: + matrix: + os: + - windows-latest + runs-on: ${{matrix.os}} steps: - uses: actions/checkout@v3 + - run: echo "VCPKG_ROOT=$env:VCPKG_INSTALLATION_ROOT" | Out-File -FilePath $env:GITHUB_ENV -Append + - run: vcpkg install openssl:x64-windows-static-md + - name: Setup Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable - name: Build run: cargo build --verbose - name: Run tests diff --git a/Cargo.toml b/Cargo.toml index ff0e86a..ac37738 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,6 @@ clap = { version = "4.4", features = ["wrap_help", "suggestions"] } sysexits = { version = "0.7", features = ["std"] } build-time = "0.1" hcl-rs = "0.16" -daemonize = "0.5" actix-web = { version = "4.4", features = ["openssl"] } actix-tls = "3.1" actix-rt = "2.9" @@ -40,6 +39,9 @@ as-any = "0.3.1" pem = "3.0" chrono = "0.4" +[target.'cfg(unix)'.dependencies] +daemonize = "0.5" + [dependencies.foreign-types] version = "0.3.1" diff --git a/src/cli/command/server.rs b/src/cli/command/server.rs index 85f45ec..f14f6b3 100644 --- a/src/cli/command/server.rs +++ b/src/cli/command/server.rs @@ -2,11 +2,9 @@ use std::{ env, fs, default::Default, - fs::OpenOptions, path::Path, sync::{Arc, RwLock} }; -use daemonize::Daemonize; use clap::{ArgMatches}; use sysexits::ExitCode; use actix_web::{ @@ -52,6 +50,7 @@ pub fn main(config_path: &str) -> Result<(), RvError> { fs::create_dir_all(work_dir.as_str())?; } + #[cfg(not(windows))] if config.daemon { // start daemon let log_path = format!("{}/rusty_vault.log", work_dir); @@ -70,7 +69,7 @@ pub fn main(config_path: &str) -> Result<(), RvError> { group = config.daemon_group.clone(); } - let log_file = OpenOptions::new() + let log_file = std::fs::OpenOptions::new() .read(true) .write(true) .append(true) @@ -79,7 +78,7 @@ pub fn main(config_path: &str) -> Result<(), RvError> { .open(log_path) .unwrap(); - let daemonize = Daemonize::new() + let daemonize = daemonize::Daemonize::new() .working_directory(work_dir.as_str()) .user(user.as_str()) .group(group.as_str()) diff --git a/src/storage/barrier_aes_gcm.rs b/src/storage/barrier_aes_gcm.rs index f6d8c03..21e26d6 100644 --- a/src/storage/barrier_aes_gcm.rs +++ b/src/storage/barrier_aes_gcm.rs @@ -505,9 +505,12 @@ mod test { assert!(keys.is_ok()); let keys = keys.unwrap(); assert_eq!(keys.len(), 3); - assert_eq!(keys[0], "bar".to_string()); - assert_eq!(keys[1], "barrier/".to_string()); - assert_eq!(keys[2], "bar/".to_string()); + assert!(keys.join("") == "barbarrier/bar/" + || keys.join("") == "barbar/barrier/" + || keys.join("") == "bar/barbarrier/" + || keys.join("") == "barrier/bar/bar" + || keys.join("") == "barrier/barbar/" + || keys.join("") == "bar/barrier/bar"); let get = barrier.get("bar"); assert!(get.is_ok()); assert_eq!(get.unwrap().unwrap().value, "test1".as_bytes()); @@ -517,8 +520,7 @@ mod test { assert!(keys.is_ok()); let keys = keys.unwrap(); assert_eq!(keys.len(), 2); - assert_eq!(keys[0], "foo".to_string()); - assert_eq!(keys[1], "foo/".to_string()); + assert!(keys.join("") == "foofoo/" || keys.join("") == "foo/foo"); let get = barrier.get("bar/foo"); assert!(get.is_ok()); assert_eq!(get.unwrap().unwrap().value, "test2".as_bytes()); @@ -548,8 +550,7 @@ mod test { assert!(keys.is_ok()); let keys = keys.unwrap(); assert_eq!(keys.len(), 2); - assert_eq!(keys[0], "barrier/".to_string()); - assert_eq!(keys[1], "bar/".to_string()); + assert!(keys.join("") == "barrier/bar/" || keys.join("") == "bar/barrier/"); let seal = barrier.seal(); assert!(seal.is_ok()); diff --git a/src/storage/physical/mod.rs b/src/storage/physical/mod.rs index f1fa35b..b39c0e1 100644 --- a/src/storage/physical/mod.rs +++ b/src/storage/physical/mod.rs @@ -151,16 +151,14 @@ mod test { assert!(keys.is_ok()); let keys = keys.unwrap(); assert_eq!(keys.len(), 2); - assert_eq!(keys[0], "bar".to_string()); - assert_eq!(keys[1], "bar/".to_string()); + assert!(keys.join("") == "barbar/" || keys.join("") == "bar/bar"); // Scan bar/ let keys = backend.list("bar/"); assert!(keys.is_ok()); let keys = keys.unwrap(); assert_eq!(keys.len(), 2); - assert_eq!(keys[0], "foo".to_string()); - assert_eq!(keys[1], "foo/".to_string()); + assert!(keys.join("") == "foofoo/" || keys.join("") == "foo/foo"); // Scan bar/foo/ let keys = backend.list("bar/foo/"); From de99c3d89886ec4ec0443c1ae612241ad3585902 Mon Sep 17 00:00:00 2001 From: Jin Jiu Date: Tue, 28 Nov 2023 10:39:09 +0800 Subject: [PATCH 3/3] Update rustfmt.toml --- bin/rusty_vault.rs | 2 +- rustfmt.toml | 27 +- src/cli/command/server.rs | 31 +- src/cli/command/status.rs | 6 +- src/cli/config.rs | 94 ++- src/cli/mod.rs | 35 +- src/context.rs | 14 +- src/core.rs | 80 +-- src/errors.rs | 34 +- src/handler.rs | 8 +- src/http/logical.rs | 66 +-- src/http/mod.rs | 44 +- src/http/sys.rs | 127 ++-- src/lib.rs | 20 +- src/logical/auth.rs | 8 +- src/logical/backend.rs | 30 +- src/logical/field.rs | 16 +- src/logical/lease.rs | 11 +- src/logical/mod.rs | 26 +- src/logical/path.rs | 29 +- src/logical/request.rs | 62 +- src/logical/response.rs | 54 +- src/logical/secret.rs | 23 +- src/module_manager.rs | 19 +- src/modules/auth/expiration.rs | 74 ++- src/modules/auth/mod.rs | 44 +- src/modules/auth/token_store.rs | 114 ++-- src/modules/kv/mod.rs | 38 +- src/modules/mod.rs | 10 +- src/modules/pki/mod.rs | 907 +++++++++++++++++++++++++---- src/modules/pki/path_config_ca.rs | 26 +- src/modules/pki/path_config_crl.rs | 8 +- src/modules/pki/path_fetch.rs | 27 +- src/modules/pki/path_issue.rs | 53 +- src/modules/pki/path_keys.rs | 65 ++- src/modules/pki/path_revoke.rs | 9 +- src/modules/pki/path_roles.rs | 60 +- src/modules/system/mod.rs | 58 +- src/mount.rs | 49 +- src/router.rs | 28 +- src/shamir.rs | 111 ++-- src/storage/barrier.rs | 2 +- src/storage/barrier_aes_gcm.rs | 106 ++-- src/storage/barrier_view.rs | 37 +- src/storage/mod.rs | 15 +- src/storage/physical/file.rs | 36 +- src/storage/physical/mock.rs | 3 +- src/storage/physical/mod.rs | 45 +- src/utils/cert.rs | 82 ++- src/utils/key.rs | 56 +- src/utils/mod.rs | 42 +- tests/test_default_logical.rs | 104 ++-- 52 files changed, 1754 insertions(+), 1321 deletions(-) diff --git a/bin/rusty_vault.rs b/bin/rusty_vault.rs index c83081c..cfe0aaa 100644 --- a/bin/rusty_vault.rs +++ b/bin/rusty_vault.rs @@ -1,6 +1,6 @@ use std::process::ExitCode; -use clap::{Command}; +use clap::Command; use rusty_vault::cli; fn main() -> ExitCode { diff --git a/rustfmt.toml b/rustfmt.toml index 41bd10d..18a78fc 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,18 +1,15 @@ edition = "2021" # We are going to enable these after switching to nightly tool chain -#comment_width = 100 -#binop_separator = "Front" -#format_strings = true -#max_width = 100 -#merge_derives = true -#imports_granularity = "Crate" -#newline_style = "Unix" -#merge_imports = true -#normalize_comments = true -#normalize_doc_attributes = true -#reorder_imports = true -#report_fixme = "Always" -#report_todo = "Always" -#trailing_comma = "Vertical" -#use_field_init_shorthand = true +binop_separator = "Front" +format_strings = true +max_width = 120 +comment_width = 120 +merge_derives = false +reorder_imports = true +use_field_init_shorthand = true +group_imports = "StdExternalCrate" +imports_granularity = "Crate" +newline_style = "Unix" +trailing_comma = "Vertical" +use_small_heuristics = "Max" diff --git a/src/cli/command/server.rs b/src/cli/command/server.rs index f14f6b3..a7774b2 100644 --- a/src/cli/command/server.rs +++ b/src/cli/command/server.rs @@ -1,22 +1,21 @@ use std::{ - env, - fs, default::Default, + env, fs, path::Path, - sync::{Arc, RwLock} + sync::{Arc, RwLock}, }; -use clap::{ArgMatches}; + +use actix_web::{middleware, web, App, HttpResponse, HttpServer}; +use clap::ArgMatches; use sysexits::ExitCode; -use actix_web::{ - middleware, web, App, HttpResponse, HttpServer -}; + use crate::{ - http, - errors::RvError, - EXIT_CODE_OK, EXIT_CODE_INSUFFICIENT_PARAMS, EXIT_CODE_LOAD_CONFIG_FAILURE, cli::config, - storage::{physical, barrier_aes_gcm}, - core::Core + core::Core, + errors::RvError, + http, + storage::{barrier_aes_gcm, physical}, + EXIT_CODE_INSUFFICIENT_PARAMS, EXIT_CODE_LOAD_CONFIG_FAILURE, EXIT_CODE_OK, }; pub const WORK_DIR_PATH_DEFAULT: &str = "/tmp/rusty_vault"; @@ -107,11 +106,7 @@ pub fn main(config_path: &str) -> Result<(), RvError> { let barrier = barrier_aes_gcm::AESGCMBarrier::new(Arc::clone(&backend)); - let core = Arc::new(RwLock::new(Core { - physical: backend, - barrier: Arc::new(barrier), - ..Default::default() - })); + let core = Arc::new(RwLock::new(Core { physical: backend, barrier: Arc::new(barrier), ..Default::default() })); { let mut c = core.write()?; @@ -148,7 +143,7 @@ pub fn execute(matches: &ArgMatches) -> ExitCode { println!("server error: {:?}", e); EXIT_CODE_LOAD_CONFIG_FAILURE } - } + }; } return EXIT_CODE_INSUFFICIENT_PARAMS; diff --git a/src/cli/command/status.rs b/src/cli/command/status.rs index 0cbca9a..bbbfef8 100644 --- a/src/cli/command/status.rs +++ b/src/cli/command/status.rs @@ -1,7 +1,7 @@ -use clap::{ArgMatches}; +use clap::ArgMatches; use sysexits::ExitCode; -use crate::{EXIT_CODE_OK, EXIT_CODE_INSUFFICIENT_PARAMS}; -use crate::errors::RvError; + +use crate::{errors::RvError, EXIT_CODE_INSUFFICIENT_PARAMS, EXIT_CODE_OK}; pub fn main() -> Result<(), RvError> { println!("status: ok"); diff --git a/src/cli/config.rs b/src/cli/config.rs index 86637b1..1e0cd97 100644 --- a/src/cli/config.rs +++ b/src/cli/config.rs @@ -1,13 +1,9 @@ -use std::{ - fs, - path::Path, - collections::HashMap, -}; -use serde::{Serialize, Deserialize, Deserializer}; -use serde_json::{Value}; -use crate::{ - errors::RvError, -}; +use std::{collections::HashMap, fs, path::Path}; + +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +use crate::errors::RvError; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Config { @@ -52,7 +48,7 @@ pub struct Storage { fn parse_bool_string<'de, D>(deserializer: D) -> Result where -D: Deserializer<'de>, + D: Deserializer<'de>, { let value: Value = Deserialize::deserialize(deserializer)?; match value { @@ -68,7 +64,7 @@ D: Deserializer<'de>, fn validate_storage<'de, D>(deserializer: D) -> Result, D::Error> where -D: serde::Deserializer<'de>, + D: serde::Deserializer<'de>, { let storage: HashMap = Deserialize::deserialize(deserializer)?; @@ -83,7 +79,7 @@ D: serde::Deserializer<'de>, fn validate_listener<'de, D>(deserializer: D) -> Result, D::Error> where -D: serde::Deserializer<'de>, + D: serde::Deserializer<'de>, { let listener: HashMap = Deserialize::deserialize(deserializer)?; @@ -191,10 +187,10 @@ fn set_config_type_field(config: &mut Config) -> Result<(), RvError> { #[cfg(test)] mod test { - use std::env; - use std::fs; - use std::io::prelude::*; + use std::{env, fs, io::prelude::*}; + use go_defer::defer; + use super::*; fn write_file(path: &str, config: &str) -> Result<(), RvError> { @@ -212,8 +208,8 @@ mod test { let dir = env::temp_dir().join("rusty_vault_config_test"); assert!(fs::create_dir(&dir).is_ok()); defer! ( - assert!(fs::remove_dir_all(&dir).is_ok()); - ); + assert!(fs::remove_dir_all(&dir).is_ok()); + ); let file_path = dir.join("config.hcl"); let path = file_path.to_str().unwrap_or("config.hcl"); @@ -233,14 +229,14 @@ mod test { pid_file = "/tmp/rusty_vault.pid" "#; - assert!(write_file(path, hcl_config).is_ok()); + assert!(write_file(path, hcl_config).is_ok()); - let config = load_config(path); - assert!(config.is_ok()); - let hcl_config = config.unwrap(); - println!("hcl config: {:?}", hcl_config); + let config = load_config(path); + assert!(config.is_ok()); + let hcl_config = config.unwrap(); + println!("hcl config: {:?}", hcl_config); - let json_config = r#"{ + let json_config = r#"{ "storage": { "file": { "path": "./vault/data" @@ -257,23 +253,23 @@ mod test { "pid_file": "/tmp/rusty_vault.pid" }"#; - let file_path = dir.join("config.json"); - let path = file_path.to_str().unwrap_or("config.json"); - assert!(write_file(path, json_config).is_ok()); + let file_path = dir.join("config.json"); + let path = file_path.to_str().unwrap_or("config.json"); + assert!(write_file(path, json_config).is_ok()); - let config = load_config(path); - assert!(config.is_ok()); - let json_config = config.unwrap(); - println!("json config: {:?}", json_config); + let config = load_config(path); + assert!(config.is_ok()); + let json_config = config.unwrap(); + println!("json config: {:?}", json_config); - let hcl_config_value = serde_json::to_value(&hcl_config); - assert!(hcl_config_value.is_ok()); - let hcl_config_value: Value = hcl_config_value.unwrap(); + let hcl_config_value = serde_json::to_value(&hcl_config); + assert!(hcl_config_value.is_ok()); + let hcl_config_value: Value = hcl_config_value.unwrap(); - let json_config_value = serde_json::to_value(&json_config); - assert!(json_config_value.is_ok()); - let json_config_value: Value = json_config_value.unwrap(); - assert_eq!(hcl_config_value, json_config_value); + let json_config_value = serde_json::to_value(&json_config); + assert!(json_config_value.is_ok()); + let json_config_value: Value = json_config_value.unwrap(); + assert_eq!(hcl_config_value, json_config_value); } #[test] @@ -281,8 +277,8 @@ mod test { let dir = env::temp_dir().join("rusty_vault_config_dir_test"); assert!(fs::create_dir(&dir).is_ok()); defer! ( - assert!(fs::remove_dir_all(&dir).is_ok()); - ); + assert!(fs::remove_dir_all(&dir).is_ok()); + ); let file_path = dir.join("config1.hcl"); let path = file_path.to_str().unwrap_or("config1.hcl"); @@ -303,12 +299,12 @@ mod test { pid_file = "/tmp/rusty_vault.pid" "#; - assert!(write_file(path, hcl_config).is_ok()); + assert!(write_file(path, hcl_config).is_ok()); - let file_path = dir.join("config2.hcl"); - let path = file_path.to_str().unwrap_or("config2.hcl"); + let file_path = dir.join("config2.hcl"); + let path = file_path.to_str().unwrap_or("config2.hcl"); - let hcl_config = r#" + let hcl_config = r#" storage "file" { address = "127.0.0.1:8899" } @@ -321,11 +317,11 @@ mod test { log_level = "info" "#; - assert!(write_file(path, hcl_config).is_ok()); + assert!(write_file(path, hcl_config).is_ok()); - let config = load_config(dir.to_str().unwrap()); - assert!(config.is_ok()); - let hcl_config = config.unwrap(); - println!("hcl config: {:?}", hcl_config); + let config = load_config(dir.to_str().unwrap()); + assert!(config.is_ok()); + let hcl_config = config.unwrap(); + println!("hcl config: {:?}", hcl_config); } } diff --git a/src/cli/mod.rs b/src/cli/mod.rs index b45df82..5f31581 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -1,27 +1,24 @@ +use clap::{Arg, ArgAction, ArgMatches, Command}; use sysexits::ExitCode; -use clap::{Arg, ArgMatches, ArgAction, Command}; pub mod command; pub mod config; /// Defines command line options pub fn define_command_line_options(mut app: Command) -> Command { - app = app - .subcommands([ - Command::new("server") - .about("Start a rusty_vault server") - .arg( - Arg::new("config") - .short('c') - .long("config") - .value_name("CONFIG") - .num_args(1) - .action(ArgAction::Set) - .required(true) - .help("[CONFIG] Path to a configuration file or directory of configuration files.")), - Command::new("status") - .about("Print seal and HA status") - ]); + app = app.subcommands([ + Command::new("server").about("Start a rusty_vault server").arg( + Arg::new("config") + .short('c') + .long("config") + .value_name("CONFIG") + .num_args(1) + .action(ArgAction::Set) + .required(true) + .help("[CONFIG] Path to a configuration file or directory of configuration files."), + ), + Command::new("status").about("Print seal and HA status"), + ]); app } @@ -31,8 +28,6 @@ pub fn run(matches: &ArgMatches) -> ExitCode { match matches.subcommand() { Some(("server", server_matches)) => command::server::execute(&server_matches), Some(("status", status_matches)) => command::status::execute(&status_matches), - _ => { - crate::EXIT_CODE_INSUFFICIENT_PARAMS - } + _ => crate::EXIT_CODE_INSUFFICIENT_PARAMS, } } diff --git a/src/context.rs b/src/context.rs index a984999..45b642b 100644 --- a/src/context.rs +++ b/src/context.rs @@ -1,7 +1,9 @@ -use std::any::Any; -use std::cell::RefCell; -use std::sync::{Arc, Mutex}; -use std::collections::HashMap; +use std::{ + any::Any, + cell::RefCell, + collections::HashMap, + sync::{Arc, Mutex}, +}; pub struct Context { data_map: Mutex>>>, @@ -9,9 +11,7 @@ pub struct Context { impl Context { pub fn new() -> Self { - Self { - data_map: Mutex::new(HashMap::new()), - } + Self { data_map: Mutex::new(HashMap::new()) } } pub fn set(&self, key: &str, data: Arc>) { diff --git a/src/core.rs b/src/core.rs index 5882030..396dc31 100644 --- a/src/core.rs +++ b/src/core.rs @@ -1,36 +1,29 @@ use std::{ - sync::{Arc, Mutex, RwLock}, collections::HashMap, + sync::{Arc, Mutex, RwLock}, }; -use as_any::{Downcast}; -use serde::{Serialize, Deserialize}; + +use as_any::Downcast; use go_defer::defer; +use serde::{Deserialize, Serialize}; + use crate::{ cli::config::Config, - shamir::{ShamirSecret, SHAMIR_OVERHEAD}, + errors::RvError, + handler::Handler, + logical::{Backend, Request, Response}, + module_manager::ModuleManager, + modules::{auth::AuthModule, pki::PkiModule}, mount::MountTable, router::Router, - handler::Handler, - logical::{ - Backend, - Request, - Response, - }, + shamir::{ShamirSecret, SHAMIR_OVERHEAD}, storage::{ - physical, - physical::{ - Backend as PhysicalBackend, - BackendEntry as PhysicalBackendEntry}, barrier::SecurityBarrier, - barrier_view::BarrierView, barrier_aes_gcm, + barrier_view::BarrierView, + physical, + physical::{Backend as PhysicalBackend, BackendEntry as PhysicalBackendEntry}, }, - module_manager::ModuleManager, - modules::{ - auth::AuthModule, - pki::PkiModule, - }, - errors::RvError, }; pub type LogicalBackendNewFunc = dyn Fn(Arc>) -> Result, RvError> + Send + Sync; @@ -95,7 +88,6 @@ impl Default for Core { } } - impl Core { pub fn config(&mut self, core: Arc>, _config: Option) -> Result<(), RvError> { self.module_manager.set_default_modules(Arc::clone(&core))?; @@ -141,17 +133,13 @@ impl Core { // Initialize the barrier barrier.init(master_key.as_slice())?; - let mut init_result = InitResult { - secret_shares: Vec::new(), - root_token: String::new(), - }; + let mut init_result = InitResult { secret_shares: Vec::new(), root_token: String::new() }; if seal_config.secret_shares == 1 { init_result.secret_shares.push(master_key.clone()); } else { - init_result.secret_shares = ShamirSecret::split(&master_key, - seal_config.secret_shares, - seal_config.secret_threshold)?; + init_result.secret_shares = + ShamirSecret::split(&master_key, seal_config.secret_shares, seal_config.secret_threshold)?; } log::debug!("master_key: {}", hex::encode(&master_key)); @@ -390,8 +378,7 @@ impl Core { if err.is_none() { for handler in handlers.iter() { match handler.post_route(req, &mut resp) { - Ok(_) => { - } + Ok(_) => {} Err(error) => { if error != RvError::ErrHandlerDefault { err = Some(error); @@ -405,8 +392,7 @@ impl Core { for handler in handlers.iter() { match handler.log(req, &resp) { - Ok(_) => { - } + Ok(_) => {} Err(error) => { if error != RvError::ErrHandlerDefault { err = Some(error); @@ -426,15 +412,13 @@ impl Core { #[cfg(test)] mod test { - use std::env; - use std::fs; - use std::sync::Arc; - use std::collections::HashMap; - use serde_json::Value; + use std::{collections::HashMap, env, fs, sync::Arc}; + use go_defer::defer; - use crate::storage::physical; - use crate::storage::barrier_aes_gcm; + use serde_json::Value; + use super::*; + use crate::storage::{barrier_aes_gcm, physical}; #[test] fn test_core_init() { @@ -469,10 +453,7 @@ mod test { let mut c = core.write().unwrap(); assert!(c.config(Arc::clone(&core), None).is_ok()); - let seal_config = SealConfig { - secret_shares: 10, - secret_threshold: 5, - }; + let seal_config = SealConfig { secret_shares: 10, secret_threshold: 5 }; let result = c.init(&seal_config); assert!(result.is_ok()); @@ -504,20 +485,13 @@ mod test { let backend = physical::new_backend("file", &conf).unwrap(); let barrier = barrier_aes_gcm::AESGCMBarrier::new(Arc::clone(&backend)); - let core = Arc::new(RwLock::new(Core { - physical: backend, - barrier: Arc::new(barrier), - ..Default::default() - })); + let core = Arc::new(RwLock::new(Core { physical: backend, barrier: Arc::new(barrier), ..Default::default() })); { let mut c = core.write().unwrap(); assert!(c.config(Arc::clone(&core), None).is_ok()); - let seal_config = SealConfig { - secret_shares: 10, - secret_threshold: 5, - }; + let seal_config = SealConfig { secret_shares: 10, secret_threshold: 5 }; let result = c.init(&seal_config); assert!(result.is_ok()); diff --git a/src/errors.rs b/src/errors.rs index b4f8c68..e4e494a 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -1,5 +1,8 @@ -use std::io; -use std::sync::{PoisonError, RwLockReadGuard, RwLockWriteGuard}; +use std::{ + io, + sync::{PoisonError, RwLockReadGuard, RwLockWriteGuard}, +}; + use thiserror::Error; #[derive(Error, Debug)] @@ -141,64 +144,64 @@ pub enum RvError { #[error("Some IO error happened, {:?}", .source)] IO { #[from] - source: io::Error + source: io::Error, }, #[error("Some serde error happened, {:?}", .source)] Serde { #[from] - source: serde_json::Error + source: serde_json::Error, }, #[error("Some openssl error happened, {:?}", .source)] OpenSSL { #[from] - source: openssl::error::ErrorStack + source: openssl::error::ErrorStack, }, #[error("Some pem error happened, {:?}", .source)] Pem { #[from] - source: pem::PemError + source: pem::PemError, }, #[error("Some regex error happened, {:?}", .source)] Regex { #[from] - source: regex::Error + source: regex::Error, }, #[error("Some hex error happened, {:?}", .source)] Hex { #[from] - source: hex::FromHexError + source: hex::FromHexError, }, #[error("Some hcl error happened, {:?}", .source)] Hcl { #[from] - source: hcl::Error + source: hcl::Error, }, #[error("Some humantime error happened, {:?}", .source)] Humantime { #[from] - source: humantime::DurationError + source: humantime::DurationError, }, #[error("Some system_time error happened, {:?}", .source)] SystemTimeError { #[from] - source: std::time::SystemTimeError + source: std::time::SystemTimeError, }, #[error("Some chrono error happened, {:?}", .source)] ChronoError { #[from] - source: chrono::ParseError + source: chrono::ParseError, }, #[error("Some delay_timer error happened, {:?}", .source)] TaskError { #[from] - source: delay_timer::error::TaskError + source: delay_timer::error::TaskError, }, #[error("RwLock was poisoned (reading)")] ErrRwLockReadPoison, #[error("RwLock was poisoned (writing)")] ErrRwLockWritePoison, #[error(transparent)] - ErrOther (#[from] anyhow::Error), + ErrOther(#[from] anyhow::Error), #[error("Unknown error.")] ErrUnknown, } @@ -275,8 +278,7 @@ impl PartialEq for RvError { | (RvError::ErrPkiCertNotFound, RvError::ErrPkiCertNotFound) | (RvError::ErrPkiRoleNotFound, RvError::ErrPkiRoleNotFound) | (RvError::ErrPkiInternal, RvError::ErrPkiInternal) - | (RvError::ErrUnknown, RvError::ErrUnknown) - => true, + | (RvError::ErrUnknown, RvError::ErrUnknown) => true, _ => false, } } diff --git a/src/handler.rs b/src/handler.rs index 1d16b4e..d43d52d 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -1,6 +1,7 @@ -use crate::errors::RvError; -use crate::logical::request::Request; -use crate::logical::response::Response; +use crate::{ + errors::RvError, + logical::{request::Request, response::Response}, +}; pub trait Handler: Send + Sync { fn name(&self) -> String; @@ -21,4 +22,3 @@ pub trait Handler: Send + Sync { Err(RvError::ErrHandlerDefault) } } - diff --git a/src/http/logical.rs b/src/http/logical.rs index 1891df2..c387d9a 100644 --- a/src/http/logical.rs +++ b/src/http/logical.rs @@ -1,34 +1,25 @@ use std::{ - sync::{Arc, RwLock}, collections::HashMap, + sync::{Arc, RwLock}, time::Duration, }; + use actix_web::{ - http::{ - Method, StatusCode - }, - cookie::{ - Cookie, - time::{OffsetDateTime} - }, - web, HttpRequest, HttpResponse + cookie::{time::OffsetDateTime, Cookie}, + http::{Method, StatusCode}, + web, HttpRequest, HttpResponse, }; -use serde::{Serialize, Deserialize}; -use serde_json::{Value}; use humantime::parse_duration; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use super::AUTH_COOKIE_NAME; use crate::{ - core::{Core}, - logical::{Operation, Response}, - http::{ - Connection, - request_auth, - response_error, - response_ok, - response_json_ok, - }, + core::Core, errors::RvError, + http::{request_auth, response_error, response_json_ok, response_ok, Connection}, + logical::{Operation, Response}, }; -use super::AUTH_COOKIE_NAME; #[derive(Debug, Clone, Serialize, Deserialize)] struct Auth { @@ -50,13 +41,7 @@ struct LogicalResponse { impl Default for LogicalResponse { fn default() -> Self { - Self { - renewable: false, - lease_id: String::new(), - lease_duration: 0, - auth: None, - data: HashMap::new(), - } + Self { renewable: false, lease_id: String::new(), lease_duration: 0, auth: None, data: HashMap::new() } } } @@ -65,7 +50,7 @@ async fn logical_request_handler( body: web::Bytes, method: Method, path: web::Path, - core: web::Data>> + core: web::Data>>, ) -> Result { let conn = req.conn_data::().unwrap(); log::debug!("logical request, connection info: {:?}, method: {:?}, path: {:?}", conn, method, path); @@ -76,17 +61,17 @@ async fn logical_request_handler( match method { Method::GET => { r.operation = Operation::Read; - }, + } Method::POST | Method::PUT => { r.operation = Operation::Write; if body.len() > 0 { let payload = serde_json::from_slice(&body)?; r.body = Some(payload); } - }, + } Method::DELETE => { r.operation = Operation::Delete; - }, + } other => { if other.as_str() != "LIST" { return Ok(response_error(StatusCode::METHOD_NOT_ALLOWED, "")); @@ -116,7 +101,7 @@ fn response_logical(resp: &Response, path: &str) -> Result Result Result Result Self { - TlsClientInfo { - client_cert_chain: None, - client_verify_result: X509VerifyResult::OK, - } + TlsClientInfo { client_cert_chain: None, client_verify_result: X509VerifyResult::OK } } } @@ -71,7 +56,7 @@ pub fn request_on_connect_handler(conn: &dyn Any, ext: &mut Extensions) { let socket = tls_stream.get_ref(); let mut cert_chain = None; - if let Some(cert_stack) = tls_stream.ssl().verified_chain() { + if let Some(cert_stack) = tls_stream.ssl().verified_chain() { let certs: Vec = cert_stack.iter().map(X509Ref::to_owned).collect(); cert_chain = Some(certs); } @@ -155,10 +140,7 @@ pub fn response_json_ok(cookie: Option, body: T) -> HttpRe response_json(StatusCode::OK, cookie, body) } -pub fn handle_request( - core: web::Data>>, - req: &mut Request -) -> Result { +pub fn handle_request(core: web::Data>>, req: &mut Request) -> Result { let core = core.read()?; let resp = core.handle_request(req)?; if resp.is_none() { diff --git a/src/http/sys.rs b/src/http/sys.rs index 761c41f..29df8e9 100644 --- a/src/http/sys.rs +++ b/src/http/sys.rs @@ -1,24 +1,21 @@ -use std::{ - sync::{Arc, RwLock} -}; -use actix_web::{ - http::{StatusCode}, - web, HttpRequest, HttpResponse -}; -use serde::{Serialize, Deserialize}; -use serde_json::{json}; +use std::sync::{Arc, RwLock}; + +use actix_web::{http::StatusCode, web, HttpRequest, HttpResponse}; +use serde::{Deserialize, Serialize}; +use serde_json::json; + use crate::{ core::{Core, SealConfig}, - logical::{Operation}, + errors::RvError, http::{ //Connection, handle_request, request_auth, response_error, - response_ok, response_json_ok, + response_ok, }, - errors::RvError, + logical::Operation, }; #[derive(Debug, Clone, Serialize, Deserialize)] @@ -48,7 +45,7 @@ pub struct SealStatusResponse { #[derive(Debug, Clone, Serialize, Deserialize)] struct MountRequest { - #[serde(rename="type")] + #[serde(rename = "type")] logical_type: String, #[serde(default)] description: String, @@ -60,47 +57,44 @@ struct RemountRequest { to: String, } -fn response_seal_status( - core: web::Data>> -) -> Result { +fn response_seal_status(core: web::Data>>) -> Result { let core = core.read()?; let progress = core.unseal_progress(); let sealed = core.sealed(); let seal_config = core.seal_config()?; - let resp = SealStatusResponse { - sealed: sealed, - t: seal_config.secret_shares, - n: seal_config.secret_threshold, - progress: progress, - }; + let resp = SealStatusResponse { sealed, t: seal_config.secret_shares, n: seal_config.secret_threshold, progress }; Ok(response_json_ok(None, resp)) } async fn sys_init_get_request_handler( _req: HttpRequest, - core: web::Data>> + core: web::Data>>, ) -> Result { //let conn = req.conn_data::().unwrap(); let core = core.read()?; let inited = core.inited()?; - Ok(response_ok(None, Some(json!({ - "initialized": inited - }).as_object().unwrap()))) + Ok(response_ok( + None, + Some( + json!({ + "initialized": inited + }) + .as_object() + .unwrap(), + ), + )) } async fn sys_init_put_request_handler( _req: HttpRequest, body: web::Bytes, - core: web::Data>> + core: web::Data>>, ) -> Result { let payload = serde_json::from_slice::(&body)?; - let seal_config = SealConfig { - secret_shares: payload.secret_shares, - secret_threshold: payload.secret_threshold, - }; + let seal_config = SealConfig { secret_shares: payload.secret_shares, secret_threshold: payload.secret_threshold }; let mut core = core.write()?; let result = core.init(&seal_config)?; @@ -115,14 +109,14 @@ async fn sys_init_put_request_handler( async fn sys_seal_status_request_handler( _req: HttpRequest, - core: web::Data>> + core: web::Data>>, ) -> Result { response_seal_status(core) } async fn sys_seal_request_handler( _req: HttpRequest, - core: web::Data>> + core: web::Data>>, ) -> Result { let mut core = core.write()?; core.seal("")?; @@ -132,7 +126,7 @@ async fn sys_seal_request_handler( async fn sys_unseal_request_handler( _req: HttpRequest, body: web::Bytes, - core: web::Data>> + core: web::Data>>, ) -> Result { // TODO let payload = serde_json::from_slice::(&body)?; @@ -148,7 +142,7 @@ async fn sys_unseal_request_handler( async fn sys_list_mounts_request_handler( req: HttpRequest, - core: web::Data>> + core: web::Data>>, ) -> Result { let mut r = request_auth(&req); r.path = "sys/mounts".to_string(); @@ -161,7 +155,7 @@ async fn sys_mount_request_handler( req: HttpRequest, path: web::Path, body: web::Bytes, - core: web::Data>> + core: web::Data>>, ) -> Result { let _test = serde_json::from_slice::(&body)?; let payload = serde_json::from_slice(&body)?; @@ -181,7 +175,7 @@ async fn sys_mount_request_handler( async fn sys_unmount_request_handler( req: HttpRequest, path: web::Path, - core: web::Data>> + core: web::Data>>, ) -> Result { let mount_path = path.into_inner(); if mount_path.len() == 0 { @@ -198,7 +192,7 @@ async fn sys_unmount_request_handler( async fn sys_remount_request_handler( req: HttpRequest, body: web::Bytes, - core: web::Data>> + core: web::Data>>, ) -> Result { let _test = serde_json::from_slice::(&body)?; let payload = serde_json::from_slice(&body)?; @@ -212,7 +206,7 @@ async fn sys_remount_request_handler( async fn sys_list_auth_mounts_request_handler( req: HttpRequest, - core: web::Data>> + core: web::Data>>, ) -> Result { let mut r = request_auth(&req); r.path = "sys/auth".to_string(); @@ -225,7 +219,7 @@ async fn sys_auth_enable_request_handler( req: HttpRequest, path: web::Path, body: web::Bytes, - core: web::Data>> + core: web::Data>>, ) -> Result { let _test = serde_json::from_slice::(&body)?; let payload = serde_json::from_slice(&body)?; @@ -245,7 +239,7 @@ async fn sys_auth_enable_request_handler( async fn sys_auth_disable_request_handler( req: HttpRequest, path: web::Path, - core: web::Data>> + core: web::Data>>, ) -> Result { let mount_path = path.into_inner(); if mount_path.len() == 0 { @@ -262,29 +256,32 @@ async fn sys_auth_disable_request_handler( pub fn init_sys_service(cfg: &mut web::ServiceConfig) { cfg.service( web::scope("/v1/sys") - .service(web::resource("/init") - .route(web::get().to(sys_init_get_request_handler)) - .route(web::put().to(sys_init_put_request_handler))) - .service(web::resource("/seal-status") - .route(web::get().to(sys_seal_status_request_handler))) - .service(web::resource("/seal") - .route(web::put().to(sys_seal_request_handler))) - .service(web::resource("/unseal") - .route(web::put().to(sys_unseal_request_handler))) - .service(web::resource("/mounts") - .route(web::get().to(sys_list_mounts_request_handler))) - .service(web::resource("/mounts/{path:.*}") - .route(web::get().to(sys_list_mounts_request_handler)) - .route(web::post().to(sys_mount_request_handler)) - .route(web::delete().to(sys_unmount_request_handler))) - .service(web::resource("/remount") - .route(web::post().to(sys_remount_request_handler)) - .route(web::put().to(sys_remount_request_handler))) - .service(web::resource("/auth") - .route(web::get().to(sys_list_auth_mounts_request_handler))) - .service(web::resource("/auth/{path:.*}") - .route(web::get().to(sys_list_auth_mounts_request_handler)) - .route(web::post().to(sys_auth_enable_request_handler)) - .route(web::delete().to(sys_auth_disable_request_handler))) + .service( + web::resource("/init") + .route(web::get().to(sys_init_get_request_handler)) + .route(web::put().to(sys_init_put_request_handler)), + ) + .service(web::resource("/seal-status").route(web::get().to(sys_seal_status_request_handler))) + .service(web::resource("/seal").route(web::put().to(sys_seal_request_handler))) + .service(web::resource("/unseal").route(web::put().to(sys_unseal_request_handler))) + .service(web::resource("/mounts").route(web::get().to(sys_list_mounts_request_handler))) + .service( + web::resource("/mounts/{path:.*}") + .route(web::get().to(sys_list_mounts_request_handler)) + .route(web::post().to(sys_mount_request_handler)) + .route(web::delete().to(sys_unmount_request_handler)), + ) + .service( + web::resource("/remount") + .route(web::post().to(sys_remount_request_handler)) + .route(web::put().to(sys_remount_request_handler)), + ) + .service(web::resource("/auth").route(web::get().to(sys_list_auth_mounts_request_handler))) + .service( + web::resource("/auth/{path:.*}") + .route(web::get().to(sys_list_auth_mounts_request_handler)) + .route(web::post().to(sys_auth_enable_request_handler)) + .route(web::delete().to(sys_auth_disable_request_handler)), + ), ); } diff --git a/src/lib.rs b/src/lib.rs index 7b2cf4a..e5d28ed 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,17 +1,17 @@ -pub mod errors; -pub mod storage; -pub mod logical; -pub mod router; -pub mod mount; +pub mod cli; +pub mod context; pub mod core; +pub mod errors; pub mod handler; -pub mod context; -pub mod utils; -pub mod modules; -pub mod module_manager; -pub mod cli; pub mod http; +pub mod logical; +pub mod module_manager; +pub mod modules; +pub mod mount; +pub mod router; pub mod shamir; +pub mod storage; +pub mod utils; /// Exit ok pub const EXIT_CODE_OK: sysexits::ExitCode = sysexits::ExitCode::Ok; diff --git a/src/logical/auth.rs b/src/logical/auth.rs index 9e01f36..87c80be 100644 --- a/src/logical/auth.rs +++ b/src/logical/auth.rs @@ -1,9 +1,11 @@ use std::{ - ops::{Deref, DerefMut}, collections::HashMap, + ops::{Deref, DerefMut}, }; -use serde::{Serialize, Deserialize}; -use super::{lease::Lease}; + +use serde::{Deserialize, Serialize}; + +use super::lease::Lease; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Auth { diff --git a/src/logical/backend.rs b/src/logical/backend.rs index 47e2398..80c7f26 100644 --- a/src/logical/backend.rs +++ b/src/logical/backend.rs @@ -1,13 +1,10 @@ -use std::sync::Arc; +use std::{collections::HashMap, sync::Arc}; + use regex::Regex; -use std::collections::HashMap; -use serde_json::{Value, Map}; +use serde_json::{Map, Value}; + +use super::{path::Path, request::Request, response::Response, secret::Secret, Backend, Operation}; use crate::errors::RvError; -use super::request::Request; -use super::response::Response; -use super::path::Path; -use super::secret::Secret; -use super::{Backend, Operation}; #[derive(Clone)] pub struct LogicalBackend { @@ -174,17 +171,16 @@ macro_rules! new_logical_backend_internal { #[cfg(test)] mod test { - use std::env; - use std::fs; - use std::sync::Arc; - use std::collections::HashMap; - use std::time::Duration; + use std::{collections::HashMap, env, fs, sync::Arc, time::Duration}; + use go_defer::defer; + use super::*; - use crate::{new_path, new_path_internal, new_secret, new_secret_internal}; - use crate::storage::physical; - use crate::storage::barrier_aes_gcm::AESGCMBarrier; - use crate::logical::{Field, FieldType, PathOperation}; + use crate::{ + logical::{Field, FieldType, PathOperation}, + new_path, new_path_internal, new_secret, new_secret_internal, + storage::{barrier_aes_gcm::AESGCMBarrier, physical}, + }; #[test] fn test_logical_backend_match_path() { diff --git a/src/logical/field.rs b/src/logical/field.rs index edb62ab..44504b7 100644 --- a/src/logical/field.rs +++ b/src/logical/field.rs @@ -1,10 +1,10 @@ -use std::fmt; -use std::sync::Arc; -use std::any::Any; -use enum_map::{Enum}; -use strum::{Display, EnumString}; -use serde::{Serialize, Deserialize}; +use std::{any::Any, fmt, sync::Arc}; + +use enum_map::Enum; +use serde::{Deserialize, Serialize}; use serde_json::Value; +use strum::{Display, EnumString}; + use crate::errors::RvError; #[derive(Eq, PartialEq, Copy, Clone, Debug, EnumString, Display, Enum, Serialize, Deserialize)] @@ -69,8 +69,10 @@ impl fmt::Debug for Field { #[cfg(test)] mod test { use std::sync::Arc; + + use serde_json::{json, Number, Value}; + use super::*; - use serde_json::{json, Value, Number}; #[test] fn test_field_get_default() { diff --git a/src/logical/lease.rs b/src/logical/lease.rs index 51b9b65..aa7eebd 100644 --- a/src/logical/lease.rs +++ b/src/logical/lease.rs @@ -1,9 +1,10 @@ -use std::time::{SystemTime, Duration}; -use serde::{Serialize, Deserialize}; +use std::time::{Duration, SystemTime}; + +use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Lease { - #[serde(rename="lease")] + #[serde(rename = "lease")] pub ttl: Duration, pub max_ttl: Duration, pub renewable: bool, @@ -29,9 +30,7 @@ impl Default for Lease { impl Lease { pub fn new() -> Self { - Self { - ..Default::default() - } + Self { ..Default::default() } } pub fn ttl(&self) -> Duration { diff --git a/src/logical/mod.rs b/src/logical/mod.rs index 64bc4d6..58dfb5f 100644 --- a/src/logical/mod.rs +++ b/src/logical/mod.rs @@ -1,26 +1,28 @@ use std::sync::Arc; -use enum_map::{Enum}; + +use enum_map::Enum; +use serde::{Deserialize, Serialize}; use strum::{Display, EnumString}; -use serde::{Serialize, Deserialize}; + use crate::errors::RvError; -pub mod connection; -pub mod request; -pub mod response; +pub mod auth; pub mod backend; -pub mod path; +pub mod connection; pub mod field; pub mod lease; +pub mod path; +pub mod request; +pub mod response; pub mod secret; -pub mod auth; -pub use request::Request; -pub use response::Response; -pub use path::{Path, PathOperation}; -pub use field::{Field, FieldType}; -pub use backend::LogicalBackend; pub use auth::Auth; +pub use backend::LogicalBackend; +pub use field::{Field, FieldType}; pub use lease::Lease; +pub use path::{Path, PathOperation}; +pub use request::Request; +pub use response::Response; pub use secret::{Secret, SecretData}; #[derive(Eq, PartialEq, Copy, Clone, Debug, EnumString, Display, Enum, Serialize, Deserialize)] diff --git a/src/logical/path.rs b/src/logical/path.rs index d645c51..d0cc841 100644 --- a/src/logical/path.rs +++ b/src/logical/path.rs @@ -1,12 +1,7 @@ -use std::fmt; -use std::sync::Arc; -use std::collections::HashMap; +use std::{collections::HashMap, fmt, sync::Arc}; + +use super::{request::Request, response::Response, Backend, Field, Operation}; use crate::errors::RvError; -use super::request::Request; -use super::response::Response; -use super::Field; -use super::Operation; -use super::Backend; type PathOperationHandler = dyn Fn(&dyn Backend, &mut Request) -> Result, RvError> + Send + Sync; @@ -26,20 +21,13 @@ pub struct PathOperation { impl fmt::Debug for PathOperation { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("PathOperation") - .field("op", &self.op) - .finish() + f.debug_struct("PathOperation").field("op", &self.op).finish() } } impl Path { pub fn new(pattern: &str) -> Self { - Self { - pattern: pattern.to_string(), - fields: HashMap::new(), - operations: Vec::new(), - help: String::new(), - } + Self { pattern: pattern.to_string(), fields: HashMap::new(), operations: Vec::new(), help: String::new() } } pub fn get_field(&self, key: &str) -> Option> { @@ -51,7 +39,9 @@ impl PathOperation { pub fn new() -> Self { Self { op: Operation::Read, - handler: Arc::new(|_backend: &dyn Backend, _req: &mut Request| -> Result, RvError> { Ok(None) }), + handler: Arc::new(|_backend: &dyn Backend, _req: &mut Request| -> Result, RvError> { + Ok(None) + }), } } @@ -169,8 +159,7 @@ macro_rules! new_path_internal { #[cfg(test)] mod test { - use super::*; - use super::super::FieldType; + use super::{super::FieldType, *}; pub fn my_test_read_handler(_backend: &dyn Backend, _req: &mut Request) -> Result, RvError> { Ok(None) diff --git a/src/logical/request.rs b/src/logical/request.rs index 79941c6..92cb7db 100644 --- a/src/logical/request.rs +++ b/src/logical/request.rs @@ -1,16 +1,13 @@ -use std::collections::HashMap; -use std::sync::Arc; -use serde_json::{Value, Map}; +use std::{collections::HashMap, sync::Arc}; + +use serde_json::{Map, Value}; + +use super::{Operation, Path}; use crate::{ - logical::{ - connection::Connection, - secret::SecretData, - auth::Auth, - }, - storage::{Storage, StorageEntry}, errors::RvError, + logical::{auth::Auth, connection::Connection, secret::SecretData}, + storage::{Storage, StorageEntry}, }; -use super::{Path, Operation}; pub struct Request { pub id: String, @@ -50,46 +47,19 @@ impl Default for Request { impl Request { pub fn new(path: &str) -> Self { - Self { - path: path.to_string(), - ..Default::default() - } + Self { path: path.to_string(), ..Default::default() } } - pub fn new_revoke_request(path: &str, - secret: Option, - data: Option>) -> Self { - Self { - operation: Operation::Revoke, - path: path.to_string(), - secret: secret, - data: data, - ..Default::default() - } + pub fn new_revoke_request(path: &str, secret: Option, data: Option>) -> Self { + Self { operation: Operation::Revoke, path: path.to_string(), secret, data, ..Default::default() } } - pub fn new_renew_request(path: &str, - secret: Option, - data: Option>) -> Self { - Self { - operation: Operation::Renew, - path: path.to_string(), - secret: secret, - data: data, - ..Default::default() - } + pub fn new_renew_request(path: &str, secret: Option, data: Option>) -> Self { + Self { operation: Operation::Renew, path: path.to_string(), secret, data, ..Default::default() } } - pub fn new_renew_auth_request(path: &str, - auth: Option, - data: Option>) -> Self { - Self { - operation: Operation::Renew, - path: path.to_string(), - auth: auth, - data: data, - ..Default::default() - } + pub fn new_renew_auth_request(path: &str, auth: Option, data: Option>) -> Self { + Self { operation: Operation::Renew, path: path.to_string(), auth, data, ..Default::default() } } pub fn get_data(&self, key: &str) -> Result { @@ -108,13 +78,13 @@ impl Request { if self.data.is_some() { if let Some(data) = self.data.as_ref().unwrap().get(key) { - return Ok(data.clone()) + return Ok(data.clone()); } } if self.body.is_some() { if let Some(data) = self.body.as_ref().unwrap().get(key) { - return Ok(data.clone()) + return Ok(data.clone()); } } diff --git a/src/logical/response.rs b/src/logical/response.rs index 29433f7..d812f6a 100644 --- a/src/logical/response.rs +++ b/src/logical/response.rs @@ -1,5 +1,7 @@ use std::collections::HashMap; -use serde_json::{json, Value, Map}; + +use serde_json::{json, Map, Value}; + use crate::logical::{secret::SecretData, Auth}; #[derive(Debug, Clone)] @@ -8,26 +10,18 @@ pub struct Response { pub data: Option>, pub auth: Option, pub secret: Option, - pub redirect: String + pub redirect: String, } impl Default for Response { fn default() -> Self { - Response { - headers: None, - data: None, - auth: None, - secret: None, - redirect: String::new(), - } + Response { headers: None, data: None, auth: None, secret: None, redirect: String::new() } } } impl Response { pub fn new() -> Self { - Self { - ..Default::default() - } + Self { ..Default::default() } } pub fn data_response(data: Option>) -> Self { @@ -40,9 +34,14 @@ impl Response { let value = serde_json::to_value(keys); let mut resp = Response::new(); if value.is_ok() { - resp.data = Some(json!({ - "keys": value.unwrap(), - }).as_object().unwrap().clone()); + resp.data = Some( + json!({ + "keys": value.unwrap(), + }) + .as_object() + .unwrap() + .clone(), + ); } resp } @@ -51,20 +50,29 @@ impl Response { let value = serde_json::to_value(see_also); let mut resp = Response::new(); if value.is_ok() { - resp.data = Some(json!({ - "help": text.to_string(), - "sea_also": value.unwrap(), - }).as_object().unwrap().clone()); + resp.data = Some( + json!({ + "help": text.to_string(), + "sea_also": value.unwrap(), + }) + .as_object() + .unwrap() + .clone(), + ); } resp } pub fn error_response(text: &str) -> Self { let mut resp = Response::new(); - resp.data = Some(json!({ - "error": text.to_string(), - }).as_object().unwrap().clone()); + resp.data = Some( + json!({ + "error": text.to_string(), + }) + .as_object() + .unwrap() + .clone(), + ); resp } } - diff --git a/src/logical/secret.rs b/src/logical/secret.rs index fe3e5ae..8d7cc69 100644 --- a/src/logical/secret.rs +++ b/src/logical/secret.rs @@ -1,15 +1,16 @@ use std::{ - sync::Arc, ops::{Deref, DerefMut}, - time::{Duration} + sync::Arc, + time::Duration, }; -use serde::{Serialize, Deserialize}; -use serde_json::{Value, Map}; -use super::{Request, Response, Backend, lease::Lease}; -use crate::{errors::RvError}; -type SecretOperationHandler = dyn Fn(&dyn Backend, &mut Request) - -> Result, RvError> + Send + Sync; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +use super::{lease::Lease, Backend, Request, Response}; +use crate::errors::RvError; + +type SecretOperationHandler = dyn Fn(&dyn Backend, &mut Request) -> Result, RvError> + Send + Sync; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SecretData { @@ -49,11 +50,7 @@ impl Secret { lease.ttl = self.default_duration; lease.renewable = self.renewable(); - let mut secret = SecretData { - lease: lease, - lease_id: String::new(), - internal_data: Map::new(), - }; + let mut secret = SecretData { lease, lease_id: String::new(), internal_data: Map::new() }; if internal.is_some() { secret.internal_data = internal.as_ref().unwrap().clone(); diff --git a/src/module_manager.rs b/src/module_manager.rs index 6a136cd..066e922 100644 --- a/src/module_manager.rs +++ b/src/module_manager.rs @@ -1,11 +1,10 @@ -use std::{ - sync::{Arc, RwLock}, +use std::sync::{Arc, RwLock}; + +use crate::{ + core::Core, + errors::RvError, + modules::{kv::KvModule, system::SystemModule, Module}, }; -use crate::core::Core; -use crate::modules::Module; -use crate::modules::kv::KvModule; -use crate::modules::system::SystemModule; -use crate::errors::RvError; pub struct ModuleManager { pub modules: Vec>>>, @@ -13,15 +12,13 @@ pub struct ModuleManager { impl ModuleManager { pub fn new() -> Self { - Self { - modules: Vec::new(), - } + Self { modules: Vec::new() } } pub fn set_default_modules(&mut self, core: Arc>) -> Result<(), RvError> { self.modules = vec![ Arc::new(RwLock::new(Box::new(KvModule::new(Arc::clone(&core))))), - Arc::new(RwLock::new(Box::new(SystemModule::new(core)))) + Arc::new(RwLock::new(Box::new(SystemModule::new(core)))), ]; Ok(()) } diff --git a/src/modules/auth/expiration.rs b/src/modules/auth/expiration.rs index 6b0c3ec..3998902 100644 --- a/src/modules/auth/expiration.rs +++ b/src/modules/auth/expiration.rs @@ -1,24 +1,24 @@ use std::{ - sync::{Arc, RwLock}, - ops::{Deref}, - time::{SystemTime, Duration}, collections::HashMap, + ops::Deref, path::PathBuf, + sync::{Arc, RwLock}, + time::{Duration, SystemTime}, }; -use serde_json::{Value, Map}; -use serde::{Serialize, Deserialize}; + use delay_timer::prelude::*; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +use super::TokenStore; use crate::{ - utils::{generate_uuid, serialize_system_time, deserialize_system_time}, - logical::{ - Auth, SecretData, Request, Response, - }, - storage::{StorageEntry, barrier_view::BarrierView}, core::Core, - router::Router, errors::RvError, + logical::{Auth, Request, Response, SecretData}, + router::Router, + storage::{barrier_view::BarrierView, StorageEntry}, + utils::{deserialize_system_time, generate_uuid, serialize_system_time}, }; -use super::TokenStore; pub const EXPIRATION_SUB_PATH: &str = "expire/"; pub const LEASE_VIEW_PREFIX: &str = "id/"; @@ -26,8 +26,8 @@ pub const TOKEN_VIEW_PREFIX: &str = "token/"; pub const MAX_REVOKE_ATTEMPTS: u32 = 6; pub const REVOKE_RETRY_SECS: Duration = Duration::from_secs(10); pub const MIN_REVOKE_DELAY_SECS: Duration = Duration::from_secs(5); -pub const MAX_LEASE_DURATION_SECS: Duration= Duration::from_secs(30 * 24 * 60 * 60); -pub const DEFAULT_LEASE_DURATION_SECS: Duration= MAX_LEASE_DURATION_SECS; +pub const MAX_LEASE_DURATION_SECS: Duration = Duration::from_secs(30 * 24 * 60 * 60); +pub const DEFAULT_LEASE_DURATION_SECS: Duration = MAX_LEASE_DURATION_SECS; #[derive(Debug, Clone, Serialize, Deserialize)] struct LeaseEntry { @@ -88,9 +88,7 @@ impl Default for ExpirationManagerInner { impl Default for ExpirationManager { fn default() -> Self { - Self { - inner: Arc::new(ExpirationManagerInner::default()), - } + Self { inner: Arc::new(ExpirationManagerInner::default()) } } } @@ -106,15 +104,15 @@ impl LeaseEntry { fn renewable(&self) -> bool { let now = SystemTime::now(); if self.expire_time < now { - return false + return false; } if self.secret.is_some() && !self.secret.as_ref().unwrap().renewable() { - return false + return false; } if self.auth.is_some() && !self.auth.as_ref().unwrap().renewable() { - return false + return false; } true @@ -123,7 +121,10 @@ impl LeaseEntry { impl ExpirationTask { fn add_task U + 'static + Send, U: std::future::Future + 'static + Send>( - &mut self, lease_id: &str, ttl: u64, routine: F + &mut self, + lease_id: &str, + ttl: u64, + routine: F, ) -> Result<(), RvError> { self.clean_finish_task()?; @@ -144,7 +145,10 @@ impl ExpirationTask { } fn update_task U + 'static + Send, U: std::future::Future + 'static + Send>( - &mut self, lease_id: &str, ttl: u64, routine: F + &mut self, + lease_id: &str, + ttl: u64, + routine: F, ) -> Result<(), RvError> { let task_id = self.task_id_map.get(lease_id); log::debug!("update task, lease_id: {}, ttl: {}", lease_id, ttl); @@ -201,9 +205,7 @@ impl ExpirationManager { inner.id_view = Some(Arc::new(id_view)); inner.token_view = Some(Arc::new(token_view)); - let expiration = ExpirationManager { - inner: Arc::new(inner), - }; + let expiration = ExpirationManager { inner: Arc::new(inner) }; Ok(expiration) } @@ -264,9 +266,7 @@ impl ExpirationManager { let ttl = resp.secret.as_ref().unwrap().ttl().as_secs(); resp.secret.as_mut().unwrap().lease_id = lease_id.to_string(); - le.data = resp.data.clone().map(|serde_map| { - serde_map.into_iter().collect() - }); + le.data = resp.data.clone().map(|serde_map| serde_map.into_iter().collect()); le.expire_time = resp.secret.as_ref().unwrap().expiration_time(); le.secret = resp.secret.clone(); @@ -347,12 +347,10 @@ impl ExpirationManager { let lease_id = path.join(generate_uuid()).to_string_lossy().to_string(); let le = LeaseEntry { - lease_id: lease_id, + lease_id, client_token: req.client_token.clone(), path: req.path.clone(), - data: resp.data.clone().map(|serde_map| { - serde_map.into_iter().collect() - }), + data: resp.data.clone().map(|serde_map| serde_map.into_iter().collect()), secret: Some(secret.clone()), auth: None, issue_time: now, @@ -384,7 +382,7 @@ impl ExpirationManager { auth.issue_time = Some(now); let le = LeaseEntry { - lease_id: lease_id, + lease_id, client_token: auth.client_token.clone(), path: source.to_string(), data: None, @@ -483,10 +481,7 @@ impl ExpirationManagerInner { let value = serde_json::to_string(&le)?; - let entry = StorageEntry { - key: le.lease_id.clone(), - value: value.as_bytes().to_vec(), - }; + let entry = StorageEntry { key: le.lease_id.clone(), value: value.as_bytes().to_vec() }; id_view.put(&entry) } @@ -513,10 +508,7 @@ impl ExpirationManagerInner { let key = format!("{}/{}", token_store.salt_id(token), token_store.salt_id(lease_id)); - let entry = StorageEntry { - key: key, - value: lease_id.as_bytes().to_owned(), - }; + let entry = StorageEntry { key, value: lease_id.as_bytes().to_owned() }; token_view.put(&entry) } diff --git a/src/modules/auth/mod.rs b/src/modules/auth/mod.rs index 476fb4d..718c655 100644 --- a/src/modules/auth/mod.rs +++ b/src/modules/auth/mod.rs @@ -1,43 +1,40 @@ use std::{ - sync::{Arc, Mutex, RwLock}, collections::HashMap, + sync::{Arc, Mutex, RwLock}, }; + use lazy_static::lazy_static; + use crate::{ - utils::generate_uuid, + core::{Core, LogicalBackendNewFunc}, + errors::RvError, + handler::Handler, logical::Backend, modules::Module, - core::{Core, LogicalBackendNewFunc}, - mount::{MountTable, MountEntry}, + mount::{MountEntry, MountTable}, router::Router, - storage::{ - barrier::SecurityBarrier, - barrier_view::BarrierView - }, - handler::Handler, - errors::RvError, + storage::{barrier::SecurityBarrier, barrier_view::BarrierView}, + utils::generate_uuid, }; pub mod expiration; pub mod token_store; -pub use token_store::TokenStore; pub use expiration::ExpirationManager; +pub use token_store::TokenStore; const AUTH_CONFIG_PATH: &str = "core/auth"; const AUTH_BARRIER_PREFIX: &str = "auth/"; const AUTH_ROUTER_PREFIX: &str = "auth/"; lazy_static! { - static ref DEFAULT_AUTH_MOUNTS: Vec = vec![ - MountEntry { - tainted: false, - uuid: generate_uuid(), - path: "token/".to_string(), - logical_type: "token".to_string(), - description: "token based credentials".to_string(), - options: None, - } - ]; + static ref DEFAULT_AUTH_MOUNTS: Vec = vec![MountEntry { + tainted: false, + uuid: generate_uuid(), + path: "token/".to_string(), + logical_type: "token".to_string(), + description: "token based credentials".to_string(), + options: None, + }]; } pub struct AuthRouterStore { @@ -47,10 +44,7 @@ pub struct AuthRouterStore { impl AuthRouterStore { pub fn new(mounts: Arc, router: Arc) -> Self { - Self { - mounts, - router, - } + Self { mounts, router } } } diff --git a/src/modules/auth/token_store.rs b/src/modules/auth/token_store.rs index 0263672..295772d 100644 --- a/src/modules/auth/token_store.rs +++ b/src/modules/auth/token_store.rs @@ -1,32 +1,26 @@ -use std::{ - sync::Arc, - ops::Deref, - time::Duration, - collections::HashMap, -}; +use std::{collections::HashMap, ops::Deref, sync::Arc, time::Duration}; + +use humantime::parse_duration; use lazy_static::lazy_static; use regex::Regex; +use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; -use serde::{Serialize, Deserialize}; -use humantime::parse_duration; + +use super::{ + expiration::{ExpirationManager, DEFAULT_LEASE_DURATION_SECS, MAX_LEASE_DURATION_SECS}, + AUTH_ROUTER_PREFIX, +}; use crate::{ - utils::{generate_uuid, sha1, is_str_subset}, - new_path, new_path_internal, - new_logical_backend, new_logical_backend_internal, + core::Core, + errors::RvError, + handler::Handler, logical::{ - Auth, Lease, - Backend, LogicalBackend, Request, Response, - Operation, Path, PathOperation, Field, FieldType, + Auth, Backend, Field, FieldType, Lease, LogicalBackend, Operation, Path, PathOperation, Request, Response, }, - storage::{Storage, StorageEntry}, - core::Core, + new_logical_backend, new_logical_backend_internal, new_path, new_path_internal, router::Router, - handler::Handler, - errors::RvError, -}; -use super::{ - AUTH_ROUTER_PREFIX, - expiration::{ExpirationManager, MAX_LEASE_DURATION_SECS, DEFAULT_LEASE_DURATION_SECS}, + storage::{Storage, StorageEntry}, + utils::{generate_uuid, is_str_subset, sha1}, }; const TOKEN_LOOKUP_PREFIX: &str = "id/"; @@ -84,7 +78,7 @@ pub struct TokenStoreInner { } pub struct TokenStore { - pub inner: Arc + pub inner: Arc, } impl Deref for TokenStore { @@ -123,13 +117,9 @@ impl Default for TokenStoreInner { impl Default for TokenStore { fn default() -> Self { - let inner = TokenStoreInner { - ..TokenStoreInner::default() - }; + let inner = TokenStoreInner { ..TokenStoreInner::default() }; - Self { - inner: Arc::new(inner), - } + Self { inner: Arc::new(inner) } } } @@ -150,10 +140,7 @@ impl TokenStore { if inner.salt.as_str() == "" { inner.salt = generate_uuid(); - let raw = StorageEntry { - key: TOKEN_SALT_LOCATION.to_string(), - value: inner.salt.as_bytes().to_vec(), - }; + let raw = StorageEntry { key: TOKEN_SALT_LOCATION.to_string(), value: inner.salt.as_bytes().to_vec() }; view.as_storage().put(&raw)?; } @@ -161,9 +148,7 @@ impl TokenStore { inner.view = Some(Arc::new(view)); inner.expiration = expiration; - let token_store = TokenStore { - inner: Arc::new(inner), - }; + let token_store = TokenStore { inner: Arc::new(inner) }; Ok(token_store) } @@ -303,21 +288,14 @@ impl TokenStoreInner { return Err(RvError::ErrAuthTokenNotFound); } - let path = format!("{}{}/{}", TOKEN_PARENT_PREFIX, - self.salt_id(&entry.parent), salted_id); - let entry = StorageEntry { - key: path, - ..StorageEntry::default() - }; + let path = format!("{}{}/{}", TOKEN_PARENT_PREFIX, self.salt_id(&entry.parent), salted_id); + let entry = StorageEntry { key: path, ..StorageEntry::default() }; view.put(&entry)?; } let path = format!("{}{}", TOKEN_LOOKUP_PREFIX, salted_id); - let entry = StorageEntry { - key: path, - value: value.as_bytes().to_vec(), - }; + let entry = StorageEntry { key: path, value: value.as_bytes().to_vec() }; view.put(&entry) } @@ -329,13 +307,13 @@ impl TokenStoreInner { let view = self.view.as_ref().unwrap(); - if entry.num_uses == 0{ + if entry.num_uses == 0 { return Ok(()); } entry.num_uses -= 1; - if entry.num_uses == 0{ + if entry.num_uses == 0 { return self.revoke(&entry.id); } @@ -343,10 +321,7 @@ impl TokenStoreInner { let value = serde_json::to_string(&entry)?; let path = format!("{}{}", TOKEN_LOOKUP_PREFIX, salted_id); - let entry = StorageEntry { - key: path, - value: value.as_bytes().to_vec(), - }; + let entry = StorageEntry { key: path, value: value.as_bytes().to_vec() }; view.put(&entry) } @@ -427,8 +402,7 @@ impl TokenStoreInner { if entry.is_some() { let entry = entry.unwrap(); if entry.parent.as_str() != "" { - let path = format!("{}{}/{}", TOKEN_PARENT_PREFIX, - self.salt_id(&entry.parent), salted_id); + let path = format!("{}{}/{}", TOKEN_PARENT_PREFIX, self.salt_id(&entry.parent), salted_id); view.delete(&path)?; } //Revoke all secrets under this token @@ -535,20 +509,13 @@ impl TokenStoreInner { self.create(&mut te)?; let auth = Auth { - lease: Lease { - ttl: Duration::from_secs(te.ttl), - renewable: renewable, - ..Lease::default() - }, + lease: Lease { ttl: Duration::from_secs(te.ttl), renewable, ..Lease::default() }, client_token: te.id.clone(), display_name: te.display_name.clone(), policies: te.policies.clone(), metadata: te.meta.clone(), }; - let resp = Response { - auth: Some(auth), - ..Response::default() - }; + let resp = Response { auth: Some(auth), ..Response::default() }; Ok(Some(resp)) } @@ -581,9 +548,14 @@ impl TokenStoreInner { if let Some(data) = req.data.as_mut() { data.insert("token".to_string(), Value::String(req.client_token.clone())); } else { - req.data = Some(json!({ - "token": req.client_token.clone(), - }).as_object().unwrap().clone()); + req.data = Some( + json!({ + "token": req.client_token.clone(), + }) + .as_object() + .unwrap() + .clone(), + ); } self.handle_lookup(backend, req) @@ -618,7 +590,10 @@ impl TokenStoreInner { "display_name": te.display_name.clone(), "num_uses": te.num_uses, "ttl": te.ttl, - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); Ok(Some(Response::data_response(Some(data)))) } @@ -641,10 +616,7 @@ impl TokenStoreInner { let auth = self.expiration.renew_token(&te.path, &te.id, increment)?; - let resp = Response { - auth: auth, - ..Response::default() - }; + let resp = Response { auth, ..Response::default() }; Ok(Some(resp)) } diff --git a/src/modules/kv/mod.rs b/src/modules/kv/mod.rs index 422a903..a3d27ec 100644 --- a/src/modules/kv/mod.rs +++ b/src/modules/kv/mod.rs @@ -1,24 +1,22 @@ use std::{ + collections::HashMap, ops::Deref, sync::{Arc, RwLock}, - time::{Duration}, - collections::HashMap, + time::Duration, }; -use serde_json::{Value, Map}; + use humantime::parse_duration; +use serde_json::{Map, Value}; + use crate::{ - new_path, new_path_internal, - new_secret, new_secret_internal, - new_logical_backend, new_logical_backend_internal, + core::Core, + errors::RvError, logical::{ - Backend, LogicalBackend, Request, Response, - Operation, Path, PathOperation, Field, FieldType, - secret::Secret, + secret::Secret, Backend, Field, FieldType, LogicalBackend, Operation, Path, PathOperation, Request, Response, }, - storage::{StorageEntry}, modules::Module, - core::Core, - errors::RvError, + new_logical_backend, new_logical_backend_internal, new_path, new_path_internal, new_secret, new_secret_internal, + storage::StorageEntry, }; static KV_BACKEND_HELP: &str = r#" @@ -56,11 +54,7 @@ impl Deref for KvBackend { impl KvBackend { pub fn new(core: Arc>) -> Self { - Self { - inner: Arc::new(KvBackendInner { - core: core, - }) - } + Self { inner: Arc::new(KvBackendInner { core }) } } pub fn new_backend(&self) -> LogicalBackend { @@ -151,10 +145,7 @@ impl KvBackendInner { } let data = serde_json::to_string(req.body.as_ref().unwrap())?; - let entry = StorageEntry { - key: req.path.clone(), - value: data.into_bytes(), - }; + let entry = StorageEntry { key: req.path.clone(), value: data.into_bytes() }; req.storage_put(&entry)?; Ok(None) @@ -178,10 +169,7 @@ impl KvBackendInner { impl KvModule { pub fn new(core: Arc>) -> Self { - Self { - name: "kv".to_string(), - backend: Arc::new(KvBackend::new(core)), - } + Self { name: "kv".to_string(), backend: Arc::new(KvBackend::new(core)) } } } diff --git a/src/modules/mod.rs b/src/modules/mod.rs index 136d933..b19d109 100644 --- a/src/modules/mod.rs +++ b/src/modules/mod.rs @@ -1,11 +1,11 @@ -use as_any::{AsAny}; -use crate::core::Core; -use crate::errors::RvError; +use as_any::AsAny; + +use crate::{core::Core, errors::RvError}; -pub mod kv; -pub mod system; pub mod auth; +pub mod kv; pub mod pki; +pub mod system; pub trait Module: AsAny + Send + Sync { fn name(&self) -> String; diff --git a/src/modules/pki/mod.rs b/src/modules/pki/mod.rs index fc37f94..797caa3 100644 --- a/src/modules/pki/mod.rs +++ b/src/modules/pki/mod.rs @@ -1,30 +1,27 @@ use std::{ - ops::Deref, - sync::{Arc, RwLock, atomic::AtomicU64}, - time::{Duration}, collections::HashMap, + ops::Deref, + sync::{atomic::AtomicU64, Arc, RwLock}, + time::Duration, }; + use crate::{ - new_path, new_path_internal, - new_secret, new_secret_internal, - new_logical_backend, new_logical_backend_internal, + core::Core, + errors::RvError, logical::{ - Backend, LogicalBackend, Request, Response, - Operation, Path, PathOperation, Field, FieldType, - secret::Secret, + secret::Secret, Backend, Field, FieldType, LogicalBackend, Operation, Path, PathOperation, Request, Response, }, modules::Module, - core::Core, - errors::RvError, + new_logical_backend, new_logical_backend_internal, new_path, new_path_internal, new_secret, new_secret_internal, }; -pub mod path_roles; pub mod path_config_ca; pub mod path_config_crl; pub mod path_fetch; pub mod path_issue; -pub mod path_revoke; pub mod path_keys; +pub mod path_revoke; +pub mod path_roles; static PKI_BACKEND_HELP: &str = r#" The PKI backend dynamically generates X509 server and client certificates. @@ -61,10 +58,10 @@ impl PkiBackend { pub fn new(core: Arc>) -> Self { Self { inner: Arc::new(PkiBackendInner { - core: core, + core, cert_count: AtomicU64::new(0), revoked_cert_count: AtomicU64::new(0), - }) + }), } } @@ -115,7 +112,7 @@ max_ttl, whichever is shorter."# field_type: FieldType::Str, required: true, description: r#" -The maximum allowed lease duration. If not set, defaults to the system maximum lease TTL."# + The maximum allowed lease duration. If not set, defaults to the system maximum lease TTL."# }, "allow_localhost": { field_type: FieldType::Bool, @@ -160,30 +157,30 @@ See the documentation for more information."# field_type: FieldType::Bool, default: true, description: r#" -If set, IP Subject Alternative Names are allowed. Any valid IP is accepted and No authorization checking is performed."# + If set, IP Subject Alternative Names are allowed. Any valid IP is accepted and No authorization checking is performed."# }, "server_flag": { field_type: FieldType::Bool, default: true, description: r#" -If set, certificates are flagged for server auth use. defaults to true. See also RFC 5280 Section 4.2.1.12."# + If set, certificates are flagged for server auth use. defaults to true. See also RFC 5280 Section 4.2.1.12."# }, "client_flag": { field_type: FieldType::Bool, default: true, description: r#" -If set, certificates are flagged for client auth use. defaults to true. See also RFC 5280 Section 4.2.1.12."# + If set, certificates are flagged for client auth use. defaults to true. See also RFC 5280 Section 4.2.1.12."# }, "code_signing_flag": { field_type: FieldType::Bool, description: r#" -If set, certificates are flagged for code signing use. defaults to false. See also RFC 5280 Section 4.2.1.12."# + If set, certificates are flagged for code signing use. defaults to false. See also RFC 5280 Section 4.2.1.12."# }, "key_type": { field_type: FieldType::Str, default: "rsa", description: r#" -The type of key to use; defaults to RSA. "rsa" "ec", "ed25519" and "any" are the only valid values."# + The type of key to use; defaults to RSA. "rsa" "ec", "ed25519" and "any" are the only valid values."# }, "key_bits": { field_type: FieldType::Int, @@ -205,7 +202,7 @@ The number of bits to use in the signature algorithm; accepts 256 for SHA-2-256, field_type: FieldType::Int, default: 30, description: r#" -The duration before now which the certificate needs to be backdated by."# + The duration before now which the certificate needs to be backdated by."# }, "not_after": { field_type: FieldType::Str, @@ -218,31 +215,31 @@ The value format should be given in UTC format YYYY-MM-ddTHH:MM:SSZ."# required: false, field_type: FieldType::Str, description: r#" -If set, OU (OrganizationalUnit) will be set to this value in certificates issued by this role."# + If set, OU (OrganizationalUnit) will be set to this value in certificates issued by this role."# }, "organization": { required: false, field_type: FieldType::Str, description: r#" -If set, O (Organization) will be set to this value in certificates issued by this role."# + If set, O (Organization) will be set to this value in certificates issued by this role."# }, "country": { required: false, field_type: FieldType::Str, description: r#" -If set, Country will be set to this value in certificates issued by this role."# + If set, Country will be set to this value in certificates issued by this role."# }, "locality": { required: false, field_type: FieldType::Str, description: r#" -If set, Locality will be set to this value in certificates issued by this role."# + If set, Locality will be set to this value in certificates issued by this role."# }, "province": { required: false, field_type: FieldType::Str, description: r#" -If set, Province will be set to this value in certificates issued by this role."# + If set, Province will be set to this value in certificates issued by this role."# }, "use_csr_common_name": { field_type: FieldType::Bool, @@ -383,13 +380,13 @@ Using "ca" or "crl" as the value fetches the appropriate information in DER enco "common_name": { field_type: FieldType::Str, description: r#" -The requested common name; if you want more than one, specify the alternative names in the alt_names map"# + The requested common name; if you want more than one, specify the alternative names in the alt_names map"# }, "alt_names": { required: false, field_type: FieldType::Str, description: r#" -The requested Subject Alternative Names, if any, in a comma-delimited list"# + The requested Subject Alternative Names, if any, in a comma-delimited list"# }, "ip_sans": { required: false, @@ -639,28 +636,23 @@ impl Module for PkiModule { #[cfg(test)] mod test { - use super::*; use std::{ - env, - fs, - time::{SystemTime, UNIX_EPOCH}, + collections::HashMap, default::Default, + env, fs, sync::{Arc, RwLock}, - collections::HashMap, + time::{SystemTime, UNIX_EPOCH}, }; - use serde_json::{json, Value, Map}; + use go_defer::defer; - use openssl::{ - x509::X509, - pkey::PKey, - rsa::{Rsa}, - ec::{EcKey}, - asn1::Asn1Time, - }; + use openssl::{asn1::Asn1Time, ec::EcKey, pkey::PKey, rsa::Rsa, x509::X509}; + use serde_json::{json, Map, Value}; + + use super::*; use crate::{ - storage::{physical, barrier_aes_gcm}, core::{Core, SealConfig}, logical::{Operation, Request}, + storage::{barrier_aes_gcm, physical}, }; const CA_CERT_PEM: &str = r#" @@ -721,7 +713,13 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L resp } - fn test_write_api(core: &Core, token: &str, path: &str, is_ok: bool, data: Option>) -> Result, RvError> { + fn test_write_api( + core: &Core, + token: &str, + path: &str, + is_ok: bool, + data: Option>, + ) -> Result, RvError> { let mut req = Request::new(path); req.operation = Operation::Write; req.client_token = token.to_string(); @@ -759,7 +757,10 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L // mount pki backend to path: pki/ let mount_data = json!({ "type": "pki", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); let resp = test_write_api(&core, token, "sys/mounts/pki/", true, Some(mount_data)); assert!(resp.is_ok()); @@ -768,7 +769,10 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L let ca_data = json!({ "pem_bundle": ca_pem_bundle, - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); // config ca let resp = test_write_api(&core, token, "pki/config/ca", true, Some(ca_data)); @@ -779,8 +783,14 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L let resp_ca_pem_cert_data = resp_ca_pem.unwrap().unwrap().data.unwrap(); assert!(resp_ca_cert_data.get("private_key").is_none()); assert!(resp_ca_pem_cert_data.get("private_key").is_none()); - assert_eq!(resp_ca_cert_data["certificate"].as_str().unwrap(), resp_ca_pem_cert_data["certificate"].as_str().unwrap()); - assert_eq!(resp_ca_cert_data["serial_number"].as_str().unwrap(), resp_ca_pem_cert_data["serial_number"].as_str().unwrap()); + assert_eq!( + resp_ca_cert_data["certificate"].as_str().unwrap(), + resp_ca_pem_cert_data["certificate"].as_str().unwrap() + ); + assert_eq!( + resp_ca_cert_data["serial_number"].as_str().unwrap(), + resp_ca_pem_cert_data["serial_number"].as_str().unwrap() + ); assert_eq!(resp_ca_cert_data["certificate"].as_str().unwrap().trim(), CA_CERT_PEM.trim()); } @@ -798,7 +808,10 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L "organization": "ANT-Group", "ou": "Big-Security", "no_store": false, - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); // config role assert!(test_write_api(&core, token, "pki/roles/test", true, Some(role_data)).is_ok()); @@ -809,8 +822,8 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L let data = resp.unwrap().data; assert!(data.is_some()); let role_data = data.unwrap(); - assert_eq!(role_data["ttl"].as_u64().unwrap(), 60*24*60*60); - assert_eq!(role_data["max_ttl"].as_u64().unwrap(), 365*24*60*60); + assert_eq!(role_data["ttl"].as_u64().unwrap(), 60 * 24 * 60 * 60); + assert_eq!(role_data["max_ttl"].as_u64().unwrap(), 365 * 24 * 60 * 60); assert_eq!(role_data["key_type"].as_str().unwrap(), "rsa"); assert_eq!(role_data["key_bits"].as_u64().unwrap(), 4096); assert_eq!(role_data["country"].as_str().unwrap(), "CN"); @@ -829,7 +842,10 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L "ttl": "10d", "common_name": "test.com", "alt_names": "a.test.com,b.test.com", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); // issue cert let resp = test_write_api(&core, token, "pki/issue/test", true, Some(issue_data)); @@ -853,7 +869,10 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L assert!(priv_key.public_eq(&cert.public_key().unwrap())); let serial_number = cert.serial_number().to_bn().unwrap(); let serial_number_hex = serial_number.to_hex_str().unwrap(); - assert_eq!(cert_data["serial_number"].as_str().unwrap().replace(":", "").to_lowercase().as_str(), serial_number_hex.to_lowercase().as_str()); + assert_eq!( + cert_data["serial_number"].as_str().unwrap().replace(":", "").to_lowercase().as_str(), + serial_number_hex.to_lowercase().as_str() + ); let expiration_time = Asn1Time::from_unix(cert_data["expiration"].as_i64().unwrap()).unwrap(); let ttl_compare = cert.not_after().compare(&expiration_time); assert!(ttl_compare.is_ok()); @@ -861,31 +880,67 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L let now_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(); let expiration_ttl = cert_data["expiration"].as_u64().unwrap(); let ttl = expiration_ttl - now_timestamp; - let expect_ttl = 10*24*60*60; + let expect_ttl = 10 * 24 * 60 * 60; assert!(ttl <= expect_ttl); assert!((ttl + 10) > expect_ttl); //test fetch cert let serial_number_hex = cert_data["serial_number"].as_str().unwrap(); - let resp_lowercase = test_read_api(&core, token, format!("pki/cert/{}", serial_number_hex.to_lowercase().as_str()).as_str(), true); - let resp_uppercase = test_read_api(&core, token, format!("pki/cert/{}", serial_number_hex.to_uppercase().as_str()).as_str(), true); + let resp_lowercase = test_read_api( + &core, + token, + format!("pki/cert/{}", serial_number_hex.to_lowercase().as_str()).as_str(), + true, + ); + let resp_uppercase = test_read_api( + &core, + token, + format!("pki/cert/{}", serial_number_hex.to_uppercase().as_str()).as_str(), + true, + ); let resp_lowercase_cert_data = resp_lowercase.unwrap().unwrap().data.unwrap(); let resp_uppercase_cert_data = resp_uppercase.unwrap().unwrap().data.unwrap(); assert!(resp_lowercase_cert_data.get("private_key").is_none()); assert!(resp_uppercase_cert_data.get("private_key").is_none()); - assert_eq!(resp_lowercase_cert_data["certificate"].as_str().unwrap(), resp_uppercase_cert_data["certificate"].as_str().unwrap()); - assert_eq!(cert_data["certificate"].as_str().unwrap(), resp_uppercase_cert_data["certificate"].as_str().unwrap()); - assert_eq!(cert_data["serial_number"].as_str().unwrap(), resp_lowercase_cert_data["serial_number"].as_str().unwrap()); + assert_eq!( + resp_lowercase_cert_data["certificate"].as_str().unwrap(), + resp_uppercase_cert_data["certificate"].as_str().unwrap() + ); + assert_eq!( + cert_data["certificate"].as_str().unwrap(), + resp_uppercase_cert_data["certificate"].as_str().unwrap() + ); + assert_eq!( + cert_data["serial_number"].as_str().unwrap(), + resp_lowercase_cert_data["serial_number"].as_str().unwrap() + ); } - fn test_pki_generate_key_case(core: &Core, token: &str, key_name: &str, key_type: &str, key_bits: u32, exported: bool, is_ok: bool) { + fn test_pki_generate_key_case( + core: &Core, + token: &str, + key_name: &str, + key_type: &str, + key_bits: u32, + exported: bool, + is_ok: bool, + ) { let req_data = json!({ "key_name": key_name.to_string(), "key_type": key_type.to_string(), "key_bits": key_bits, - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); println!("generate req_data: {:?}, is_ok: {}", req_data, is_ok); - let resp = test_write_api(core, token, format!("pki/keys/generate/{}", if exported { "exported" } else { "internal" }).as_str(), is_ok, Some(req_data)); + let resp = test_write_api( + core, + token, + format!("pki/keys/generate/{}", if exported { "exported" } else { "internal" }).as_str(), + is_ok, + Some(req_data), + ); if !is_ok { return; } @@ -906,41 +961,51 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L let rsa_key = Rsa::private_key_from_pem(private_key_pem.as_bytes()); assert!(rsa_key.is_ok()); assert_eq!(rsa_key.unwrap().size() * 8, key_bits); - }, + } "ec" => { let ec_key = EcKey::private_key_from_pem(private_key_pem.as_bytes()); assert!(ec_key.is_ok()); assert_eq!(ec_key.unwrap().group().degree(), key_bits); - }, + } "aes-gcm" | "aes-cbc" | "aes-ecb" => { let aes_key = hex::decode(private_key_pem.as_bytes()); assert!(aes_key.is_ok()); assert_eq!(aes_key.unwrap().len() as u32 * 8, key_bits); - }, - _ => { } + _ => {} } } else { assert!(key_data.get("private_key").is_none()); } } - fn test_pki_import_key_case(core: &Core, token: &str, key_name: &str, key_type: &str, key_bits: u32, iv: &str, data: &str, is_ok: bool) { + fn test_pki_import_key_case( + core: &Core, + token: &str, + key_name: &str, + key_type: &str, + key_bits: u32, + iv: &str, + data: &str, + is_ok: bool, + ) { let mut req_data = json!({ "key_name": key_name.to_string(), "key_type": key_type.to_string(), - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); match key_type { "rsa" | "ec" => { req_data.insert("pem_bundle".to_string(), Value::String(data.to_string())); - }, + } "aes-gcm" | "aes-cbc" | "aes-ecb" => { req_data.insert("hex_bundle".to_string(), Value::String(data.to_string())); req_data.insert("iv".to_string(), Value::String(iv.to_string())); - }, - _ => { } + _ => {} } println!("import req_data: {:?}, is_ok: {}", req_data, is_ok); @@ -963,7 +1028,10 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L let req_data = json!({ "key_name": key_name.to_string(), "data": hex::encode(data), - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); println!("sign req_data: {:?}, is_ok: {}", req_data, is_ok); let resp = test_write_api(core, token, "pki/keys/sign", is_ok, Some(req_data)); if !is_ok { @@ -982,7 +1050,10 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L "key_name": key_name.to_string(), "data": hex::encode(data), "signature": signature, - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); println!("verify req_data: {:?}, is_ok: {}", req_data, is_ok); let resp = test_write_api(core, token, "pki/keys/verify", is_ok, Some(req_data)); let resp_body = resp.unwrap(); @@ -998,7 +1069,10 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L "key_name": key_name.to_string(), "data": hex::encode("bad data".as_bytes()), "signature": signature, - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); println!("verify bad req_data: {:?}, is_ok: {}", req_data, is_ok); let resp = test_write_api(core, token, "pki/keys/verify", true, Some(req_data)); let resp_body = resp.unwrap(); @@ -1013,7 +1087,10 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L "key_name": key_name.to_string(), "data": hex::encode(data), "signature": signature[2..], - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); println!("verify bad signatue req_data: {:?}, is_ok: {}", req_data, is_ok); let resp = test_write_api(core, token, "pki/keys/verify", true, Some(req_data)); let resp_body = resp.unwrap(); @@ -1028,7 +1105,10 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L "key_name": key_name.to_string(), "data": hex::encode(data), "signature": signature[1..], - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); assert!(test_write_api(core, token, "pki/keys/verify", false, Some(req_data)).is_err()); } @@ -1037,7 +1117,10 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L let req_data = json!({ "key_name": key_name.to_string(), "data": origin_data.clone(), - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); println!("encrypt req_data: {:?}, is_ok: {}", req_data, is_ok); let resp = test_write_api(core, token, "pki/keys/encrypt", is_ok, Some(req_data)); if !is_ok { @@ -1055,7 +1138,10 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L let req_data = json!({ "key_name": key_name.to_string(), "data": encrypted_data, - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); println!("decrypt req_data: {:?}, is_ok: {}", req_data, is_ok); let resp = test_write_api(core, token, "pki/keys/decrypt", is_ok, Some(req_data)); let resp_body = resp.unwrap(); @@ -1070,7 +1156,10 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L let req_data = json!({ "key_name": key_name.to_string(), "data": encrypted_data[1..], - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); assert!(test_write_api(core, token, "pki/keys/decrypt", false, Some(req_data)).is_err()); } @@ -1169,12 +1258,349 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L fn test_pki_import_key(core: Arc>, token: &str) { let core = core.read().unwrap(); //test import rsa key - test_pki_import_key_case(&core, token, "rsa-2048-import", "rsa", 2048, "", "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC/K85aluWn5Pkl\nHZ5Ye59UkY7S5dLLBSOXpVyECniTpYi08jK0mwP3D+xqgDvS7OBEK2OVO+eUSWCe\ntNHGA/u00HeeADVTNaZK7f2+1KQPkmernOecRU0xbl59ScSOzDDYXMKIhoRs6Neu\nqw+jRTuW0t9/UOmni1pN+w9i5z9Lmz0qMsSaPDoy1JqajZoTyzJz30ftN/kEg75T\nuhwczIzyKPib/IzvsgoPq6ZtVFx9hVEU6SkaKu3jLrxEIpwAROn0fIrcNuOE+VxY\ntpGrBFheD0qbEqOLtMgUYAMWWG86tqWBOBxEnRSEmxhPDLqhu6a4yfBKtwL1JA1e\nPeuiEEKJAgMBAAECggEAFHIZx0bajVrSqf1hc+LWLGQcQNezSY2lUVuDqgbj/3KA\nTPiW+LRC4ne8WBBFQFlKNlrnncyC3Nv+LpXLK7Y9rjMaNUvzaBCrANo0PbvInMu9\nNQr6cGmvCFQ0BzVOWtwMIKUcacqX5if+9/Tenskm8YoLEjbz+RHRLi7lkIqH5/d6\nlIJAss5Q/u3D9uTP0ngmztG65IV0vHacn0S3zyOZ7DD+MJwk4GUpYxTtgkFIzuDH\naQgkYcjJeNNWcOesEHs0u1Nqt9GlPyScde/jcblNPMdkBuu1vP0gxjCNdRVu9ZE5\nx7V9w2buKFwPIS+Hpv35t/0qvcoYDq1Vg1wj6VUVewKBgQDgv0pq1gwkvcZCttEb\nEIitqlQ2y0HH7TdiMB317U2wmLwPmVQ2b1gTD+cHNWE9y1F9rSVeDUfcizm9qvDk\nkjNOAfXRt5aFi2a03DKlGY57k6o9sp3qqvESEoryzUOUTUvYe9S7nXZ7B8/Pv0OE\n2yyEiCg4XtHTRYPLMqbGp359OwKBgQDZwT/ahzYM7RZex9i3BHpuqs6m9ig7W2oM\n7H1Qd4FOOa1lnnq5+/CXDH258OmqANvie/wcD/eQ/tvKIrUfm6DRBvSul2Bbae5F\nGJxLttPFqxCiGgWhPW4EWdFgHXCTmMd3gOByklfw1dMZkjor2kJJSi8kPvfWUKgM\noCyZ7aiTCwKBgFmnFSl/D0MMzOzJ/qocM1mLi6J7/FajYydw6FK1AfvDQam7UWOR\nkQGxo0g12/+Jfo1yp2hYReVNSJBHg2a6h2rDz2qEILBPBn55JF7FzhevtQZ9nQ8C\nd73s1a67gQzEtM+7vgXFb4DugdBujKGPyLdplRm/gVYU8dj58JtoL0YHAoGBAMyi\nQvOGJVE4bNFdVVeIqdXeRp24rk45tgu3InzAEZAFu+HHcOXe0VXhszVOJQhSDlFk\n2qM0jh6AouPuge/WPOaydrasIy1E+1mLqzWr9o/IFrV/ZtMD+6OzFIQSpnzOEoVH\nY6XHyUTWbK+XL3uOfMSLJooVcqrA2WwkCkYNhWHJAoGBANRT1KPQP0+Tlc+8FoGa\nq2Kt71bpNXUzj5Vi/Ikgqm0z943hAvBKIvxY2SPdybvSxk9YeUXhB88cApdepRzc\n4hNAvCtpiAQHbH5P9dpDXx6xbr1kT/z5iKe3VzxnEyLlm6yEItoq1k0ZvpyQO+W4\nbwtnhIcuKu7aG0qI2abuLtNI\n-----END PRIVATE KEY-----\n", true); - test_pki_import_key_case(&core, token, "rsa-3072-import", "rsa", 3072, "", "-----BEGIN PRIVATE KEY-----\nMIIG/QIBADANBgkqhkiG9w0BAQEFAASCBucwggbjAgEAAoIBgQCdvtaUxXZVuDCR\nnmIXvl93uTYrwym95f3vJKaF2dWaJ+3FLPsTTup1pLAKRKdB7s/T5Az/oduymmrn\nBUqLCwMdk04YTiTegby4os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INW9Jb6y8Vx9hiIzDvzUPqX8bWGRAoK4K8Z1Et7aYsZLXYGPliHt\nH81++OW0h8yf/wCAAy4l242bZfdWIwmlz941YeR3Lzifo7JlMy0Sokp2Ir8e6RTX\nDo5o32GEcxbLo+woXez/9og=\n-----END PRIVATE KEY-----\n", true); - test_pki_import_key_case(&core, token, "rsa-4096-import", "rsa", 4096, "", "-----BEGIN PRIVATE KEY-----\nMIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDonanogPRAGLwJ\nBg1EWDgaqJlQLnb7TrvtBzKCLjtw6ssi/1Q1Oldsw6+QEcDOUl5Z+p2SgyT9Ciq+\neXZQ31TxSppmjyQ1E7xsUk33+TBt8Clcw7sXG0MT7CI+q4s356bJ5IF7O5Sz38Lj\nRC2svmE6ptWO+lGtZZTUM4nKs6TWOo/uwfg1OzmwIbFhZsy0l1cF6DO8XKI0L2I8\nMjNCZ6mUh7fYfREuXzX/rnZI8Kc4cQWaGfxHGXkXzmW0WQ3K7EfdXgdP9xAeTmvJ\nsSWlUVsrxo3+IHGjxExrAjB7xLCl778Nff+MVErt+4aveWocrNHOyXgfYHijyjxl\nx0BbjNmPiiBmtaApE950VNzmaoj7B+OrC4SY2yxVjnSOoGo0i08wJIIwYVZQBSwI\nyFECMzQupSQfo7/AeIhtXzKRtVHgI6M08IqRIiirqA0x62HQmFmjny3cWhUSHSaJ\nfcO0YLThCIjbyw8HtfMyHH3whFrX+hOvgEpC5yabwoqs5PseEAJ7vkOrsfo5/61R\nkRrwqonXD68CBwRXWwuGWlxPGRjBt9EMRh7tPTAQD5v5u4ZI1jDsAF24pIPMDAQs\nAhqahX+5zsNgIaY2YIBhMcu90eCqqUc9oHQ3l5jOYoGyfI58Vs3N5TEyGYPCu2Es\nFJKXNoU8NhH77Y+yWSkxCA20MB6lsQIDAQABAoICABoREOktCjHkk62vL+1otWDH\nY+bITiz7NbPqCo7r/1038muJkTYlw4Y8p3/NfX2hXVFX9DBm4c45RXD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Uxk74CYPMmG2w4+Lyr8siTfDvTW5f9Q43vGAGzRF0oGyQNBHv\nVTNPCI2QzRBXneLn+hWcDda3Lgg0IMpPQEXJKOak3kOFnboSwvsN8aP2/LrLBKaV\nV6B7Y5GlEch1VTZMb8tyAeLa1PIFFGoJb7mfiZqIfRqrRbQ9kzVBzyeiHAc06VvJ\nCMWOmQT9pmXTLLmS4KDU+ktQao+U+LXvgYzhzFo9KqkVeNkifppVFZBW5sC/DQbd\nsrlAra2xKovU8At81EhC3oarMYLbY9w=\n-----END PRIVATE KEY-----\n", true); - test_pki_import_key_case(&core, token, "rsa-4096-import", "rsa", 4096, "", "-----BEGIN PRIVATE KEY-----\nMIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDonanogPRAGLwJ\nBg1EWDgaqJlQLnb7TrvtBzKCLjtw6ssi/1Q1Oldsw6+QEcDOUl5Z+p2SgyT9Ciq+\neXZQ31TxSppmjyQ1E7xsUk33+TBt8Clcw7sXG0MT7CI+q4s356bJ5IF7O5Sz38Lj\nRC2svmE6ptWO+lGtZZTUM4nKs6TWOo/uwfg1OzmwIbFhZsy0l1cF6DO8XKI0L2I8\nMjNCZ6mUh7fYfREuXzX/rnZI8Kc4cQWaGfxHGXkXzmW0WQ3K7EfdXgdP9xAeTmvJ\nsSWlUVsrxo3+IHGjxExrAjB7xLCl778Nff+MVErt+4aveWocrNHOyXgfYHijyjxl\nx0BbjNmPiiBmtaApE950VNzmaoj7B+OrC4SY2yxVjnSOoGo0i08wJIIwYVZQBSwI\nyFECMzQupSQfo7/AeIhtXzKRtVHgI6M08IqRIiirqA0x62HQmFmjny3cWhUSHSaJ\nfcO0YLThCIjbyw8HtfMyHH3whFrX+hOvgEpC5yabwoqs5PseEAJ7vkOrsfo5/61R\nkRrwqonXD68CBwRXWwuGWlxPGRjBt9EMRh7tPTAQD5v5u4ZI1jDsAF24pIPMDAQs\nAhqahX+5zsNgIaY2YIBhMcu90eCqqUc9oHQ3l5jOY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/Vnq9MdH5903GAVc6HAEWblppbVZ4NuTX5I6+lQwnTeOcDVVwBuQoZ+0\nqDECggEBAIwdjxe5PVCk4dNZh5tiGta+IEeiF7nTrqFJrlGYQ5HUPUcD8chupAAB\nLdHdzlsJUyCsqAHUxk74CYPMmG2w4+Lyr8siTfDvTW5f9Q43vGAGzRF0oGyQNBHv\nVTNPCI2QzRBXneLn+hWcDda3Lgg0IMpPQEXJKOak3kOFnboSwvsN8aP2/LrLBKaV\nV6B7Y5GlEch1VTZMb8tyAeLa1PIFFGoJb7mfiZqIfRqrRbQ9kzVBzyeiHAc06VvJ\nCMWOmQT9pmXTLLmS4KDU+ktQao+U+LXvgYzhzFo9KqkVeNkifppVFZBW5sC/DQbd\nsrlAra2xKovU8At81EhC3oarMYLbY9w=\n-----END PRIVATE KEY-----\n", false); - test_pki_import_key_case(&core, token, "rsa-4096-import-bad-type", "rsaa", 4096, "", "-----BEGIN PRIVATE KEY-----\nMIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDonanogPRAGLwJ\nBg1EWDgaqJlQLnb7TrvtBzKCLjtw6ssi/1Q1Oldsw6+QEcDOUl5Z+p2SgyT9Ciq+\neXZQ31TxSppmjyQ1E7xsUk33+TBt8Clcw7sXG0MT7CI+q4s356bJ5IF7O5Sz38Lj\nRC2svmE6ptWO+lGtZZTUM4nKs6TWOo/uwfg1OzmwIbFhZsy0l1cF6DO8XKI0L2I8\nMjNCZ6mUh7fYfREuXzX/rnZI8Kc4cQWaGfxHGXkXzmW0WQ3K7EfdXgdP9xAeTmvJ\nsSWlUVsrxo3+IHGjxExrAjB7xLCl778Nff+MVErt+4aveWocrNHOyXgfYHijyjxl\nx0BbjNmPiiBmtaApE950VNzmaoj7B+OrC4SY2yxVjnSOoGo0i08wJIIwYVZQBSwI\nyFECMzQupSQfo7/AeIhtXzKRtVHgI6M08IqRIiirqA0x62HQmFmjny3cWhUSHSaJ\nfcO0YLThCIjbyw8HtfMyHH3whFrX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KFKplaGuGLw1U99sO\nNdxOWWgkN+un2BpYNdo9nTtYZAZz8sN+Y9hlGGZnAoIBAAGqxdBZRYc4nMj9u/M+\nVXGBSXHt4G6wsEQaDjE0uLlxqaR+npJgusXRdHzturn9wNiKdIuaDnAFaiTpxVvG\nXniadwj3T0CckjhcaKTY5QxSCJ6T3YED2BL6IfJmwiKWx+YoMP485/B7QDVslVjT\nbP36pgYl5Cz09S1RZp21F/zryDsf3ZOwhqvwgF6suj36eH059e9uAYkABBQ9BH5Z\nX8d5sLnO3OO7Bt7YnSCJtk0P1LnSe4nFZJIflUqdCxSh7Ada7rT1ldLTwU+/nbIE\nTc1ey5VT/Vnq9MdH5903GAVc6HAEWblppbVZ4NuTX5I6+lQwnTeOcDVVwBuQoZ+0\nqDECggEBAIwdjxe5PVCk4dNZh5tiGta+IEeiF7nTrqFJrlGYQ5HUPUcD8chupAAB\nLdHdzlsJUyCsqAHUxk74CYPMmG2w4+Lyr8siTfDvTW5f9Q43vGAGzRF0oGyQNBHv\nVTNPCI2QzRBXneLn+hWcDda3Lgg0IMpPQEXJKOak3kOFnboSwvsN8aP2/LrLBKaV\nV6B7Y5GlEch1VTZMb8tyAeLa1PIFFGoJb7mfiZqIfRqrRbQ9kzVBzyeiHAc06VvJ\nCMWOmQT9pmXTLLmS4KDU+ktQao+U+LXvgYzhzFo9KqkVeNkifppVFZBW5sC/DQbd\nsrlAra2xKovU8At81EhC3oarMYLbY9w=\n-----END PRIVATE KEY-----\n", false); + test_pki_import_key_case( + &core, + token, + "rsa-2048-import", + "rsa", + 2048, + "", + r#" +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC/K85aluWn5Pkl +HZ5Ye59UkY7S5dLLBSOXpVyECniTpYi08jK0mwP3D+xqgDvS7OBEK2OVO+eUSWCe +tNHGA/u00HeeADVTNaZK7f2+1KQPkmernOecRU0xbl59ScSOzDDYXMKIhoRs6Neu +qw+jRTuW0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yLdplRm/gVYU8dj58JtoL0YHAoGBAMyi +QvOGJVE4bNFdVVeIqdXeRp24rk45tgu3InzAEZAFu+HHcOXe0VXhszVOJQhSDlFk +2qM0jh6AouPuge/WPOaydrasIy1E+1mLqzWr9o/IFrV/ZtMD+6OzFIQSpnzOEoVH +Y6XHyUTWbK+XL3uOfMSLJooVcqrA2WwkCkYNhWHJAoGBANRT1KPQP0+Tlc+8FoGa +q2Kt71bpNXUzj5Vi/Ikgqm0z943hAvBKIvxY2SPdybvSxk9YeUXhB88cApdepRzc +4hNAvCtpiAQHbH5P9dpDXx6xbr1kT/z5iKe3VzxnEyLlm6yEItoq1k0ZvpyQO+W4 +bwtnhIcuKu7aG0qI2abuLtNI +-----END PRIVATE KEY----- +"#, + true, + ); + test_pki_import_key_case( + &core, + token, + "rsa-3072-import", + "rsa", + 3072, + "", + r#" +-----BEGIN PRIVATE KEY----- +MIIG/QIBADANBgkqhkiG9w0BAQEFAASCBucwggbjAgEAAoIBgQCdvtaUxXZVuDCR +nmIXvl93uTYrwym95f3vJKaF2dWaJ+3FLPsTTup1pLAKRKdB7s/T5Az/oduymmrn +BUqLCwMdk04YTiTegby4osyt/A1IC9levly68+8rVmaDQwuiTEja5qBsTIM4JYrX ++7Bi8KNFhzLu1OdH86RsfPWi++i5DlwFlRSmE2O5wnuv6iYWaLq7FV0UAyj5MhVL +MP65ncVo5TVfnaHqZBSWkYa9V9+W5iggddsliAbBr/as7fYUdat/Bv8hpziD0S6+ +BOAPGg4ahXOkNgnIbyKeAWdN462C+RVJoERiDiynnA7NfyDehKUvbCI8oTfUX9mF +QtocU/nCuiew55OJiXPe9E6VZZfmeDtTH2TWDbb4fPL2CjxtS/X74P4wc+EoYP87 +d8/YChBr8juqtAm8h7/2WRYNlEdU6oTRih3+UrDUz+9fdck7z0H0QIMIomrJWF6u +4sRo6F1XTaxSLfGPlZumDZYovjR9Hlar0U6VFI47CM+RJz1la6ECAwEAAQKCAYAO +JWOmnIUhx4Zifqi3DqFO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F +1pMSlpLt/fPPNbWiTr3kj59BN8P9ZCLG5XakVxBNgvrxqVdpZ3dB8Jq3bbg3bSYr +BYToehmvQUMoRUURGhfmLErJb5sDwbWqNa2UCW1oFCbKre8rPg4mcXXsUxcNYWPn +aGahMWl0+XL5Gpy2Y1LmGuzsfAUeHtI/DDre2ll8gWw+5zX4wScczHG3xaR5kYyz ++zN1y9NRgzcQcQKBwBonLYRza9VPGOl2m29jZpt8kiil6wZM4iKf9PcdIrpdeSsC +BUTHBG3A1s1UrRVSlvEBYcNGePjri4QMgeVhzTt0f5jJl5vi1N0vxWxeU8sJIS4f +gKePIOhBMub107C7G0AQMfyq/GFnVuW2toCURybQsm+2GnVJaaeI20vRMFjaZx4z +JmcHVAKVHD5mtP8s1x+11yg8kQ+zLF2f8fLN7w1IpIYBu4nhddwMfD2EPXp4yw6I +3jvlxtdrohxLPrFUoQKBwQCcFE7qT87knR1qX7wzCjSJ1+T7fmeoOuZhCNqhvwdZ +Da/ExWLPqKQ3pAMYwHpJELNUu2kki1RkoQHqkuUpzW96p/Q0IlzlE/ocz6lLSLnf +ib52Wp0DuzsfINW9Jb6y8Vx9hiIzDvzUPqX8bWGRAoK4K8Z1Et7aYsZLXYGPliHt +H81++OW0h8yf/wCAAy4l242bZfdWIwmlz941YeR3Lzifo7JlMy0Sokp2Ir8e6RTX +Do5o32GEcxbLo+woXez/9og= +-----END PRIVATE KEY----- +"#, + true, + ); + test_pki_import_key_case( + &core, + token, + "rsa-4096-import", + "rsa", + 4096, + "", + r#" +-----BEGIN PRIVATE KEY----- +MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDonanogPRAGLwJ +Bg1EWDgaqJlQLnb7TrvtBzKCLjtw6ssi/1Q1Oldsw6+QEcDOUl5Z+p2SgyT9Ciq+ +eXZQ31TxSppmjyQ1E7xsUk33+TBt8Clcw7sXG0MT7CI+q4s356bJ5IF7O5Sz38Lj +RC2svmE6ptWO+lGtZZTUM4nKs6TWOo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IkyF5+P5bAl0c9IiwoVDqd49db4t8uZJaGmGoegJqa +0O2Y79YXO+FPGfcfa6YallgYJ6p0wcb0xftHPbhFD2aJ2rdKFKplaGuGLw1U99sO +NdxOWWgkN+un2BpYNdo9nTtYZAZz8sN+Y9hlGGZnAoIBAAGqxdBZRYc4nMj9u/M+ +VXGBSXHt4G6wsEQaDjE0uLlxqaR+npJgusXRdHzturn9wNiKdIuaDnAFaiTpxVvG +Xniadwj3T0CckjhcaKTY5QxSCJ6T3YED2BL6IfJmwiKWx+YoMP485/B7QDVslVjT +bP36pgYl5Cz09S1RZp21F/zryDsf3ZOwhqvwgF6suj36eH059e9uAYkABBQ9BH5Z +X8d5sLnO3OO7Bt7YnSCJtk0P1LnSe4nFZJIflUqdCxSh7Ada7rT1ldLTwU+/nbIE +Tc1ey5VT/Vnq9MdH5903GAVc6HAEWblppbVZ4NuTX5I6+lQwnTeOcDVVwBuQoZ+0 +qDECggEBAIwdjxe5PVCk4dNZh5tiGta+IEeiF7nTrqFJrlGYQ5HUPUcD8chupAAB +LdHdzlsJUyCsqAHUxk74CYPMmG2w4+Lyr8siTfDvTW5f9Q43vGAGzRF0oGyQNBHv +VTNPCI2QzRBXneLn+hWcDda3Lgg0IMpPQEXJKOak3kOFnboSwvsN8aP2/LrLBKaV +V6B7Y5GlEch1VTZMb8tyAeLa1PIFFGoJb7mfiZqIfRqrRbQ9kzVBzyeiHAc06VvJ +CMWOmQT9pmXTLLmS4KDU+ktQao+U+LXvgYzhzFo9KqkVeNkifppVFZBW5sC/DQbd +srlAra2xKovU8At81EhC3oarMYLbY9w= +-----END PRIVATE KEY----- +"#, + true, + ); + test_pki_import_key_case( + &core, + token, + "rsa-4096-import", + "rsa", + 4096, + "", + r#" +-----BEGIN PRIVATE KEY----- +MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDonanogPRAGLwJ +Bg1EWDgaqJlQLnb7TrvtBzKCLjtw6ssi/1Q1Oldsw6+QEcDOUl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l2ysqM2Do4sGcqzo+vgPanTO8t4/9u +7uWQcA2l8P5VpZwKcIdOLaNVaTncBJGYlCPCRQ904puiprgekS0LlH75MXWjKGd6 +x1j3GzcWTVRcbaTahjeWT7IkyF5+P5bAl0c9IiwoVDqd49db4t8uZJaGmGoegJqa +0O2Y79YXO+FPGfcfa6YallgYJ6p0wcb0xftHPbhFD2aJ2rdKFKplaGuGLw1U99sO +NdxOWWgkN+un2BpYNdo9nTtYZAZz8sN+Y9hlGGZnAoIBAAGqxdBZRYc4nMj9u/M+ +VXGBSXHt4G6wsEQaDjE0uLlxqaR+npJgusXRdHzturn9wNiKdIuaDnAFaiTpxVvG +Xniadwj3T0CckjhcaKTY5QxSCJ6T3YED2BL6IfJmwiKWx+YoMP485/B7QDVslVjT +bP36pgYl5Cz09S1RZp21F/zryDsf3ZOwhqvwgF6suj36eH059e9uAYkABBQ9BH5Z +X8d5sLnO3OO7Bt7YnSCJtk0P1LnSe4nFZJIflUqdCxSh7Ada7rT1ldLTwU+/nbIE +Tc1ey5VT/Vnq9MdH5903GAVc6HAEWblppbVZ4NuTX5I6+lQwnTeOcDVVwBuQoZ+0 +qDECggEBAIwdjxe5PVCk4dNZh5tiGta+IEeiF7nTrqFJrlGYQ5HUPUcD8chupAAB +LdHdzlsJUyCsqAHUxk74CYPMmG2w4+Lyr8siTfDvTW5f9Q43vGAGzRF0oGyQNBHv +VTNPCI2QzRBXneLn+hWcDda3Lgg0IMpPQEXJKOak3kOFnboSwvsN8aP2/LrLBKaV +V6B7Y5GlEch1VTZMb8tyAeLa1PIFFGoJb7mfiZqIfRqrRbQ9kzVBzyeiHAc06VvJ +CMWOmQT9pmXTLLmS4KDU+ktQao+U+LXvgYzhzFo9KqkVeNkifppVFZBW5sC/DQbd +srlAra2xKovU8At81EhC3oarMYLbY9w= +-----END PRIVATE KEY----- +"#, + false, + ); + test_pki_import_key_case( + &core, + token, + "rsa-4096-import-bad-type", + "rsaa", + 4096, + "", + r#" +-----BEGIN PRIVAT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lAra2xKovU8At81EhC3oarMYLbY9w= +-----END PRIVATE KEY----- +"#, + false, + ); + test_pki_import_key_case( + &core, + token, + "rsa-4096-import-bad-pem", + "rsaa", + 4096, + "", + r#" +-----BEGIN PRIVATE KEY----- +AAAAAAAAAAAAAAAAAAAAAAAkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk +MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDonanogPRAGLwJ +Bg1EWDgaqJlQLnb7TrvtBzKCLjtw6ssi/1Q1Oldsw6+QEcDOUl5Z+p2SgyT9Ciq+ +eXZQ31TxSppmjyQ1E7xsUk33+TBt8Clcw7sXG0MT7CI+q4s356bJ5IF7O5Sz38Lj +RC2svmE6ptWO+lGtZZTUM4nKs6TWOo/uwfg1OzmwIbFhZsy0l1cF6DO8XKI0L2I8 +MjNCZ6mUh7fYfREuXzX/rnZI8Kc4cQWaGfxHGXkXzmW0WQ3K7EfdXgdP9xAeTmvJ +sSWlUVsrxo3+IHGjxExrAjB7xLCl778Nff+MVErt+4aveWocrNHOyXgfYHijyjxl +x0BbjNmPiiBmtaApE950VNzmaoj7B+OrC4SY2yxVjnSOoGo0i08wJIIwYVZQBSwI +yFECMzQupSQfo7/AeIhtXzKRtVHgI6M08IqRIiirqA0x62HQmFmjny3cWhUSHSaJ +fcO0YLThCIjbyw8HtfMyHH3whFrX+hOvgEpC5yabwoqs5PseEAJ7vkOrsfo5/61R +kRrwqonXD68CBwRXWwuGWlxPGRjBt9EMRh7tPTAQD5v5u4ZI1jDsAF24pIPMDAQs +AhqahX+5zsNgIaY2YIBhMcu90eCqqUc9oHQ3l5jOYoGyfI58Vs3N5TEyGYPCu2Es +FJKXNoU8NhH77Y+yWSkxCA20MB6lsQIDAQABAoICABoREOktCjHkk62vL+1otWDH +Y+bITiz7NbPqCo7r/1038muJkTYlw4Y8p3/NfX2hXVFX9DBm4c45RXDyy39kh3BC +m+rCP5xzCbpZvsL6+aJYN0pd5KlCNNI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+hWcDda3Lgg0IMpPQEXJKOak3kOFnboSwvsN8aP2/LrLBKaV +V6B7Y5GlEch1VTZMb8tyAeLa1PIFFGoJb7mfiZqIfRqrRbQ9kzVBzyeiHAc06VvJ +CMWOmQT9pmXTLLmS4KDU+ktQao+U+LXvgYzhzFo9KqkVeNkifppVFZBW5sC/DQbd +srlAra2xKovU8At81EhC3oarMYLbY9w= +-----END PRIVATE KEY----- +"#, + false, + ); //test rsa sign and verify test_pki_sign_verify(&core, token, "rsa-2048-import", "rusty_vault test".as_bytes(), true); @@ -1182,13 +1608,114 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L test_pki_sign_verify(&core, token, "rsa-4096-import", "rusty_vault test".as_bytes(), true); //test import ec key - test_pki_import_key_case(&core, token, "ec-224-import", "ec", 224, "", "-----BEGIN PRIVATE KEY-----\nMHgCAQAwEAYHKoZIzj0CAQYFK4EEACEEYTBfAgEBBBzsiBoYW2wy95WsH51cIW90\nl5jP3LyA//F/qHE5oTwDOgAEasjtLNpFz6+08WsxkDppMANKXPfaiIzvSfLMFIZU\nK9bNL/xrK2WENeATjX1eZE9JZtjDwnAqlJM=\n-----END PRIVATE KEY-----\n", true); - test_pki_import_key_case(&core, token, "ec-256-import", "ec", 256, "", "-----BEGIN PRIVATE KEY-----\nMIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgfSJ3DnUokwFD0QtnEE1f\ne0Y20qDAjcYbwFwkWBkWcy+hRANCAATKrAXdOc0ufhMk8225jX+C9a/WfjNIp7lu\nAAOYNTNA2jpy34lQ2zlBLIoaTuxXtg6mWvfITYPGrpWorcPTYzG+\n-----END PRIVATE KEY-----\n", true); - test_pki_import_key_case(&core, token, "ec-384-import", "ec", 384, "", "-----BEGIN PRIVATE KEY-----\nMIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDDY0x5JtPPUfipvnd7P\nC6vZfNzkyBRCiwzGbFY1MH39ZC4TfNx0t5SiADPDNv4g1y6hZANiAASMgIt8fVVY\nTKSYqB3QPPoSWhfvlq1iSdarRYfH+6S9dRpeaf+xnnVVMD8iqmUBOdl0UZZHOOt6\n+JJpUl0cZF9t6E92N4SaXaFI3ZLzYziaMZU1MSTWJZyJvi3vswqHEYU=\n-----END PRIVATE KEY-----\n", true); - test_pki_import_key_case(&core, token, "ec-521-import", "ec", 521, "", "-----BEGIN PRIVATE KEY-----\nMIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIA/PzzOHksK0r/Z/82\n43IOFCYFjhOL08+cFGElJjHfubjTGhzr1jDHwwnMnd7LAOk+M9395uJjwXMrW5GN\nqWeY8cWhgYkDgYYABAG44vWoqZdKP+nGTDNcmK2phS9/TWfHrCqxJAckyINLYwuE\nUdkF6MbAwJJOPnBntqZOt83iUtFKUWxy0iFPQVn49QHP/yT+G/cz3qjx7TkFP+4W\njmQbXbxLGIvSIZoscho/LSWyyct4CBPbPplopiMTgDN1MA7mFvT2TYAxFJA0rVWk\nFw==\n-----END PRIVATE KEY-----\n", true); + test_pki_import_key_case( + &core, + token, + "ec-224-import", + "ec", + 224, + "", + r#" +-----BEGIN PRIVATE KEY----- +MHgCAQAwEAYHKoZIzj0CAQYFK4EEACEEYTBfAgEBBBzsiBoYW2wy95WsH51cIW90 +l5jP3LyA//F/qHE5oTwDOgAEasjtLNpFz6+08WsxkDppMANKXPfaiIzvSfLMFIZU +K9bNL/xrK2WENeATjX1eZE9JZtjDwnAqlJM= +-----END PRIVATE KEY----- + "#, + true, + ); + test_pki_import_key_case( + &core, + token, + "ec-256-import", + "ec", + 256, + "", + r#" +-----BEGIN PRIVATE KEY----- +MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgfSJ3DnUokwFD0QtnEE1f +e0Y20qDAjcYbwFwkWBkWcy+hRANCAATKrAXdOc0ufhMk8225jX+C9a/WfjNIp7lu +AAOYNTNA2jpy34lQ2zlBLIoaTuxXtg6mWvfITYPGrpWorcPTYzG+ +-----END PRIVATE KEY----- +"#, + true, + ); + test_pki_import_key_case( + &core, + token, + "ec-384-import", + "ec", + 384, + "", + r#" +-----BEGIN PRIVATE KEY----- +MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDDY0x5JtPPUfipvnd7P +C6vZfNzkyBRCiwzGbFY1MH39ZC4TfNx0t5SiADPDNv4g1y6hZANiAASMgIt8fVVY +TKSYqB3QPPoSWhfvlq1iSdarRYfH+6S9dRpeaf+xnnVVMD8iqmUBOdl0UZZHOOt6 ++JJpUl0cZF9t6E92N4SaXaFI3ZLzYziaMZU1MSTWJZyJvi3vswqHEYU= +-----END PRIVATE KEY----- +"#, + true, + ); + test_pki_import_key_case( + &core, + token, + "ec-521-import", + "ec", + 521, + "", + r#" +-----BEGIN PRIVATE KEY----- +MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIA/PzzOHksK0r/Z/82 +43IOFCYFjhOL08+cFGElJjHfubjTGhzr1jDHwwnMnd7LAOk+M9395uJjwXMrW5GN +qWeY8cWhgYkDgYYABAG44vWoqZdKP+nGTDNcmK2phS9/TWfHrCqxJAckyINLYwuE +UdkF6MbAwJJOPnBntqZOt83iUtFKUWxy0iFPQVn49QHP/yT+G/cz3qjx7TkFP+4W +jmQbXbxLGIvSIZoscho/LSWyyct4CBPbPplopiMTgDN1MA7mFvT2TYAxFJA0rVWk +Fw== +-----END PRIVATE KEY----- +"#, + true, + ); test_pki_import_key_case(&core, token, "ec-521-import", "ec", 521, "", "same key name", false); - test_pki_import_key_case(&core, token, "ec-521-import-bad-type", "ecc", 521, "", "-----BEGIN PRIVATE KEY-----\nMIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIA/PzzOHksK0r/Z/82\n43IOFCYFjhOL08+cFGElJjHfubjTGhzr1jDHwwnMnd7LAOk+M9395uJjwXMrW5GN\nqWeY8cWhgYkDgYYABAG44vWoqZdKP+nGTDNcmK2phS9/TWfHrCqxJAckyINLYwuE\nUdkF6MbAwJJOPnBntqZOt83iUtFKUWxy0iFPQVn49QHP/yT+G/cz3qjx7TkFP+4W\njmQbXbxLGIvSIZoscho/LSWyyct4CBPbPplopiMTgDN1MA7mFvT2TYAxFJA0rVWk\nFw==\n-----END PRIVATE KEY-----\n", false); - test_pki_import_key_case(&core, token, "ec-521-import-bad-pem", "ec", 521, "", "-----BEGIN PRIVATE KEY-----\nMIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIA/PzzOHksK0r/Z/82\n43IOFCYFjhOL08+cFGElJjHfubjTGhzr1jDHwwnMnd7LAOk+M9395uJjwXMrW5GN\nqWeY8cWhgYkDgYYABAG44vWoqZdKP+nGTDNcmK2phS9/TWfHrCqxJAckyINLYwuE\nUdkF6MbAwJJOPnBntqZOt83iUtFKUWxy0iFPQVn49QHP/yT+G/cz3qjx7TkFP+4W\njmQbXbxLGIvSIZoscho/LSWyyct4CBPbPplopiMTgDN1MA7mFvT2TYAxFJA0rVWkaabb\nFw==\nxxxxxxxxxxxxxx\n-----END PRIVATE KEY-----\n", false); + test_pki_import_key_case( + &core, + token, + "ec-521-import-bad-type", + "ecc", + 521, + "", + r#" +-----BEGIN PRIVATE KEY----- +MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIA/PzzOHksK0r/Z/82 +43IOFCYFjhOL08+cFGElJjHfubjTGhzr1jDHwwnMnd7LAOk+M9395uJjwXMrW5GN +qWeY8cWhgYkDgYYABAG44vWoqZdKP+nGTDNcmK2phS9/TWfHrCqxJAckyINLYwuE +UdkF6MbAwJJOPnBntqZOt83iUtFKUWxy0iFPQVn49QHP/yT+G/cz3qjx7TkFP+4W +jmQbXbxLGIvSIZoscho/LSWyyct4CBPbPplopiMTgDN1MA7mFvT2TYAxFJA0rVWk +Fw== +-----END PRIVATE KEY----- +"#, + false, + ); + test_pki_import_key_case( + &core, + token, + "ec-521-import-bad-pem", + "ec", + 521, + "", + r#" +-----BEGIN PRIVATE KEY----- +MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIA/PzzOHksK0r/Z/82 +43IOFCYFjhOL08+cFGElJjHfubjTGhzr1jDHwwnMnd7LAOk+M9395uJjwXMrW5GN +qWeY8cWhgYkDgYYABAG44vWoqZdKP+nGTDNcmK2phS9/TWfHrCqxJAckyINLYwuE +UdkF6MbAwJJOPnBntqZOt83iUtFKUWxy0iFPQVn49QHP/yT+G/cz3qjx7TkFP+4W +jmQbXbxLGIvSIZoscho/LSWyyct4CBPbPplopiMTgDN1MA7mFvT2TYAxFJA0rVWkaabb +Fw== +xxxxxxxxxxxxxx +-----END PRIVATE KEY----- + "#, + false, + ); //test ec sign and verify test_pki_sign_verify(&core, token, "ec-224-import", "rusty_vault test".as_bytes(), true); @@ -1197,12 +1724,66 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L test_pki_sign_verify(&core, token, "ec-521-import", "rusty_vault test".as_bytes(), true); //test import aes-gcm key - test_pki_import_key_case(&core, token, "aes-gcm-128-import", "aes-gcm", 128, "1c499088cddd0382918bd5650718533d", "cfe0f571fe695c6a4c5e34339d32eb3c", true); - test_pki_import_key_case(&core, token, "aes-gcm-192-import", "aes-gcm", 192, "1c499088cddd0382918bd5650718533d", "3077fdca16350c85c354a700bbc127972dafe2138874cdea", true); - test_pki_import_key_case(&core, token, "aes-gcm-256-import", "aes-gcm", 256, "1c499088cddd0382918bd5650718533d", "6349e3032b690f2fe61a824746ac3ab05c1829a4147f4891f595dfb19cddfd06", true); - test_pki_import_key_case(&core, token, "aes-gcm-256-import", "aes-gcm", 256, "1c499088cddd0382918bd5650718533d", "same key name", false); - test_pki_import_key_case(&core, token, "aes-gcm-256-import-bad-type", "aes-gcmm", 256, "1c499088cddd0382918bd5650718533d", "6349e3032b690f2fe61a824746ac3ab05c1829a4147f4891f595dfb19cddfd06", false); - test_pki_import_key_case(&core, token, "aes-gcm-256-import-bad-hex", "aes-gcm", 256, "1c499088cddd0382918bd5650718533d", "aa6349e3032b690f2fe61a824746ac3ab05c1829a4147f4891f595dfb19cddfd06", false); + test_pki_import_key_case( + &core, + token, + "aes-gcm-128-import", + "aes-gcm", + 128, + "1c499088cddd0382918bd5650718533d", + "cfe0f571fe695c6a4c5e34339d32eb3c", + true, + ); + test_pki_import_key_case( + &core, + token, + "aes-gcm-192-import", + "aes-gcm", + 192, + "1c499088cddd0382918bd5650718533d", + "3077fdca16350c85c354a700bbc127972dafe2138874cdea", + true, + ); + test_pki_import_key_case( + &core, + token, + "aes-gcm-256-import", + "aes-gcm", + 256, + "1c499088cddd0382918bd5650718533d", + "6349e3032b690f2fe61a824746ac3ab05c1829a4147f4891f595dfb19cddfd06", + true, + ); + test_pki_import_key_case( + &core, + token, + "aes-gcm-256-import", + "aes-gcm", + 256, + "1c499088cddd0382918bd5650718533d", + "same key name", + false, + ); + test_pki_import_key_case( + &core, + token, + "aes-gcm-256-import-bad-type", + "aes-gcmm", + 256, + "1c499088cddd0382918bd5650718533d", + "6349e3032b690f2fe61a824746ac3ab05c1829a4147f4891f595dfb19cddfd06", + false, + ); + test_pki_import_key_case( + &core, + token, + "aes-gcm-256-import-bad-hex", + "aes-gcm", + 256, + "1c499088cddd0382918bd5650718533d", + "aa6349e3032b690f2fe61a824746ac3ab05c1829a4147f4891f595dfb19cddfd06", + false, + ); //test aes-gcm encrypt and decrypt test_pki_encrypt_decrypt(&core, token, "aes-gcm-128-import", "rusty_vault test".as_bytes(), true); @@ -1210,12 +1791,66 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L test_pki_encrypt_decrypt(&core, token, "aes-gcm-256-import", "rusty_vault test".as_bytes(), true); //test import aes-cbc key - test_pki_import_key_case(&core, token, "aes-cbc-128-import", "aes-cbc", 128, "1c499088cddd0382918bd5650718533d", "77628ff2c35adc7efdecfb0e86a4576f", true); - test_pki_import_key_case(&core, token, "aes-cbc-192-import", "aes-cbc", 192, "1c499088cddd0382918bd5650718533d", "807f5f15d2924f104700f058030298c8591d0f6b5163b333", true); - test_pki_import_key_case(&core, token, "aes-cbc-256-import", "aes-cbc", 256, "1c499088cddd0382918bd5650718533d", "521fc4bb8ee6015ac5a6e3e611854aa7608a17413f72ee007e799dac303853e1", true); - test_pki_import_key_case(&core, token, "aes-cbc-256-import", "aes-cbc", 256, "1c499088cddd0382918bd5650718533d", "same key name", false); - test_pki_import_key_case(&core, token, "aes-cbc-256-import-bad-type", "aes-cbcc", 256, "1c499088cddd0382918bd5650718533d", "521fc4bb8ee6015ac5a6e3e611854aa7608a17413f72ee007e799dac303853e1", false); - test_pki_import_key_case(&core, token, "aes-cbc-256-import-bad-hex", "aes-cbc", 256, "1c499088cddd0382918bd5650718533d", "21521fc4bb8ee6015ac5a6e3e611854aa7608a17413f72ee007e799dac303853e1", false); + test_pki_import_key_case( + &core, + token, + "aes-cbc-128-import", + "aes-cbc", + 128, + "1c499088cddd0382918bd5650718533d", + "77628ff2c35adc7efdecfb0e86a4576f", + true, + ); + test_pki_import_key_case( + &core, + token, + "aes-cbc-192-import", + "aes-cbc", + 192, + "1c499088cddd0382918bd5650718533d", + "807f5f15d2924f104700f058030298c8591d0f6b5163b333", + true, + ); + test_pki_import_key_case( + &core, + token, + "aes-cbc-256-import", + "aes-cbc", + 256, + "1c499088cddd0382918bd5650718533d", + "521fc4bb8ee6015ac5a6e3e611854aa7608a17413f72ee007e799dac303853e1", + true, + ); + test_pki_import_key_case( + &core, + token, + "aes-cbc-256-import", + "aes-cbc", + 256, + "1c499088cddd0382918bd5650718533d", + "same key name", + false, + ); + test_pki_import_key_case( + &core, + token, + "aes-cbc-256-import-bad-type", + "aes-cbcc", + 256, + "1c499088cddd0382918bd5650718533d", + "521fc4bb8ee6015ac5a6e3e611854aa7608a17413f72ee007e799dac303853e1", + false, + ); + test_pki_import_key_case( + &core, + token, + "aes-cbc-256-import-bad-hex", + "aes-cbc", + 256, + "1c499088cddd0382918bd5650718533d", + "21521fc4bb8ee6015ac5a6e3e611854aa7608a17413f72ee007e799dac303853e1", + false, + ); //test aes-cbc encrypt and decrypt test_pki_encrypt_decrypt(&core, token, "aes-cbc-128-import", "rusty_vault test".as_bytes(), true); @@ -1223,12 +1858,57 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L test_pki_encrypt_decrypt(&core, token, "aes-cbc-256-import", "rusty_vault test".as_bytes(), true); //test import aes-ecb key - test_pki_import_key_case(&core, token, "aes-ecb-128-import", "aes-ecb", 128, "", "38a1f9ad74562db696872cbfa10cc46e", true); - test_pki_import_key_case(&core, token, "aes-ecb-192-import", "aes-ecb", 192, "", "b80f65a5a334e583bafd18d2e86667384ae16cb0467982de", true); - test_pki_import_key_case(&core, token, "aes-ecb-256-import", "aes-ecb", 256, "", "95b622ebf838b0b8b4cc60635333f87f9b10bcbe340b710020a6e9789156c052", true); + test_pki_import_key_case( + &core, + token, + "aes-ecb-128-import", + "aes-ecb", + 128, + "", + "38a1f9ad74562db696872cbfa10cc46e", + true, + ); + test_pki_import_key_case( + &core, + token, + "aes-ecb-192-import", + "aes-ecb", + 192, + "", + "b80f65a5a334e583bafd18d2e86667384ae16cb0467982de", + true, + ); + test_pki_import_key_case( + &core, + token, + "aes-ecb-256-import", + "aes-ecb", + 256, + "", + "95b622ebf838b0b8b4cc60635333f87f9b10bcbe340b710020a6e9789156c052", + true, + ); test_pki_import_key_case(&core, token, "aes-ecb-256-import", "aes-ecb", 256, "", "same key name", false); - test_pki_import_key_case(&core, token, "aes-ecb-256-import-bad-type", "aes-ecbb", 256, "", "95b622ebf838b0b8b4cc60635333f87f9b10bcbe340b710020a6e9789156c052", false); - test_pki_import_key_case(&core, token, "aes-ecb-256-import-bad-hex", "aes-ecb", 256, "", "2295b622ebf838b0b8b4cc60635333f87f9b10bcbe340b710020a6e9789156c052", false); + test_pki_import_key_case( + &core, + token, + "aes-ecb-256-import-bad-type", + "aes-ecbb", + 256, + "", + "95b622ebf838b0b8b4cc60635333f87f9b10bcbe340b710020a6e9789156c052", + false, + ); + test_pki_import_key_case( + &core, + token, + "aes-ecb-256-import-bad-hex", + "aes-ecb", + 256, + "", + "2295b622ebf838b0b8b4cc60635333f87f9b10bcbe340b710020a6e9789156c052", + false, + ); //test aes-gcm encrypt and decrypt test_pki_encrypt_decrypt(&core, token, "aes-ecb-128-import", "rusty_vault test".as_bytes(), true); @@ -1254,20 +1934,13 @@ x/+V28hUf8m8P2NxP5ALaDZagdaMfzjGZo3O3wDv33Cds0P5GMGQYnRXDxcZN/2L let barrier = barrier_aes_gcm::AESGCMBarrier::new(Arc::clone(&backend)); - let c = Arc::new(RwLock::new(Core { - physical: backend, - barrier: Arc::new(barrier), - ..Default::default() - })); + let c = Arc::new(RwLock::new(Core { physical: backend, barrier: Arc::new(barrier), ..Default::default() })); { let mut core = c.write().unwrap(); assert!(core.config(Arc::clone(&c), None).is_ok()); - let seal_config = SealConfig { - secret_shares: 10, - secret_threshold: 5, - }; + let seal_config = SealConfig { secret_shares: 10, secret_threshold: 5 }; let result = core.init(&seal_config); assert!(result.is_ok()); diff --git a/src/modules/pki/path_config_ca.rs b/src/modules/pki/path_config_ca.rs index bec61bc..1cc5c69 100644 --- a/src/modules/pki/path_config_ca.rs +++ b/src/modules/pki/path_config_ca.rs @@ -1,19 +1,15 @@ use openssl::{ - x509::{X509}, - pkey::{PKey, Id}, + pkey::{Id, PKey}, + x509::X509, }; use pem; + +use super::PkiBackendInner; use crate::{ - utils::cert, - utils::cert::CertBundle, - logical::{ - Backend, Request, Response, - }, - storage::{StorageEntry}, errors::RvError, -}; -use super::{ - PkiBackendInner, + logical::{Backend, Request, Response}, + storage::StorageEntry, + utils::{cert, cert::CertBundle}, }; impl PkiBackendInner { @@ -50,16 +46,16 @@ impl PkiBackendInner { match key.id() { Id::RSA => { cert_bundle.private_key_type = "rsa".to_string(); - }, + } Id::EC => { cert_bundle.private_key_type = "ec".to_string(); - }, + } Id::SM2 => { cert_bundle.private_key_type = "sm2".to_string(); - }, + } Id::ED25519 => { cert_bundle.private_key_type = "ed25519".to_string(); - }, + } _ => { cert_bundle.private_key_type = "other".to_string(); } diff --git a/src/modules/pki/path_config_crl.rs b/src/modules/pki/path_config_crl.rs index 3da211b..134c945 100644 --- a/src/modules/pki/path_config_crl.rs +++ b/src/modules/pki/path_config_crl.rs @@ -1,11 +1,7 @@ +use super::PkiBackendInner; use crate::{ - logical::{ - Backend, Request, Response, - }, errors::RvError, -}; -use super::{ - PkiBackendInner, + logical::{Backend, Request, Response}, }; impl PkiBackendInner { diff --git a/src/modules/pki/path_fetch.rs b/src/modules/pki/path_fetch.rs index 2c2491f..8f64b34 100644 --- a/src/modules/pki/path_fetch.rs +++ b/src/modules/pki/path_fetch.rs @@ -1,18 +1,17 @@ use serde_json::json; + +use super::PkiBackendInner; use crate::{ - logical::{ - Backend, Request, Response, - }, - utils::cert::CertBundle, errors::RvError, -}; -use super::{ - PkiBackendInner, + logical::{Backend, Request, Response}, + utils::cert::CertBundle, }; impl PkiBackendInner { pub fn handle_fetch_cert_bundle(&self, cert_bundle: &CertBundle) -> Result, RvError> { - let ca_chain_pem: String = cert_bundle.ca_chain.iter() + let ca_chain_pem: String = cert_bundle + .ca_chain + .iter() .map(|x509| x509.to_pem().unwrap()) .map(|pem| String::from_utf8_lossy(&pem).to_string()) .collect::>() @@ -21,7 +20,10 @@ impl PkiBackendInner { "ca_chain": ca_chain_pem, "certificate": String::from_utf8_lossy(&cert_bundle.certificate.to_pem()?), "serial_number": cert_bundle.serial_number.clone(), - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); Ok(Some(Response::data_response(Some(resp_data)))) } @@ -40,8 +42,11 @@ impl PkiBackendInner { self.handle_fetch_cert_bundle(&cert_bundle) } - pub fn read_path_fetch_cert_crl(&self, _backend: &dyn Backend, _req: &mut Request) -> Result, RvError> { + pub fn read_path_fetch_cert_crl( + &self, + _backend: &dyn Backend, + _req: &mut Request, + ) -> Result, RvError> { Ok(None) } } - diff --git a/src/modules/pki/path_issue.rs b/src/modules/pki/path_issue.rs index 25ede94..5e42e2f 100644 --- a/src/modules/pki/path_issue.rs +++ b/src/modules/pki/path_issue.rs @@ -1,24 +1,16 @@ -use std::time::{SystemTime, Duration, UNIX_EPOCH}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + use humantime::parse_duration; -use openssl::{ - x509::{ - X509NameBuilder, - }, - asn1::Asn1Time, -}; -use serde_json::{json, Value, Map}; +use openssl::{asn1::Asn1Time, x509::X509NameBuilder}; +use serde_json::{json, Map, Value}; + +use super::PkiBackendInner; use crate::{ - utils, - utils::cert, - utils::cert::CertBundle, - logical::{ - Backend, Request, Response, - }, - storage::{StorageEntry}, errors::RvError, -}; -use super::{ - PkiBackendInner, + logical::{Backend, Request, Response}, + storage::StorageEntry, + utils, + utils::{cert, cert::CertBundle}, }; impl PkiBackendInner { @@ -73,7 +65,8 @@ impl PkiBackendInner { if ttl != "" { let ttl_dur = parse_duration(ttl)?; let req_ttl_not_after_dur = SystemTime::now() + ttl_dur; - let req_ttl_not_after = Asn1Time::from_unix(req_ttl_not_after_dur.duration_since(UNIX_EPOCH)?.as_secs() as i64)?; + let req_ttl_not_after = + Asn1Time::from_unix(req_ttl_not_after_dur.duration_since(UNIX_EPOCH)?.as_secs() as i64)?; let ca_not_after = ca_bundle.certificate.not_after(); match ca_not_after.compare(&req_ttl_not_after) { Ok(ret) => { @@ -81,14 +74,14 @@ impl PkiBackendInner { return Err(RvError::ErrRequestInvalid); } not_after = req_ttl_not_after_dur; - }, + } Err(err) => { return Err(RvError::OpenSSL { source: err }); } } } - let mut subject_name = X509NameBuilder::new().unwrap(); + let mut subject_name = X509NameBuilder::new().unwrap(); if role_entry.country.len() > 0 { subject_name.append_entry_by_text("C", &role_entry.country).unwrap(); } @@ -110,11 +103,11 @@ impl PkiBackendInner { let subject = subject_name.build(); let mut cert = cert::Certificate { - not_before: not_before, - not_after: not_after, - subject: subject, + not_before, + not_after, + subject, dns_sans: common_names, - ip_sans: ip_sans, + ip_sans, key_bits: role_entry.key_bits, ..cert::Certificate::default() }; @@ -128,7 +121,9 @@ impl PkiBackendInner { } let cert_expiration = utils::asn1time_to_timestamp(cert_bundle.certificate.not_after().to_string().as_str())?; - let ca_chain_pem: String = cert_bundle.ca_chain.iter() + let ca_chain_pem: String = cert_bundle + .ca_chain + .iter() .map(|x509| x509.to_pem().unwrap()) .map(|pem| String::from_utf8_lossy(&pem).to_string()) .collect::>() @@ -141,7 +136,10 @@ impl PkiBackendInner { "private_key": String::from_utf8_lossy(&cert_bundle.private_key.private_key_to_pem_pkcs8()?), "private_key_type": cert_bundle.private_key_type.clone(), "serial_number": cert_bundle.serial_number.clone(), - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); if role_entry.generate_lease { let mut secret_data: Map = Map::new(); @@ -174,4 +172,3 @@ impl PkiBackendInner { Ok(cert_bundle) } } - diff --git a/src/modules/pki/path_keys.rs b/src/modules/pki/path_keys.rs index 66be787..f8691ca 100644 --- a/src/modules/pki/path_keys.rs +++ b/src/modules/pki/path_keys.rs @@ -1,18 +1,12 @@ -use openssl::{ - rsa::{Rsa}, - ec::{EcKey}, -}; +use openssl::{ec::EcKey, rsa::Rsa}; use serde_json::{json, Value}; + +use super::PkiBackendInner; use crate::{ - utils::key::KeyBundle, - logical::{ - Backend, Request, Response, - }, - storage::{StorageEntry}, errors::RvError, -}; -use super::{ - PkiBackendInner, + logical::{Backend, Request, Response}, + storage::StorageEntry, + utils::key::KeyBundle, }; const PKI_CONFIG_KEY_PREFIX: &str = "config/key/"; @@ -46,13 +40,19 @@ impl PkiBackendInner { "key_name": key_bundle.name.clone(), "key_type": key_bundle.key_type.clone(), "key_bits": key_bundle.bits, - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); if export_private_key { match key_type { "rsa" | "ec" => { - resp_data.insert("private_key".to_string(), Value::String(String::from_utf8_lossy(&key_bundle.key).to_string())); - }, + resp_data.insert( + "private_key".to_string(), + Value::String(String::from_utf8_lossy(&key_bundle.key).to_string()), + ); + } _ => { resp_data.insert("private_key".to_string(), Value::String(hex::encode(&key_bundle.key))); } @@ -92,11 +92,11 @@ impl PkiBackendInner { "rsa" => { let rsa = Rsa::private_key_from_pem(&key_bundle.key)?; key_bundle.bits = rsa.size() * 8; - }, + } "ec" => { let ec_key = EcKey::private_key_from_pem(&key_bundle.key)?; key_bundle.bits = ec_key.group().degree(); - }, + } _ => { return Err(RvError::ErrPkiKeyTypeInvalid); } @@ -112,7 +112,7 @@ impl PkiBackendInner { key_bundle.key = hex::decode(&hex_bundle)?; key_bundle.bits = (key_bundle.key.len() as u32) * 8; match key_bundle.bits { - 128 | 192 | 256 => {}, + 128 | 192 | 256 => {} _ => { return Err(RvError::ErrPkiKeyBitsInvalid); } @@ -125,8 +125,8 @@ impl PkiBackendInner { } else { return Err(RvError::ErrRequestFieldNotFound); } - }, - "aes-ecb" => {}, + } + "aes-ecb" => {} _ => { return Err(RvError::ErrPkiKeyTypeInvalid); } @@ -143,7 +143,10 @@ impl PkiBackendInner { "key_name": key_bundle.name.clone(), "key_type": key_bundle.key_type.clone(), "key_bits": key_bundle.bits, - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); Ok(Some(Response::data_response(Some(resp_data)))) } @@ -161,7 +164,10 @@ impl PkiBackendInner { let resp_data = json!({ "result": hex::encode(&result), - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); Ok(Some(Response::data_response(Some(resp_data)))) } @@ -182,7 +188,10 @@ impl PkiBackendInner { let resp_data = json!({ "result": result, - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); Ok(Some(Response::data_response(Some(resp_data)))) } @@ -202,7 +211,10 @@ impl PkiBackendInner { let resp_data = json!({ "result": hex::encode(&result), - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); Ok(Some(Response::data_response(Some(resp_data)))) } @@ -222,7 +234,10 @@ impl PkiBackendInner { let resp_data = json!({ "result": hex::encode(&result), - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); Ok(Some(Response::data_response(Some(resp_data)))) } diff --git a/src/modules/pki/path_revoke.rs b/src/modules/pki/path_revoke.rs index 86ce11a..8012409 100644 --- a/src/modules/pki/path_revoke.rs +++ b/src/modules/pki/path_revoke.rs @@ -1,11 +1,7 @@ +use super::PkiBackendInner; use crate::{ - logical::{ - Backend, Request, Response, - }, errors::RvError, -}; -use super::{ - PkiBackendInner, + logical::{Backend, Request, Response}, }; impl PkiBackendInner { @@ -17,4 +13,3 @@ impl PkiBackendInner { Ok(None) } } - diff --git a/src/modules/pki/path_roles.rs b/src/modules/pki/path_roles.rs index 7ef491e..6f55ee3 100644 --- a/src/modules/pki/path_roles.rs +++ b/src/modules/pki/path_roles.rs @@ -1,18 +1,14 @@ -use std::{ - time::{Duration}, -}; +use std::time::Duration; + use humantime::parse_duration; -use serde::{Serialize, Deserialize}; +use serde::{Deserialize, Serialize}; + +use super::PkiBackendInner; use crate::{ - utils::{serialize_duration, deserialize_duration}, - logical::{ - Backend, Request, Response, - }, - storage::StorageEntry, errors::RvError, -}; -use super::{ - PkiBackendInner, + logical::{Backend, Request, Response}, + storage::StorageEntry, + utils::{deserialize_duration, serialize_duration}, }; #[derive(Debug, Clone, Serialize, Deserialize)] @@ -90,7 +86,7 @@ impl PkiBackendInner { if key_bits != 2048 && key_bits != 3072 && key_bits != 4096 { return Err(RvError::ErrPkiKeyBitsInvalid); } - }, + } "ec" => { if key_bits == 0 { key_bits = 256; @@ -143,28 +139,28 @@ impl PkiBackendInner { let not_after = not_after_vale.as_str().unwrap().to_string(); let role_entry = RoleEntry { - ttl: ttl, - max_ttl: max_ttl, + ttl, + max_ttl, key_type: key_type.to_string(), key_bits: key_bits as u32, signature_bits: signature_bits as u32, - allow_localhost: allow_localhost, - allow_bare_domains: allow_bare_domains, - allow_subdomains: allow_subdomains, - allow_any_name: allow_any_name, - allow_ip_sans: allow_ip_sans, - server_flag: server_flag, - client_flag: client_flag, - use_csr_sans: use_csr_sans, - use_csr_common_name: use_csr_common_name, - country: country, - province: province, - locality: locality, - organization: organization, - ou: ou, - no_store: no_store, - generate_lease: generate_lease, - not_after: not_after, + allow_localhost, + allow_bare_domains, + allow_subdomains, + allow_any_name, + allow_ip_sans, + server_flag, + client_flag, + use_csr_sans, + use_csr_common_name, + country, + province, + locality, + organization, + ou, + no_store, + generate_lease, + not_after, }; let entry = StorageEntry::new(format!("role/{}", name).as_str(), &role_entry)?; diff --git a/src/modules/system/mod.rs b/src/modules/system/mod.rs index d115331..9909543 100644 --- a/src/modules/system/mod.rs +++ b/src/modules/system/mod.rs @@ -1,23 +1,20 @@ use std::{ - sync::{Arc, RwLock}, - ops::Deref, collections::HashMap, + ops::Deref, + sync::{Arc, RwLock}, }; -use as_any::{Downcast}; -use serde_json::{json, from_value, Value, Map}; + +use as_any::Downcast; +use serde_json::{from_value, json, Map, Value}; + use crate::{ - new_path, new_path_internal, new_logical_backend, new_logical_backend_internal, - logical::{ - Backend, LogicalBackend, Request, Response, - Operation, Path, PathOperation, Field, FieldType, - }, - storage::{StorageEntry}, - modules::{ - Module, auth::AuthModule, - }, - mount::MountEntry, core::Core, errors::RvError, + logical::{Backend, Field, FieldType, LogicalBackend, Operation, Path, PathOperation, Request, Response}, + modules::{auth::AuthModule, Module}, + mount::MountEntry, + new_logical_backend, new_logical_backend_internal, new_path, new_path_internal, + storage::StorageEntry, }; static SYSTEM_BACKEND_HELP: &str = r#" @@ -49,11 +46,7 @@ impl Deref for SystemBackend { impl SystemBackend { pub fn new(core: Arc>) -> Self { - Self { - inner: Arc::new(SystemBackendInner { - core: core, - }) - } + Self { inner: Arc::new(SystemBackendInner { core }) } } pub fn new_backend(&self) -> LogicalBackend { @@ -448,7 +441,11 @@ impl SystemBackendInner { Ok(None) } - pub fn handle_policy_delete(&self, _backend: &dyn Backend, _req: &mut Request) -> Result, RvError> { + pub fn handle_policy_delete( + &self, + _backend: &dyn Backend, + _req: &mut Request, + ) -> Result, RvError> { Ok(None) } @@ -460,7 +457,11 @@ impl SystemBackendInner { Ok(None) } - pub fn handle_audit_disable(&self, _backend: &dyn Backend, _req: &mut Request) -> Result, RvError> { + pub fn handle_audit_disable( + &self, + _backend: &dyn Backend, + _req: &mut Request, + ) -> Result, RvError> { Ok(None) } @@ -478,7 +479,10 @@ impl SystemBackendInner { let data = json!({ "value": String::from_utf8_lossy(&entry.unwrap().value), - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); Ok(Some(Response::data_response(Some(data)))) } @@ -493,10 +497,7 @@ impl SystemBackendInner { let core = self.core.read()?; let storage = core.barrier.as_storage(); - let entry = StorageEntry { - key: path.to_string(), - value: value.as_bytes().to_vec(), - }; + let entry = StorageEntry { key: path.to_string(), value: value.as_bytes().to_vec() }; storage.put(&entry)?; @@ -519,10 +520,7 @@ impl SystemBackendInner { impl SystemModule { pub fn new(core: Arc>) -> Self { - Self { - name: "system".to_string(), - backend: Arc::new(SystemBackend::new(core)), - } + Self { name: "system".to_string(), backend: Arc::new(SystemBackend::new(core)) } } } diff --git a/src/mount.rs b/src/mount.rs index a40a9c8..dd07e58 100644 --- a/src/mount.rs +++ b/src/mount.rs @@ -1,25 +1,25 @@ -use std::sync::{Arc, RwLock}; -use std::collections::HashMap; +use std::{ + collections::HashMap, + sync::{Arc, RwLock}, +}; + use lazy_static::lazy_static; -use serde::{Serialize, Deserialize}; -use crate::storage::{Storage, StorageEntry}; -use crate::storage::barrier_view::BarrierView; -use crate::core::Core; -use crate::router::Router; -use crate::utils::generate_uuid; -use crate::errors::RvError; +use serde::{Deserialize, Serialize}; + +use crate::{ + core::Core, + errors::RvError, + router::Router, + storage::{barrier_view::BarrierView, Storage, StorageEntry}, + utils::generate_uuid, +}; const CORE_MOUNT_CONFIG_PATH: &str = "core/mounts"; const LOGICAL_BARRIER_PREFIX: &str = "logical/"; -const SYSTEM_BARRIER_PREFIX: &str = "sys/"; +const SYSTEM_BARRIER_PREFIX: &str = "sys/"; lazy_static! { - static ref PROTECTED_MOUNTS: Vec<&'static str> = vec![ - "audit/", - "auth/", - "sys/", - ]; - + static ref PROTECTED_MOUNTS: Vec<&'static str> = vec!["audit/", "auth/", "sys/",]; static ref DEFAULT_CORE_MOUNTS: Vec = vec![ MountEntry { tainted: false, @@ -70,9 +70,7 @@ impl MountEntry { impl MountTable { pub fn new() -> Self { - Self { - entries: Arc::new(RwLock::new(HashMap::new())), - } + Self { entries: Arc::new(RwLock::new(HashMap::new())) } } pub fn hash(&self) -> Result, RvError> { @@ -87,12 +85,8 @@ impl MountTable { pub fn delete(&self, path: &str) -> bool { match self.entries.write() { - Ok(mut mounts) => { - mounts.remove(path).is_some() - } - Err(_) => { - false - } + Ok(mut mounts) => mounts.remove(path).is_some(), + Err(_) => false, } } @@ -148,10 +142,7 @@ impl MountTable { pub fn persist(&self, to: &str, storage: &dyn Storage) -> Result<(), RvError> { let value = serde_json::to_string(self)?; - let entry = StorageEntry { - key: to.to_string(), - value: value.into_bytes(), - }; + let entry = StorageEntry { key: to.to_string(), value: value.into_bytes() }; storage.put(&entry)?; Ok(()) } diff --git a/src/router.rs b/src/router.rs index 891c3fa..83868aa 100644 --- a/src/router.rs +++ b/src/router.rs @@ -1,11 +1,13 @@ use std::sync::{Arc, RwLock}; + use radix_trie::{Trie, TrieCommon}; + use crate::{ - logical::{Operation, Backend, Request, Response}, + errors::RvError, handler::Handler, + logical::{Backend, Operation, Request, Response}, mount::MountEntry, storage::barrier_view::BarrierView, - errors::RvError, }; struct RouterEntry { @@ -29,12 +31,16 @@ impl RouterEntry { impl Router { pub fn new() -> Self { - Self { - root: Arc::new(RwLock::new(Trie::new())), - } + Self { root: Arc::new(RwLock::new(Trie::new())) } } - pub fn mount(&self, backend: Arc, prefix: &str, mount_entry: Arc>, view: BarrierView) -> Result<(), RvError> { + pub fn mount( + &self, + backend: Arc, + prefix: &str, + mount_entry: Arc>, + view: BarrierView, + ) -> Result<(), RvError> { log::debug!("mount, prefix: {}", prefix); let mut root = self.root.write()?; @@ -52,7 +58,7 @@ impl Router { view: Arc::new(view), root_paths: new_radix_from_paths(root_paths.as_ref()), unauth_paths: new_radix_from_paths(unauth_paths.as_ref()), - mount_entry: mount_entry, + mount_entry, }; root.insert(prefix.to_string(), router_entry); @@ -172,7 +178,7 @@ impl Router { let root_path_match = root_entry.as_ref().unwrap().key().unwrap(); if *root_entry.as_ref().unwrap().value().unwrap() { - return Ok(remain.starts_with(root_path_match )); + return Ok(remain.starts_with(root_path_match)); } return Ok(remain == *root_path_match); @@ -248,11 +254,7 @@ fn new_radix_from_paths(paths: &[String]) -> Trie { for path in paths { // Check if this is a prefix or exact match let prefix_match = path.ends_with('*'); - let path = if prefix_match { - &path[..path.len() - 1] - } else { - path - }; + let path = if prefix_match { &path[..path.len() - 1] } else { path }; radix_paths.insert(path.to_string(), prefix_match); } diff --git a/src/shamir.rs b/src/shamir.rs index ddbbe18..17f3699 100644 --- a/src/shamir.rs +++ b/src/shamir.rs @@ -1,74 +1,39 @@ use rand::{thread_rng, RngCore}; + use crate::errors::RvError; static GF256_EXP: [u8; 256] = [ - 0x01, 0xe5, 0x4c, 0xb5, 0xfb, 0x9f, 0xfc, 0x12, - 0x03, 0x34, 0xd4, 0xc4, 0x16, 0xba, 0x1f, 0x36, - 0x05, 0x5c, 0x67, 0x57, 0x3a, 0xd5, 0x21, 0x5a, - 0x0f, 0xe4, 0xa9, 0xf9, 0x4e, 0x64, 0x63, 0xee, - 0x11, 0x37, 0xe0, 0x10, 0xd2, 0xac, 0xa5, 0x29, - 0x33, 0x59, 0x3b, 0x30, 0x6d, 0xef, 0xf4, 0x7b, - 0x55, 0xeb, 0x4d, 0x50, 0xb7, 0x2a, 0x07, 0x8d, - 0xff, 0x26, 0xd7, 0xf0, 0xc2, 0x7e, 0x09, 0x8c, - 0x1a, 0x6a, 0x62, 0x0b, 0x5d, 0x82, 0x1b, 0x8f, - 0x2e, 0xbe, 0xa6, 0x1d, 0xe7, 0x9d, 0x2d, 0x8a, - 0x72, 0xd9, 0xf1, 0x27, 0x32, 0xbc, 0x77, 0x85, - 0x96, 0x70, 0x08, 0x69, 0x56, 0xdf, 0x99, 0x94, - 0xa1, 0x90, 0x18, 0xbb, 0xfa, 0x7a, 0xb0, 0xa7, - 0xf8, 0xab, 0x28, 0xd6, 0x15, 0x8e, 0xcb, 0xf2, - 0x13, 0xe6, 0x78, 0x61, 0x3f, 0x89, 0x46, 0x0d, - 0x35, 0x31, 0x88, 0xa3, 0x41, 0x80, 0xca, 0x17, - 0x5f, 0x53, 0x83, 0xfe, 0xc3, 0x9b, 0x45, 0x39, - 0xe1, 0xf5, 0x9e, 0x19, 0x5e, 0xb6, 0xcf, 0x4b, - 0x38, 0x04, 0xb9, 0x2b, 0xe2, 0xc1, 0x4a, 0xdd, - 0x48, 0x0c, 0xd0, 0x7d, 0x3d, 0x58, 0xde, 0x7c, - 0xd8, 0x14, 0x6b, 0x87, 0x47, 0xe8, 0x79, 0x84, - 0x73, 0x3c, 0xbd, 0x92, 0xc9, 0x23, 0x8b, 0x97, - 0x95, 0x44, 0xdc, 0xad, 0x40, 0x65, 0x86, 0xa2, - 0xa4, 0xcc, 0x7f, 0xec, 0xc0, 0xaf, 0x91, 0xfd, - 0xf7, 0x4f, 0x81, 0x2f, 0x5b, 0xea, 0xa8, 0x1c, - 0x02, 0xd1, 0x98, 0x71, 0xed, 0x25, 0xe3, 0x24, - 0x06, 0x68, 0xb3, 0x93, 0x2c, 0x6f, 0x3e, 0x6c, - 0x0a, 0xb8, 0xce, 0xae, 0x74, 0xb1, 0x42, 0xb4, - 0x1e, 0xd3, 0x49, 0xe9, 0x9c, 0xc8, 0xc6, 0xc7, - 0x22, 0x6e, 0xdb, 0x20, 0xbf, 0x43, 0x51, 0x52, -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x79, 0x84, 0x73, 0x3c, 0xbd, + 0x92, 0xc9, 0x23, 0x8b, 0x97, 0x95, 0x44, 0xdc, 0xad, 0x40, 0x65, 0x86, 0xa2, 0xa4, 0xcc, 0x7f, 0xec, 0xc0, 0xaf, + 0x91, 0xfd, 0xf7, 0x4f, 0x81, 0x2f, 0x5b, 0xea, 0xa8, 0x1c, 0x02, 0xd1, 0x98, 0x71, 0xed, 0x25, 0xe3, 0x24, 0x06, + 0x68, 0xb3, 0x93, 0x2c, 0x6f, 0x3e, 0x6c, 0x0a, 0xb8, 0xce, 0xae, 0x74, 0xb1, 0x42, 0xb4, 0x1e, 0xd3, 0x49, 0xe9, + 0x9c, 0xc8, 0xc6, 0xc7, 0x22, 0x6e, 0xdb, 0x20, 0xbf, 0x43, 0x51, 0x52, 0x66, 0xb2, 0x76, 0x60, 0xda, 0xc5, 0xf3, + 0xf6, 0xaa, 0xcd, 0x9a, 0xa0, 0x75, 0x54, 0x0e, 0x01, ]; static GF256_LOG: [u8; 256] = [ - 0x00, 0xff, 0xc8, 0x08, 0x91, 0x10, 0xd0, 0x36, - 0x5a, 0x3e, 0xd8, 0x43, 0x99, 0x77, 0xfe, 0x18, - 0x23, 0x20, 0x07, 0x70, 0xa1, 0x6c, 0x0c, 0x7f, - 0x62, 0x8b, 0x40, 0x46, 0xc7, 0x4b, 0xe0, 0x0e, - 0xeb, 0x16, 0xe8, 0xad, 0xcf, 0xcd, 0x39, 0x53, - 0x6a, 0x27, 0x35, 0x93, 0xd4, 0x4e, 0x48, 0xc3, - 0x2b, 0x79, 0x54, 0x28, 0x09, 0x78, 0x0f, 0x21, - 0x90, 0x87, 0x14, 0x2a, 0xa9, 0x9c, 0xd6, 0x74, - 0xb4, 0x7c, 0xde, 0xed, 0xb1, 0x86, 0x76, 0xa4, - 0x98, 0xe2, 0x96, 0x8f, 0x02, 0x32, 0x1c, 0xc1, - 0x33, 0xee, 0xef, 0x81, 0xfd, 0x30, 0x5c, 0x13, - 0x9d, 0x29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0x0b, 0xf5, 0xe6, 0xe7, 0xe5, 0xac, 0x7e, 0x6e, 0xb9, 0xf9, 0xda, 0x8e, 0x9a, + 0xc9, 0x24, 0xe1, 0x0a, 0x15, 0x6b, 0x3a, 0xa0, 0x51, 0xf4, 0xea, 0xb2, 0x97, 0x9e, 0x5d, 0x22, 0x88, 0x94, 0xce, + 0x19, 0x01, 0x71, 0x4c, 0xa5, 0xe3, 0xc5, 0x31, 0xbb, 0xcc, 0x1f, 0x2d, 0x3b, 0x52, 0x6f, 0xf6, 0x2e, 0x89, 0xf7, + 0xc0, 0x68, 0x1b, 0x64, 0x04, 0x06, 0xbf, 0x83, 0x38, ]; pub const SHAMIR_OVERHEAD: usize = 1; @@ -91,9 +56,7 @@ impl ShamirSecret { coefficients.push(coef); } - ShamirSecret { - coefficients, - } + ShamirSecret { coefficients } } pub fn get_share(&self, id: u8) -> Result, RvError> { @@ -112,7 +75,7 @@ impl ShamirSecret { } pub fn is_valid_share(&self, share: &[u8]) -> bool { - let id = share[share.len()-1]; + let id = share[share.len() - 1]; match self.get_share(id) { Ok(s) => s == share, _ => false, @@ -151,7 +114,6 @@ impl ShamirSecret { for byte_to_use in 0..rounds { let mut fxs: Vec = vec![]; for share in shares.clone() { - fxs.push(share[0..share.len()][byte_to_use]); } @@ -173,7 +135,7 @@ impl ShamirSecret { let secret_data = ShamirSecret::with_secret(secret, threshold); let mut out: Vec> = vec![]; - for i in 1..(part+1) { + for i in 1..(part + 1) { let shared = secret_data.get_share(i)?; out.push(shared); } @@ -217,8 +179,7 @@ impl ShamirSecret { match (first_term, second_term) { (Some(a), Some(b)) => { let this_term = vec![a, b]; - this_polynomial = - ShamirSecret::multiply_polynomials(&this_polynomial, &this_term); + this_polynomial = ShamirSecret::multiply_polynomials(&this_polynomial, &this_term); } (_, _) => return None, }; @@ -226,8 +187,7 @@ impl ShamirSecret { if fxs.len() + 1 >= i { this_polynomial = ShamirSecret::multiply_polynomials(&this_polynomial, &[fxs[i]]) } - returned_coefficients = - ShamirSecret::add_polynomials(&returned_coefficients, &this_polynomial); + returned_coefficients = ShamirSecret::add_polynomials(&returned_coefficients, &this_polynomial); } Some(returned_coefficients) } @@ -247,8 +207,7 @@ impl ShamirSecret { if a == 0 || b == 0 { 0 } else { - GF256_EXP[((u16::from(GF256_LOG[a as usize]) + u16::from(GF256_LOG[b as usize])) % 255) - as usize] + GF256_EXP[((u16::from(GF256_LOG[a as usize]) + u16::from(GF256_LOG[b as usize])) % 255) as usize] } } diff --git a/src/storage/barrier.rs b/src/storage/barrier.rs index 6bfe00f..0715437 100644 --- a/src/storage/barrier.rs +++ b/src/storage/barrier.rs @@ -1,5 +1,5 @@ -use crate::errors::RvError; use super::Storage; +use crate::errors::RvError; pub const BARRIER_INIT_PATH: &str = "barrier/init"; diff --git a/src/storage/barrier_aes_gcm.rs b/src/storage/barrier_aes_gcm.rs index 21e26d6..702a1ce 100644 --- a/src/storage/barrier_aes_gcm.rs +++ b/src/storage/barrier_aes_gcm.rs @@ -1,12 +1,18 @@ -use std::sync::{RwLock, Arc}; -use rand::{Rng, thread_rng}; -use openssl::cipher::{Cipher, CipherRef}; -use openssl::cipher_ctx::{CipherCtx}; -use serde::{Serialize, Deserialize}; +use std::sync::{Arc, RwLock}; + +use openssl::{ + cipher::{Cipher, CipherRef}, + cipher_ctx::CipherCtx, +}; +use rand::{thread_rng, Rng}; +use serde::{Deserialize, Serialize}; + +use super::{ + barrier::{SecurityBarrier, BARRIER_INIT_PATH}, + physical::{Backend, BackendEntry}, + Storage, StorageEntry, +}; use crate::errors::RvError; -use super::{Storage, StorageEntry}; -use super::barrier::{SecurityBarrier, BARRIER_INIT_PATH}; -use super::physical::{Backend, BackendEntry}; const EPOCH_SIZE: usize = 4; const KEY_EPOCH: u8 = 1; @@ -55,10 +61,7 @@ impl Storage for AESGCMBarrier { // Decrypt the ciphertext let plain = self.decrypt(pe.as_ref().unwrap().value.as_slice())?; - let entry = StorageEntry{ - key: key.to_string(), - value: plain, - }; + let entry = StorageEntry { key: key.to_string(), value: plain }; Ok(Some(entry)) } @@ -71,10 +74,7 @@ impl Storage for AESGCMBarrier { let ciphertext = self.encrypt(entry.value.as_slice())?; - let be = BackendEntry { - key: entry.key.clone(), - value: ciphertext, - }; + let be = BackendEntry { key: entry.key.clone(), value: ciphertext }; self.backend.put(&be)?; @@ -110,10 +110,7 @@ impl SecurityBarrier for AESGCMBarrier { let encrypt_key = self.generate_key()?; - let barrier_init = BarrierInit { - version: 1, - key: encrypt_key, - }; + let barrier_init = BarrierInit { version: 1, key: encrypt_key }; let serialized_barrier_init = serde_json::to_string(&barrier_init)?; @@ -121,10 +118,7 @@ impl SecurityBarrier for AESGCMBarrier { let value = self.encrypt(serialized_barrier_init.as_bytes())?; - let be = BackendEntry { - key: BARRIER_INIT_PATH.to_string(), - value: value, - }; + let be = BackendEntry { key: BARRIER_INIT_PATH.to_string(), value }; self.backend.put(&be)?; @@ -251,9 +245,9 @@ impl AESGCMBarrier { out[3] = KEY_EPOCH; out[4] = AES_GCM_VERSION; - out[5..5+nonce_size].copy_from_slice(nonce.as_slice()); - out[5+nonce_size..5+nonce_size+ciphertext.len()].copy_from_slice(ciphertext.as_slice()); - out[5+nonce_size+ciphertext.len()..size].copy_from_slice(tag.as_slice()); + out[5..5 + nonce_size].copy_from_slice(nonce.as_slice()); + out[5 + nonce_size..5 + nonce_size + ciphertext.len()].copy_from_slice(ciphertext.as_slice()); + out[5 + nonce_size + ciphertext.len()..size].copy_from_slice(tag.as_slice()); Ok(out) } @@ -278,14 +272,14 @@ impl AESGCMBarrier { return Err(RvError::ErrBarrierVersionMismatch); } - let nonce = &ciphertext[5..5+nonce_size]; + let nonce = &ciphertext[5..5 + nonce_size]; cipher_ctx.decrypt_init(Some(cipher), Some(key.as_slice()), Some(nonce))?; cipher_ctx.set_padding(false); let tag_size = cipher_ctx.tag_length(); - let raw = &ciphertext[5+nonce_size..ciphertext.len()-tag_size]; - let tag = &ciphertext[ciphertext.len()-tag_size..ciphertext.len()]; + let raw = &ciphertext[5 + nonce_size..ciphertext.len() - tag_size]; + let tag = &ciphertext[ciphertext.len() - tag_size..ciphertext.len()]; let size = ciphertext.len() - 5 - nonce_size - tag_size; let mut out = vec![0u8; size]; @@ -300,13 +294,12 @@ impl AESGCMBarrier { #[cfg(test)] mod test { - use std::env; - use std::fs; - use std::collections::HashMap; - use serde_json::Value; + use std::{collections::HashMap, env, fs}; + use go_defer::defer; - use super::*; - use super::super::*; + use serde_json::Value; + + use super::{super::*, *}; #[test] fn test_encrypt_decrypt() { @@ -330,7 +323,7 @@ mod test { let backend = physical::new_backend("file", &conf).unwrap(); let barrier = AESGCMBarrier { - backend: backend, + backend, barrier_info: Arc::new(RwLock::new(BarrierInfo { sealed: true, key: Some(key), @@ -362,14 +355,15 @@ mod test { assert!(ctx.is_ok()); let cipher_ctx = ctx.unwrap(); - let key = vec![121, 133, 170, 204, 71, 77, 160, 134, 22, 37, 254, 206, 120, - 206, 143, 197, 150, 83, 5, 45, 121, 51, 124, 110, 162, 1, - 9, 51, 16, 75, 157, 129]; + let key = vec![ + 121, 133, 170, 204, 71, 77, 160, 134, 22, 37, 254, 206, 120, 206, 143, 197, 150, 83, 5, 45, 121, 51, 124, + 110, 162, 1, 9, 51, 16, 75, 157, 129, + ]; let backend = physical::new_backend("file", &conf).unwrap(); let barrier = AESGCMBarrier { - backend: backend, + backend, barrier_info: Arc::new(RwLock::new(BarrierInfo { sealed: true, key: Some(key), @@ -378,10 +372,11 @@ mod test { })), }; - let ciphertext = &[0, 0, 0, 1, 1, 99, 115, 28, 164, 208, 39, 20, 70, 150, - 217, 80, 159, 80, 251, 42, 49, 32, 136, 109, 90, 160, - 217, 227, 252, 159, 54, 194, 68, 146, 37, 88, 57, 225, - 144, 96, 105, 160, 187, 112, 145, 175, 24, 89, 33]; + let ciphertext = &[ + 0, 0, 0, 1, 1, 99, 115, 28, 164, 208, 39, 20, 70, 150, 217, 80, 159, 80, 251, 42, 49, 32, 136, 109, 90, + 160, 217, 227, 252, 159, 54, 194, 68, 146, 37, 88, 57, 225, 144, 96, 105, 160, 187, 112, 145, 175, 24, 89, + 33, + ]; let res = barrier.decrypt(ciphertext); assert!(res.is_ok()); } @@ -478,18 +473,9 @@ mod test { let get = barrier.get("/"); assert!(get.is_err()); - let entry1 = StorageEntry { - key: "bar".to_string(), - value: "test1".as_bytes().to_vec(), - }; - let entry2 = StorageEntry { - key: "bar/foo".to_string(), - value: "test2".as_bytes().to_vec(), - }; - let entry3 = StorageEntry { - key: "bar/foo/goo".to_string(), - value: "test3".as_bytes().to_vec(), - }; + let entry1 = StorageEntry { key: "bar".to_string(), value: "test1".as_bytes().to_vec() }; + let entry2 = StorageEntry { key: "bar/foo".to_string(), value: "test2".as_bytes().to_vec() }; + let entry3 = StorageEntry { key: "bar/foo/goo".to_string(), value: "test3".as_bytes().to_vec() }; let put = barrier.put(&entry1); assert!(put.is_ok()); @@ -505,12 +491,14 @@ mod test { assert!(keys.is_ok()); let keys = keys.unwrap(); assert_eq!(keys.len(), 3); - assert!(keys.join("") == "barbarrier/bar/" + assert!( + keys.join("") == "barbarrier/bar/" || keys.join("") == "barbar/barrier/" || keys.join("") == "bar/barbarrier/" || keys.join("") == "barrier/bar/bar" || keys.join("") == "barrier/barbar/" - || keys.join("") == "bar/barrier/bar"); + || keys.join("") == "bar/barrier/bar" + ); let get = barrier.get("bar"); assert!(get.is_ok()); assert_eq!(get.unwrap().unwrap().value, "test1".as_bytes()); diff --git a/src/storage/barrier_view.rs b/src/storage/barrier_view.rs index ddc3eee..33ec270 100644 --- a/src/storage/barrier_view.rs +++ b/src/storage/barrier_view.rs @@ -1,6 +1,7 @@ use std::sync::Arc; + +use super::{barrier::SecurityBarrier, Storage, StorageEntry}; use crate::errors::RvError; -use super::{Storage, StorageEntry, barrier::SecurityBarrier}; pub struct BarrierView { barrier: Arc, @@ -17,10 +18,7 @@ impl Storage for BarrierView { self.sanity_check(key)?; let storage_entry = self.barrier.get(self.expand_key(key).as_str())?; if let Some(entry) = storage_entry { - Ok(Some(StorageEntry { - key: self.truncate_key(entry.key.as_str()), - value: entry.value, - })) + Ok(Some(StorageEntry { key: self.truncate_key(entry.key.as_str()), value: entry.value })) } else { Ok(None) } @@ -28,10 +26,7 @@ impl Storage for BarrierView { fn put(&self, entry: &StorageEntry) -> Result<(), RvError> { self.sanity_check(entry.key.as_str())?; - let nested = StorageEntry { - key: self.expand_key(entry.key.as_str()), - value: entry.value.clone(), - }; + let nested = StorageEntry { key: self.expand_key(entry.key.as_str()), value: entry.value.clone() }; self.barrier.put(&nested) } @@ -43,17 +38,11 @@ impl Storage for BarrierView { impl BarrierView { pub fn new(barrier: Arc, prefix: &str) -> Self { - Self { - barrier: barrier, - prefix: prefix.to_string(), - } + Self { barrier, prefix: prefix.to_string() } } pub fn new_sub_view(&self, prefix: &str) -> Self { - Self { - barrier: Arc::clone(&self.barrier), - prefix: self.expand_key(prefix), - } + Self { barrier: Arc::clone(&self.barrier), prefix: self.expand_key(prefix) } } pub fn get_keys(&self) -> Result, RvError> { @@ -112,15 +101,13 @@ impl BarrierView { #[cfg(test)] mod test { - use std::env; - use std::fs; - use std::sync::Arc; - use std::collections::HashMap; - use rand::{Rng, thread_rng}; - use serde_json::Value; + use std::{collections::HashMap, env, fs, sync::Arc}; + use go_defer::defer; - use super::*; - use super::super::*; + use rand::{thread_rng, Rng}; + use serde_json::Value; + + use super::{super::*, *}; #[test] fn test_new_barrier_view() { diff --git a/src/storage/mod.rs b/src/storage/mod.rs index 09a7c45..4738fec 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -1,9 +1,10 @@ +use serde::{Deserialize, Serialize}; + use crate::errors::RvError; -use serde::{Serialize, Deserialize}; pub mod barrier; -pub mod barrier_view; pub mod barrier_aes_gcm; +pub mod barrier_view; pub mod physical; pub trait Storage { @@ -22,10 +23,7 @@ pub struct StorageEntry { impl Default for StorageEntry { fn default() -> Self { - Self { - key: String::new(), - value: Vec::new(), - } + Self { key: String::new(), value: Vec::new() } } } @@ -33,9 +31,6 @@ impl StorageEntry { pub fn new(k: &str, v: &impl Serialize) -> Result { let data = serde_json::to_string(v)?; - Ok(StorageEntry { - key: k.to_string(), - value: data.into_bytes(), - }) + Ok(StorageEntry { key: k.to_string(), value: data.into_bytes() }) } } diff --git a/src/storage/physical/file.rs b/src/storage/physical/file.rs index df507ff..a64acf1 100644 --- a/src/storage/physical/file.rs +++ b/src/storage/physical/file.rs @@ -1,11 +1,15 @@ -use std::sync::{Mutex, Arc}; -use std::collections::HashMap; -use std::path::{PathBuf}; -use std::fs::{self, File}; -use std::io::{self, Read, Write}; +use std::{ + collections::HashMap, + fs::{self, File}, + io::{self, Read, Write}, + path::PathBuf, + sync::{Arc, Mutex}, +}; + use serde_json::Value; -use crate::errors::RvError; + use super::{Backend, BackendEntry}; +use crate::errors::RvError; #[derive(Debug)] pub struct FileBackend { @@ -115,12 +119,9 @@ impl FileBackend { return Err(RvError::ErrPhysicalConfigItemMissing); } - Ok(FileBackend { - path: PathBuf::from(path.unwrap()), - lock: Arc::new(Mutex::new(0)), - }) + Ok(FileBackend { path: PathBuf::from(path.unwrap()), lock: Arc::new(Mutex::new(0)) }) } - None => Err(RvError::ErrPhysicalConfigItemMissing) + None => Err(RvError::ErrPhysicalConfigItemMissing), } } @@ -134,13 +135,14 @@ impl FileBackend { #[cfg(test)] mod test { - use std::env; - use std::fs; - use std::collections::HashMap; + use std::{collections::HashMap, env, fs}; + use go_defer::defer; - use super::*; - use super::super::test::test_backend; - use super::super::test::test_backend_list_prefix; + + use super::{ + super::test::{test_backend, test_backend_list_prefix}, + *, + }; #[test] fn test_file_backend() { diff --git a/src/storage/physical/mock.rs b/src/storage/physical/mock.rs index bdf03fa..d568d7d 100644 --- a/src/storage/physical/mock.rs +++ b/src/storage/physical/mock.rs @@ -1,6 +1,7 @@ use std::default::Default; -use crate::errors::RvError; + use super::{Backend, BackendEntry}; +use crate::errors::RvError; #[derive(Default)] pub struct MockBackend(u32); diff --git a/src/storage/physical/mod.rs b/src/storage/physical/mod.rs index b39c0e1..2d17b0f 100644 --- a/src/storage/physical/mod.rs +++ b/src/storage/physical/mod.rs @@ -1,7 +1,8 @@ -use std::sync::Arc; -use std::collections::HashMap; -use serde::{Serialize, Deserialize}; -use serde_json::{Value}; +use std::{collections::HashMap, sync::Arc}; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + use crate::errors::RvError; pub mod file; @@ -27,21 +28,17 @@ pub fn new_backend(t: &str, conf: &HashMap) -> Result { - Ok(Arc::new(mock::MockBackend::new())) - } - _ => { - Err(RvError::ErrPhysicalTypeInvalid) - } + "mock" => Ok(Arc::new(mock::MockBackend::new())), + _ => Err(RvError::ErrPhysicalTypeInvalid), } } #[cfg(test)] mod test { - use std::env; - use std::fs; - use std::collections::HashMap; + use std::{collections::HashMap, env, fs}; + use go_defer::defer; + use super::*; #[test] @@ -82,10 +79,7 @@ mod test { assert_eq!(res.unwrap(), None); // Make an Entry - let entry = BackendEntry { - key: "bar".to_string(), - value: "test".as_bytes().to_vec(), - }; + let entry = BackendEntry { key: "bar".to_string(), value: "test".as_bytes().to_vec() }; let res = backend.put(&entry); assert!(res.is_ok()); @@ -97,7 +91,7 @@ mod test { Some(e) => { assert_eq!(e, entry); } - None => panic!("Get should ok!") + None => panic!("Get should ok!"), } // List should not be empty @@ -124,18 +118,9 @@ mod test { } pub fn test_backend_list_prefix(backend: &dyn Backend) { - let entry1 = BackendEntry { - key: "bar".to_string(), - value: "test".as_bytes().to_vec(), - }; - let entry2 = BackendEntry { - key: "bar/foo".to_string(), - value: "test".as_bytes().to_vec(), - }; - let entry3 = BackendEntry { - key: "bar/foo/goo".to_string(), - value: "test".as_bytes().to_vec(), - }; + let entry1 = BackendEntry { key: "bar".to_string(), value: "test".as_bytes().to_vec() }; + let entry2 = BackendEntry { key: "bar/foo".to_string(), value: "test".as_bytes().to_vec() }; + let entry3 = BackendEntry { key: "bar/foo/goo".to_string(), value: "test".as_bytes().to_vec() }; let res = backend.put(&entry1); assert!(res.is_ok()); diff --git a/src/utils/cert.rs b/src/utils/cert.rs index ac7b6c2..cec688e 100644 --- a/src/utils/cert.rs +++ b/src/utils/cert.rs @@ -1,29 +1,25 @@ use std::time::{SystemTime, UNIX_EPOCH}; + +use foreign_types::ForeignType; +use lazy_static::lazy_static; +use libc::c_int; use openssl::{ - x509::{ - X509, X509Builder, X509Name, X509NameBuilder, X509Extension, - extension::{ - KeyUsage, SubjectAlternativeName, - SubjectKeyIdentifier, AuthorityKeyIdentifier, - BasicConstraints, - }, - }, - pkey::{PKey, Private}, - rsa::Rsa, - ec::{EcGroup, EcKey}, + asn1::{Asn1OctetString, Asn1Time}, bn::{BigNum, MsbOption}, + ec::{EcGroup, EcKey}, hash::MessageDigest, nid::Nid, - asn1::{Asn1OctetString, Asn1Time}, + pkey::{PKey, Private}, + rsa::Rsa, + x509::{ + extension::{AuthorityKeyIdentifier, BasicConstraints, KeyUsage, SubjectAlternativeName, SubjectKeyIdentifier}, + X509Builder, X509Extension, X509Name, X509NameBuilder, X509, + }, }; -use libc::c_int; -use lazy_static::lazy_static; -use foreign_types::{ForeignType}; -use serde::{ser::SerializeTuple, Serialize, Serializer, Deserialize, Deserializer}; +use serde::{ser::SerializeTuple, Deserialize, Deserializer, Serialize, Serializer}; use serde_bytes::ByteBuf; -use crate::{ - errors::RvError, -}; + +use crate::errors::RvError; lazy_static! { static ref X509_DEFAULT: X509 = X509Builder::new().unwrap().build(); @@ -104,9 +100,7 @@ where } pub fn is_ca_cert(cert: &X509) -> bool { - unsafe { - X509_check_ca(cert.as_ptr()) != 0 - } + unsafe { X509_check_ca(cert.as_ptr()) != 0 } } impl Default for CertBundle { @@ -217,10 +211,11 @@ impl Default for Certificate { } impl Certificate { - pub fn to_x509(&mut self, - ca_cert: &X509, - ca_key: &PKey, - private_key: &PKey + pub fn to_x509( + &mut self, + ca_cert: &X509, + ca_key: &PKey, + private_key: &PKey, ) -> Result { let mut builder = X509::builder()?; builder.set_version(self.version)?; @@ -267,15 +262,11 @@ impl Certificate { builder.append_extension(BasicConstraints::new().critical().ca().build()?)?; } - builder.append_extension(KeyUsage::new() - .critical() - .non_repudiation() - .digital_signature() - .key_encipherment() - .build()?)?; + builder.append_extension( + KeyUsage::new().critical().non_repudiation().digital_signature().key_encipherment().build()?, + )?; - let subject_key_id = SubjectKeyIdentifier::new() - .build(&builder.x509v3_context(Some(ca_cert), None))?; + let subject_key_id = SubjectKeyIdentifier::new().build(&builder.x509v3_context(Some(ca_cert), None))?; builder.append_extension(subject_key_id)?; let authority_key_id = AuthorityKeyIdentifier::new() @@ -289,10 +280,7 @@ impl Certificate { Ok(builder.build()) } - pub fn to_cert_bundle(&mut self, - ca_cert: &X509, - ca_key: &PKey) - -> Result { + pub fn to_cert_bundle(&mut self, ca_cert: &X509, ca_key: &PKey) -> Result { let key_bits = self.key_bits; let priv_key = match self.key_type.as_str() { "rsa" => { @@ -302,7 +290,7 @@ impl Certificate { let rsa_key = Rsa::generate(key_bits)?; let pkey = PKey::from_rsa(rsa_key)?; pkey - }, + } "ec" => { let curve_name = match key_bits { 224 => Nid::SECP224R1, @@ -317,7 +305,7 @@ impl Certificate { let ec_key = EcKey::generate(ec_group.as_ref())?; let pkey = PKey::from_ec_key(ec_key)?; pkey - }, + } _ => { return Err(RvError::ErrPkiKeyTypeInvalid); } @@ -326,7 +314,8 @@ impl Certificate { let cert = self.to_x509(ca_cert, ca_key, &priv_key)?; let serial_number = cert.serial_number().to_bn()?; let serial_number_hex = serial_number.to_hex_str()?; - let serial_number_hex = serial_number_hex.chars() + let serial_number_hex = serial_number_hex + .chars() .collect::>() .chunks(2) .map(|chunk| chunk.iter().collect::()) @@ -347,15 +336,16 @@ impl Certificate { #[cfg(test)] mod test { - use super::*; use humantime::parse_duration; use openssl::rsa::Rsa; + use super::*; + #[test] fn test_create_certificate() { let not_before = SystemTime::now(); let not_after = not_before + parse_duration("30d").unwrap(); - let mut subject_name = X509NameBuilder::new().unwrap(); + let mut subject_name = X509NameBuilder::new().unwrap(); subject_name.append_entry_by_text("C", "CN").unwrap(); subject_name.append_entry_by_text("ST", "ZJ").unwrap(); subject_name.append_entry_by_text("L", "HZ").unwrap(); @@ -364,9 +354,9 @@ mod test { let subject = subject_name.build(); let mut cert = Certificate { - not_before: not_before, - not_after: not_after, - subject: subject, + not_before, + not_after, + subject, dns_sans: vec!["www.test.com".to_string(), "test.com".to_string()], email_sans: vec!["www@test.com".to_string(), "xx@test.com".to_string()], ip_sans: vec!["1.1.1.1".to_string(), "2.2.2.2".to_string()], diff --git a/src/utils/key.rs b/src/utils/key.rs index 473feda..d232b5e 100644 --- a/src/utils/key.rs +++ b/src/utils/key.rs @@ -1,18 +1,16 @@ use openssl::{ - pkey::{PKey}, - rsa::{Rsa, Padding}, ec::{EcGroup, EcKey}, + hash::MessageDigest, nid::Nid, + pkey::PKey, rand::rand_bytes, - hash::MessageDigest, + rsa::{Padding, Rsa}, sign::{Signer, Verifier}, - symm::{Cipher, encrypt, decrypt, encrypt_aead, decrypt_aead}, -}; -use serde::{Serialize, Deserialize}; -use crate::{ - utils::generate_uuid, - errors::RvError, + symm::{decrypt, decrypt_aead, encrypt, encrypt_aead, Cipher}, }; +use serde::{Deserialize, Serialize}; + +use crate::{errors::RvError, utils::generate_uuid}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct KeyBundle { @@ -40,12 +38,7 @@ impl Default for KeyBundle { impl KeyBundle { pub fn new(name: &str, key_type: &str, key_bits: u32) -> Self { - Self { - name: name.to_string(), - key_type: key_type.to_string(), - bits: key_bits, - ..KeyBundle::default() - } + Self { name: name.to_string(), key_type: key_type.to_string(), bits: key_bits, ..KeyBundle::default() } } pub fn generate(&mut self) -> Result<(), RvError> { @@ -58,7 +51,7 @@ impl KeyBundle { let rsa_key = Rsa::generate(key_bits)?; let pkey = PKey::from_rsa(rsa_key)?; pkey.private_key_to_pem_pkcs8()? - }, + } "ec" => { let curve_name = match key_bits { 224 => Nid::SECP224R1, @@ -73,7 +66,7 @@ impl KeyBundle { let ec_key = EcKey::generate(ec_group.as_ref())?; let pkey = PKey::from_ec_key(ec_key)?; pkey.private_key_to_pem_pkcs8()? - }, + } "aes-gcm" | "aes-cbc" | "aes-ecb" => { if key_bits != 128 && key_bits != 192 && key_bits != 256 { return Err(RvError::ErrPkiKeyBitsInvalid); @@ -85,10 +78,10 @@ impl KeyBundle { self.iv = iv_bytes; } - let mut random_bytes = vec![0u8; (key_bits/8) as usize]; + let mut random_bytes = vec![0u8; (key_bits / 8) as usize]; rand_bytes(&mut random_bytes)?; random_bytes - }, + } _ => { return Err(RvError::ErrPkiKeyTypeInvalid); } @@ -108,14 +101,14 @@ impl KeyBundle { signer.set_rsa_padding(Padding::PKCS1)?; signer.update(data)?; return Ok(signer.sign_to_vec()?); - }, + } "ec" => { let ec_key = EcKey::private_key_from_pem(&self.key)?; let pkey = PKey::from_ec_key(ec_key)?; let mut signer = Signer::new(MessageDigest::sha256(), &pkey)?; signer.update(data)?; return Ok(signer.sign_to_vec()?); - }, + } _ => { return Err(RvError::ErrPkiKeyOperationInvalid); } @@ -131,14 +124,14 @@ impl KeyBundle { verifier.set_rsa_padding(Padding::PKCS1)?; verifier.update(data)?; return Ok(verifier.verify(signature).unwrap_or(false)); - }, + } "ec" => { let ec_key = EcKey::private_key_from_pem(&self.key)?; let pkey = PKey::from_ec_key(ec_key)?; let mut verifier = Verifier::new(MessageDigest::sha256(), &pkey)?; verifier.update(data)?; return Ok(verifier.verify(signature).unwrap_or(false)); - }, + } _ => { return Err(RvError::ErrPkiKeyOperationInvalid); } @@ -157,11 +150,11 @@ impl KeyBundle { } }; let mut tag = vec![0u8; 16]; - let mut ciphertext = encrypt_aead(cipher, &self.key, Some(&self.iv), aad.unwrap_or("".as_bytes()), data, &mut tag)?; + let mut ciphertext = + encrypt_aead(cipher, &self.key, Some(&self.iv), aad.unwrap_or("".as_bytes()), data, &mut tag)?; ciphertext.extend_from_slice(&tag); Ok(ciphertext) - - }, + } "aes-cbc" => { let cipher = match self.bits { 128 => Cipher::aes_128_cbc(), @@ -173,7 +166,7 @@ impl KeyBundle { }; Ok(encrypt(cipher, &self.key, Some(&self.iv), data)?) - }, + } "aes-ecb" => { let cipher = match self.bits { 128 => Cipher::aes_128_ecb(), @@ -185,7 +178,7 @@ impl KeyBundle { }; Ok(encrypt(cipher, &self.key, None, data)?) - }, + } _ => { return Err(RvError::ErrPkiKeyOperationInvalid); } @@ -205,8 +198,7 @@ impl KeyBundle { }; let (ciphertext, tag) = data.split_at(data.len() - 16); Ok(decrypt_aead(cipher, &self.key, Some(&self.iv), aad.unwrap_or("".as_bytes()), ciphertext, tag)?) - - }, + } "aes-cbc" => { let cipher = match self.bits { 128 => Cipher::aes_128_cbc(), @@ -218,7 +210,7 @@ impl KeyBundle { }; Ok(decrypt(cipher, &self.key, Some(&self.iv), data)?) - }, + } "aes-ecb" => { let cipher = match self.bits { 128 => Cipher::aes_128_ecb(), @@ -230,7 +222,7 @@ impl KeyBundle { }; Ok(decrypt(cipher, &self.key, None, data)?) - }, + } _ => { return Err(RvError::ErrPkiKeyOperationInvalid); } diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 70fbbb5..9527247 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -1,14 +1,11 @@ -use std::time::{SystemTime, Duration}; +use std::time::{Duration, SystemTime}; + use chrono::prelude::*; -use rand::{Rng, thread_rng}; -use openssl::{ - hash::{ - MessageDigest, - Hasher, - } -}; -use serde::{Serializer, Deserialize, Deserializer}; use humantime::{format_rfc3339, parse_rfc3339}; +use openssl::hash::{Hasher, MessageDigest}; +use rand::{thread_rng, Rng}; +use serde::{Deserialize, Deserializer, Serializer}; + use crate::errors::RvError; pub mod cert; @@ -20,11 +17,22 @@ pub fn generate_uuid() -> String { format!( "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", - buf[0], buf[1], buf[2], buf[3], - buf[4], buf[5], - buf[6], buf[7], - buf[8], buf[9], - buf[10], buf[11], buf[12], buf[13], buf[14], buf[15] + buf[0], + buf[1], + buf[2], + buf[3], + buf[4], + buf[5], + buf[6], + buf[7], + buf[8], + buf[9], + buf[10], + buf[11], + buf[12], + buf[13], + buf[14], + buf[15] ) } @@ -58,14 +66,16 @@ where } pub fn serialize_duration(duration: &Duration, serializer: S) -> Result - where S: serde::Serializer +where + S: serde::Serializer, { let timestamp = duration.as_secs(); serializer.serialize_i64(timestamp as i64) } pub fn deserialize_duration<'de, D>(deserializer: D) -> Result - where D: serde::Deserializer<'de> +where + D: serde::Deserializer<'de>, { let timestamp = i64::deserialize(deserializer)?; Ok(Duration::from_secs(timestamp as u64)) diff --git a/tests/test_default_logical.rs b/tests/test_default_logical.rs index f00e5bc..538a48d 100644 --- a/tests/test_default_logical.rs +++ b/tests/test_default_logical.rs @@ -1,14 +1,17 @@ -use std::env; -use std::fs; -use std::default::Default; -use std::sync::{Arc, RwLock}; -use std::collections::HashMap; -use serde_json::{json, Value, Map}; +use std::{ + collections::HashMap, + default::Default, + env, fs, + sync::{Arc, RwLock}, +}; + use go_defer::defer; -use rusty_vault::storage::physical; -use rusty_vault::storage::barrier_aes_gcm; -use rusty_vault::core::{Core, SealConfig}; -use rusty_vault::logical::{Operation, Request}; +use rusty_vault::{ + core::{Core, SealConfig}, + logical::{Operation, Request}, + storage::{barrier_aes_gcm, physical}, +}; +use serde_json::{json, Map, Value}; fn test_read_api(core: &Core, token: &str, path: &str, is_ok: bool, expect: Option>) { let mut req = Request::new(path); @@ -66,7 +69,10 @@ fn test_default_secret(core: Arc>, token: &str) { let kv_data = json!({ "foo": "bar", "zip": "zap", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); test_write_api(&core, token, "secret/goo", true, Some(kv_data.clone())); // get secret @@ -84,13 +90,19 @@ fn test_kv_logical_backend(core: Arc>, token: &str) { // mount kv backend to path: kv/ let mount_data = json!({ "type": "kv", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); test_write_api(&core, token, "sys/mounts/kv/", true, Some(mount_data)); let kv_data = json!({ "foo": "bar", "zip": "zap", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); test_read_api(&core, token, "secret/foo", true, None); @@ -108,7 +120,10 @@ fn test_kv_logical_backend(core: Arc>, token: &str) { // update secret let kv_data = json!({ "foo": "bar", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); test_write_api(&core, token, "kv/secret", true, Some(kv_data.clone())); // check whether the secret is updated successfully @@ -117,7 +132,10 @@ fn test_kv_logical_backend(core: Arc>, token: &str) { // add secret let kv_data = json!({ "foo": "bar", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); test_write_api(&core, token, "kv/foo", true, Some(kv_data.clone())); // list secret @@ -134,7 +152,10 @@ fn test_kv_logical_backend(core: Arc>, token: &str) { let remount_data = json!({ "from": "kv", "to": "vk", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); test_write_api(&core, token, "sys/remount", true, Some(remount_data)); // get secret from new mount path @@ -165,7 +186,10 @@ fn test_sys_mount_feature(core: Arc>, token: &str) { // test api: "mounts/kv" with valid type let mount_data = json!({ "type": "kv", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); test_write_api(&core, token, "sys/mounts/kv/", true, Some(mount_data.clone())); // test api: "mounts/kv" with path conflict @@ -174,42 +198,60 @@ fn test_sys_mount_feature(core: Arc>, token: &str) { // test api: "mounts/nope" with valid type let mount_data = json!({ "type": "nope", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); test_write_api(&core, token, "sys/mounts/nope/", false, Some(mount_data)); // test api: "remount" with valid path let remount_data = json!({ "from": "kv", "to": "vk", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); test_write_api(&core, token, "sys/remount", true, Some(remount_data)); // test api: "remount" with invalid path let remount_data = json!({ "from": "unknow", "to": "vvk", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); test_write_api(&core, token, "sys/remount", false, Some(remount_data)); // test api: "remount" with dis-path conflict let remount_data = json!({ "from": "vk", "to": "secret", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); test_write_api(&core, token, "sys/remount", false, Some(remount_data)); // test api: "remount" with protect path let remount_data = json!({ "from": "sys", "to": "foo", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); test_write_api(&core, token, "sys/remount", false, Some(remount_data)); // test api: "remount" with default src-path let remount_data = json!({ "from": "secret", "to": "bar", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); test_write_api(&core, token, "sys/remount", true, Some(remount_data)); } @@ -231,7 +273,10 @@ fn test_sys_raw_api_feature(core: Arc>, token: &str) { // test raw write let test_data = json!({ "value": "my test data", - }).as_object().unwrap().clone(); + }) + .as_object() + .unwrap() + .clone(); test_write_api(&core, token, "sys/raw/test", true, Some(test_data.clone())); // test raw read again @@ -275,20 +320,13 @@ fn test_default_logical() { let barrier = barrier_aes_gcm::AESGCMBarrier::new(Arc::clone(&backend)); - let c = Arc::new(RwLock::new(Core { - physical: backend, - barrier: Arc::new(barrier), - ..Default::default() - })); + let c = Arc::new(RwLock::new(Core { physical: backend, barrier: Arc::new(barrier), ..Default::default() })); { let mut core = c.write().unwrap(); assert!(core.config(Arc::clone(&c), None).is_ok()); - let seal_config = SealConfig { - secret_shares: 10, - secret_threshold: 5, - }; + let seal_config = SealConfig { secret_shares: 10, secret_threshold: 5 }; let result = core.init(&seal_config); assert!(result.is_ok());