### Install cargo-nextest Source: https://github.com/michaelklishin/vault-client-rs/blob/main/CONTRIBUTING.md Installs the `cargo-nextest` tool, which is required for running tests efficiently. ```bash cargo install cargo-nextest ``` -------------------------------- ### Start Vault Development Server with Docker Source: https://github.com/michaelklishin/vault-client-rs/blob/main/CONTRIBUTING.md Launches a local Vault development server using Docker. It configures root token, listen address, and port mapping. ```bash docker run --rm --cap-add=IPC_LOCK \ -e 'VAULT_DEV_ROOT_TOKEN_ID=myroot' \ -e 'VAULT_DEV_LISTEN_ADDRESS=0.0.0.0:8200' \ -p 8200:8200 \ --name dev-vault \ hashicorp/vault ``` -------------------------------- ### Build Vault Client from Environment Variables Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/01-vault-client.md Create a VaultClient builder pre-populated with configuration from environment variables. This simplifies setup by automatically reading settings like VAULT_ADDR, VAULT_TOKEN, and TLS options. ```rust let client = VaultClient::builder() .from_env() .build()?; ``` -------------------------------- ### Start Vault Development Server with Docker (Nu Shell) Source: https://github.com/michaelklishin/vault-client-rs/blob/main/CONTRIBUTING.md Launches a local Vault development server using Docker within the Nu shell environment. Configures root token, listen address, and port mapping. ```nu (docker run --rm --cap-add=IPC_LOCK -e VAULT_DEV_ROOT_TOKEN_ID=myroot -e VAULT_DEV_LISTEN_ADDRESS=0.0.0.0:8200 -p 8200:8200 --name dev-vault hashicorp/vault) ``` -------------------------------- ### VaultClient::from_env Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/01-vault-client.md Creates a VaultClient by reading configuration from environment variables. This method simplifies setup by automatically detecting Vault address, token, and other settings. ```APIDOC ## VaultClient::from_env ### Description Create a client from environment variables. Reads the following in order (token resolution: `VAULT_TOKEN` → `~/.vault-token` → `None`): - `VAULT_ADDR` (required) - `VAULT_TOKEN` (optional; falls back to `~/.vault-token` if not set) - `VAULT_NAMESPACE` (optional) - `VAULT_SKIP_VERIFY` (TLS verification, defaults to false) - `VAULT_CACERT` (path to CA certificate) - `VAULT_CLIENT_CERT` and `VAULT_CLIENT_KEY` (for mutual TLS) - `VAULT_CLIENT_TIMEOUT` (request timeout in seconds) - `VAULT_MAX_RETRIES` (max retry count) - `VAULT_WRAP_TTL` (default response wrap TTL) - `VAULT_CLI_MODE` (short-lived mode; sets retries=0, disables sealed retry) ### Method `VaultClient::from_env() -> Result` ### Response #### Success Response - **VaultClient** - The constructed VaultClient instance. #### Error Response - **VaultError** - If client construction fails due to missing environment variables or invalid configuration. ### Request Example ```rust let client = VaultClient::from_env()?; ``` ``` -------------------------------- ### Rust VaultClient with AuthMethod Usage Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/03-authentication.md Example of building a VaultClient with a pre-built authentication method like AppRoleLogin. The client will automatically re-authenticate if the token expires. ```rust use vault_client_rs::{VaultClient, AppRoleLogin}; use secrecy::SecretString; let login = AppRoleLogin { role_id: "my-role-id".into(), secret_id: SecretString::from("secret-id"), }; let client = VaultClient::builder() .address("https://vault.example.com:8200") .auth_method(login) .build()?; // Client will automatically re-authenticate if token expires ``` -------------------------------- ### Install with Cargo Features Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/00-overview.md Add vault-client-rs to your Cargo.toml with specific features like 'blocking' or 'auto-renew'. ```toml [dependencies] vault-client-rs = { version = "0.9", features = ["blocking", "auto-renew"] } ``` -------------------------------- ### Start Token Renewal Daemon Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/07-token-renewal.md Starts a background daemon that automatically renews the client token. The daemon will attempt to renew the token at approximately 2/3 of its remaining Time To Live (TTL) and will fall back to re-authentication if renewal fails. The daemon stops when its handle is dropped. ```APIDOC ## `VaultClient::start_token_renewal()` ### Description Starts the token renewal daemon. ### Returns `RenewalDaemon` – Drop this handle to stop the daemon. ### Example ```rust use vault_client_rs::VaultClient; let client = VaultClient::from_env()?; // Start renewal daemon let _daemon = client.start_token_renewal(); // Token is automatically renewed in the background // Daemon stops when dropped ``` ``` -------------------------------- ### Combine Token and Lease Renewal with AppRole Auth Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/07-token-renewal.md This snippet shows how to initialize the Vault client with AppRole authentication, start the token renewal daemon, retrieve database credentials, and set up a watcher for lease events. It also includes basic handling for lease renewal and expiration events. ```rust use vault_client_rs::{VaultClient, AppRoleLogin, LeaseEvent}; use secrecy::SecretString; use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { // Setup: token renewal + AppRole auth let login = AppRoleLogin { role_id: "my-role-id".into(), secret_id: SecretString::from("secret-id"), }; let client = VaultClient::builder() .address("https://vault.example.com:8200") .auth_method(login) .build()?; // Start token renewal daemon let _token_daemon = client.start_token_renewal(); // Get database credentials let db = client.database("database"); let creds = db.get_credentials("my-role").await?; // Watch the credential lease let mut lease_watcher = client.watch_lease_events( "database/creds/my-role/abc123", Duration::from_secs(3600) ); // Handle lease events in background tokio::spawn(async move { while let Some(event) = lease_watcher.recv().await { match event { LeaseEvent::Renewed { ttl, .. } => { println!("Credentials renewed: {:?}", ttl); } LeaseEvent::Expired { .. } => { eprintln!("Credentials expired!"); break; } _ => {} } } }); // Use credentials println!("Username: {}", creds.username.expose_secret()); // Background daemons keep everything renewed tokio::time::sleep(Duration::from_secs(3600)).await; Ok(()) } ``` -------------------------------- ### Get Database Dynamic Credentials Source: https://github.com/michaelklishin/vault-client-rs/blob/main/README.md Obtain dynamic credentials for a specified database role. The credentials include a username and password, which should be handled securely. ```rust let db = client.database("database"); // Get dynamic credentials for a role let creds = db.get_credentials("my-role").await?; println!("username: {}", creds.username.expose_secret()); ``` -------------------------------- ### Manage Vault Mounts Source: https://github.com/michaelklishin/vault-client-rs/blob/main/README.md Lists existing mounts, and mounts new backends with specified type and options. For example, mounting a KV version 2 engine. ```rust // Mounts let mounts = sys.list_mounts().await?; sys.mount("my-kv", &MountParams { mount_type: "kv".into(), options: Some([("version".into(), "2".into())].into()), ..Default::default() }).await?; ``` -------------------------------- ### Start Token Renewal Daemon Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/07-token-renewal.md Initiates a background daemon to automatically renew the client token. The daemon stops when its handle is dropped. ```rust use vault_client_rs::VaultClient; let client = VaultClient::from_env()?; // Start renewal daemon let _daemon = client.start_token_renewal(); // Token is automatically renewed in the background // Daemon stops when dropped ``` -------------------------------- ### Integrate Custom Reqwest HTTP Client Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/08-configuration-and-advanced.md Provide a pre-configured reqwest::Client for advanced HTTP setups like custom DNS or proxies. The client's timeout setting is still applied from timeout(). ```rust use reqwest::Client; let http_client = Client::builder() .proxy(reqwest::Proxy::https("https://proxy.example.com:8080")?) .build()?; let vault_client = VaultClient::builder() .address("https://vault.example.com:8200") .token_str("hvs.EXAMPLE") .with_reqwest_client(http_client) .build()?; ``` -------------------------------- ### Get Database Dynamic Credentials Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/02-secret-engines.md Retrieves dynamic database credentials for a specified role. Ensure the Vault client is initialized and authenticated before calling this method. The username and password should be handled securely, for example, by using `expose_secret()` only when necessary. ```rust let db = client.database("database"); let creds = db.get_credentials("my-db-role").await?; println!("Connect as: {}", creds.username.expose_secret()); ``` -------------------------------- ### Create Client View with Namespace Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/01-vault-client.md Obtain a client view for operations within a specific namespace. This is a cheap clone and operations on the returned client will use the specified namespace. ```rust let ns_client = client.with_namespace("my-team"); let kv = ns_client.kv2("secret"); ``` -------------------------------- ### VaultClient::new Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/01-vault-client.md Creates a VaultClient with a specified address and authentication token. This is a direct and minimal way to initialize the client. ```APIDOC ## VaultClient::new ### Description Create a client with minimal configuration. ### Method `VaultClient::new(address: &str, token: &str) -> Result` ### Parameters #### Path Parameters - **address** (`&str`) - Required - Vault HTTP address (e.g., `"https://vault.example.com:8200"`) - **token** (`&str`) - Required - Authentication token ### Response #### Success Response - **VaultClient** - The constructed VaultClient instance. #### Error Response - **VaultError** - If client construction fails. ### Request Example ```rust use vault_client_rs::VaultClient; let client = VaultClient::new("https://vault.example.com:8200", "hvs.EXAMPLE")?; ``` ``` -------------------------------- ### CLI Tool Using Blocking Vault Client Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/06-blocking-client.md Demonstrates initializing the blocking client from environment variables and using it to retrieve database credentials and application configuration. Ensure VAULT_ADDR and VAULT_TOKEN environment variables are set. ```rust use vault_client_rs::blocking::BlockingVaultClient; use std::collections::HashMap; use secrecy::SecretString; fn main() -> Result<(), Box> { // Initialize from environment (VAULT_ADDR, VAULT_TOKEN, etc.) let client = BlockingVaultClient::from_env()?; // Get database credentials let db = client.database("database"); let creds = db.get_credentials("my-role")?; // Use credentials (e.g., connect to DB) println!("Username: {}", creds.username.expose_secret()); println!("Password: {}", creds.password.expose_secret()); // Read application config let kv = client.kv2("secret"); let config: HashMap = kv.read_data("myapp/config")?; println!("Config: {:?}", config); Ok(()) } ``` -------------------------------- ### Get Static Database Credentials Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/02-secret-engines.md Retrieves static database credentials that are pre-configured and managed by Vault for a given role. ```APIDOC ## Get Static Database Credentials ### Description Get static credentials managed by Vault. ### Method `get_static_credentials(role: &str) -> Result` ### Parameters #### Path Parameters - **role** (string) - Required - Role name ``` -------------------------------- ### Userpass Login with Vault Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/03-authentication.md Authenticate to Vault using a username and password. Ensure you have the necessary Vault client setup. ```rust use secrecy::SecretString; let auth = client.auth().userpass() .login("alice", &SecretString::from("password123")) .await?; println!("Token expires in {} seconds", auth.lease_duration); ``` -------------------------------- ### Initialize Vault Client from Environment Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/00-overview.md Use this method to initialize the Vault client by reading configuration from environment variables. ```rust use vault_client_rs::VaultClient; let client = VaultClient::from_env()?; ``` -------------------------------- ### Configure Vault Client with AppRole Authentication Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/01-vault-client.md Demonstrates building a Vault client and configuring it to use AppRole for authentication. Ensure the necessary imports are included. ```rust use vault_client_rs::{VaultClient, AppRoleLogin}; use secrecy::SecretString; let login = AppRoleLogin { role_id: "my-role-id".into(), secret_id: SecretString::from("secret-id"), }; let client = VaultClient::builder() .address("https://vault.example.com:8200") .auth_method(login) .build()?; ``` -------------------------------- ### TotpGenerateResponse Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/05-types-and-errors.md Represents the response when a TOTP code is generated. It includes the generated code, and the start and end times for its validity period. ```APIDOC ## TotpGenerateResponse Generated TOTP code. ### Fields - `code` (String) – 6-digit (or configured) code - `valid_from` (u64) – Unix timestamp (start of validity period) - `valid_until` (u64) – Unix timestamp (end of validity period) ``` -------------------------------- ### Get Database Credentials Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/02-secret-engines.md Retrieves dynamic database credentials for a specified role. These credentials are automatically generated and managed by Vault. ```APIDOC ## Get Database Credentials ### Description Get dynamic database credentials for a role. ### Method `get_credentials(role: &str) -> Result` ### Parameters #### Path Parameters - **role** (string) - Required - Role name ### Response #### Success Response (200) - **username** (SecretString) - The generated username. - **password** (SecretString) - The generated password. ### Request Example ```rust let db = client.database("database"); let creds = db.get_credentials("my-db-role").await?; println!("Connect as: {}", creds.username.expose_secret()); ``` ``` -------------------------------- ### Get Database Credentials Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/06-blocking-client.md Retrieves dynamic database credentials using the database secrets engine. The username is exposed securely. ```rust let db = client.database("database"); let creds = db.get_credentials("my-role")?; println!("Connect as: {}", creds.username.expose_secret()); ``` -------------------------------- ### InitResponse Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/05-types-and-errors.md The response structure for Vault initialization. ```APIDOC ## InitResponse Initialization response. ### Fields - `keys` (Vec) – Unseal keys - `keys_base64` (Vec) – Base64-encoded keys - `root_token` (SecretString) – Initial root token - `root_token_pgp_fingerprint` (Option) ``` -------------------------------- ### AppRole Login and Token Handling Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/05-types-and-errors.md Shows how to perform an AppRole login and access the client token and policies from the authentication response. The client token should be handled securely using `SecretString`. ```rust let auth = client.auth().approle() .login("role-id", &secret_id) .await?; println!("Token: {}", auth.client_token.expose_secret()); println!("Policies: {:?}", auth.policies); ``` -------------------------------- ### Run Property-Based Tests Source: https://github.com/michaelklishin/vault-client-rs/blob/main/CONTRIBUTING.md Executes property-based tests using `cargo-nextest`. Filters tests to include only those whose names start with 'prop_'. ```bash cargo nextest run --all-features -E 'test(~prop_)' ``` -------------------------------- ### BlockingVaultClient Construction Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/06-blocking-client.md Demonstrates how to create a new blocking Vault client instance, either by providing the address and token directly or by using environment variables. ```APIDOC ## BlockingVaultClient::new ### Description Create a blocking client with minimal configuration. ### Signature `BlockingVaultClient::new(address: &str, token: &str) -> Result` ### Parameters - **address** (`&str`): Vault HTTP address - **token** (`&str`): Authentication token ### Returns `Result` ### Example ```rust use vault_client_rs::blocking::BlockingVaultClient; let client = BlockingVaultClient::new( "https://vault.example.com:8200", "hvs.EXAMPLE" )?; ``` ## BlockingVaultClient::from_env ### Description Create a blocking client from environment variables. Reads the same `VAULT_*` variables as the async client. ### Signature `BlockingVaultClient::from_env() -> Result` ### Returns `Result` ``` -------------------------------- ### Create VaultClient using ClientBuilder Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/01-vault-client.md Use `VaultClient::builder` for detailed configuration. This allows setting the address, token, timeout, retry counts, and other options programmatically before building the client. ```rust use vault_client_rs::VaultClient; use std::time::Duration; let client = VaultClient::builder() .address("https://vault.example.com:8200") .token_str("hvs.EXAMPLE") .timeout(Duration::from_secs(30)) .max_retries(3) .build()?; ``` -------------------------------- ### Generate Root / Emergency Unseal Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/04-system-operations.md Operations related to generating and managing root tokens, including starting the process, submitting key shards, and cancellation. ```APIDOC ## start_generate_root() ### Description Start a root token generation operation. ### Method Rust Function ### Signature `start_generate_root() -> Result` ``` ```APIDOC ## submit_generate_root_key(key: &str) ### Description Submit a key shard for root token generation. ### Method Rust Function ### Signature `submit_generate_root_key(key: &str) -> Result` ``` ```APIDOC ## cancel_generate_root() ### Description Cancel root token generation. ### Method Rust Function ### Signature `cancel_generate_root() -> Result<(), VaultError>` ``` -------------------------------- ### Create Client View with Namespace Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/06-blocking-client.md Obtain a new client instance that operates within a specific Vault namespace. This is useful for multi-namespaced Vault deployments. ```rust use vault_client_rs::blocking::BlockingVaultClient; // Assuming 'client' is an initialized BlockingVaultClient instance // let client = BlockingVaultClient::new(...)?; let ns_client = client.with_namespace("my-namespace"); ``` -------------------------------- ### Configure Mutual TLS with Client Certificate Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/08-configuration-and-advanced.md Set up client certificate and key for mutual TLS authentication. The certificate and key are zeroed on drop. ```rust use std::fs; let cert = fs::read("client.crt")?; let key = fs::read("client.key")?; let client = VaultClient::builder() .address("https://vault.example.com:8200") .client_cert_pem(cert, key) .build()?; ``` -------------------------------- ### Mock KV2 Operations for Testing Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/00-overview.md Implement the Kv2Operations trait to mock KV v2 interactions for testing purposes. This example shows a partial implementation. ```rust use vault_client_rs::{Kv2Operations, VaultError}; use vault_client_rs::types::kv::KvReadResponse; use std::collections::HashMap; struct MockKv2; impl Kv2Operations for MockKv2 { async fn read_data( &self, _path: &str, ) -> Result { // Return test data todo!() } // ... implement other methods } ``` -------------------------------- ### Create VaultClient from Environment Variables Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/01-vault-client.md Use `VaultClient::from_env` to automatically configure the client using environment variables like `VAULT_ADDR` and `VAULT_TOKEN`. It supports fallback mechanisms for token resolution and various other configuration options. ```rust let client = VaultClient::from_env()?; ``` -------------------------------- ### Initialize Vault Client with Builder Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/00-overview.md Initialize the Vault client using a builder pattern, allowing explicit configuration of address, token, and timeout. ```rust use std::time::Duration; let client = VaultClient::builder() .address("https://vault.example.com:8200") .token_str("hvs.EXAMPLE") .timeout(Duration::from_secs(30)) .build()?; ``` -------------------------------- ### Enable Circuit Breaker with Basic Configuration Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/08-configuration-and-advanced.md Demonstrates how to enable the circuit breaker pattern when building a Vault client, specifying a custom failure threshold and timeout. ```rust use vault_client_rs::{VaultClient, CircuitBreakerConfig}; use std::time::Duration; let client = VaultClient::builder() .address("https://vault.example.com:8200") .token_str("hvs.EXAMPLE") .circuit_breaker(CircuitBreakerConfig { failure_threshold: 3, timeout: Duration::from_secs(60), ..Default::default() }) .build()?; ``` -------------------------------- ### Get Vault Health Status Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/04-system-operations.md Retrieves the overall health status of the Vault server. Use this to check if Vault is initialized, sealed, or in a standby state. Requires an authenticated client. ```rust let health = client.sys().health().await?; println!("Sealed: {}", health.sealed); println!("Version: {}", health.version); ``` -------------------------------- ### Configuration and Settings Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/04-system-operations.md Operations for reading configuration data and generating audit hashes. ```APIDOC ## read_raw_config_data() ### Description Read Vault configuration (debugging). ### Method Rust Function ### Signature `read_raw_config_data() -> Result` ``` ```APIDOC ## audit_hash(path: &str, input: &str) ### Description Generate HMAC-SHA256 hash for audit log testing. ### Method Rust Function ### Signature `audit_hash(path: &str, input: &str) -> Result` ``` -------------------------------- ### Manual Token Renewal for Blocking Client Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/07-token-renewal.md Implement manual token renewal for a blocking Vault client. This example spawns a thread to periodically renew the token using a Tokio runtime. ```rust use vault_client_rs::blocking::BlockingVaultClient; let client = BlockingVaultClient::from_env()?; // Manual renewal in a separate thread std::thread::spawn(move || { let runtime = tokio::runtime::Runtime::new().unwrap(); runtime.block_on(async { loop { std::thread::sleep(std::time::Duration::from_secs(1800)); // 30 min if let Err(e) = client.auth().token().renew_self(Some("1h")).await { eprintln!("Renewal failed: {}", e); } } }); }); ``` -------------------------------- ### BlockingVaultClient Builder Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/06-blocking-client.md Illustrates how to use the builder pattern to configure and create a blocking Vault client. ```APIDOC ## BlockingVaultClient::builder ### Description Create a builder for configuration. Returns `BlockingClientBuilder` with the same methods as `ClientBuilder`, except: - No `auth_method()` (auto-reauthentication not applicable) - No `on_token_changed()` (no background task) ### Signature `BlockingVaultClient::builder() -> BlockingClientBuilder` ``` -------------------------------- ### Implement Kv2Operations Trait for Mocking Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/06-blocking-client.md Implement the Kv2Operations trait for a mock struct to enable testing without a live Vault instance. This example shows a basic structure for mocking the `read_data` method. ```rust use vault_client_rs::Kv2Operations; use std::collections::HashMap; struct MockKv2; impl Kv2Operations for MockKv2 { async fn read_data( &self, _path: &str, ) -> Result { // Return test data todo!() } // ... implement other methods } ``` -------------------------------- ### Create Vault Client with ClientBuilder Source: https://github.com/michaelklishin/vault-client-rs/blob/main/README.md Configure and build a VaultClient instance using the builder pattern, allowing customization of address, token, and retry settings. ```rust use vault_client_rs::VaultClient; let client = VaultClient::builder() .address("https://vault.example.com:8200") .token_str("hvs.EXAMPLE") .max_retries(3) .build()?; ``` -------------------------------- ### Custom Circuit Breaker Configuration with Exponential Backoff Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/08-configuration-and-advanced.md Shows how to create a custom circuit breaker configuration with specific thresholds, timeouts, and an exponential backoff multiplier for timeout durations. ```rust use vault_client_rs::CircuitBreakerConfig; use std::time::Duration; let config = CircuitBreakerConfig { failure_threshold: 5, success_threshold: 2, timeout: Duration::from_secs(10), timeout_multiplier: 2.0, // Double timeout on each trip max_timeout: Duration::from_secs(600), // Cap at 10 minutes }; let client = VaultClient::builder() .address("https://vault.example.com:8200") .token_str("hvs.EXAMPLE") .circuit_breaker(config) .build()?; ``` -------------------------------- ### Configuration Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/03-authentication.md Manage LDAP configuration settings. ```APIDOC ## Read Configuration ### Description Read LDAP configuration. ### Method Signature `read_config() -> Result` ### Returns - `Result` --- ## Write Configuration ### Description Update LDAP configuration. ### Method Signature `write_config(cfg: &LdapConfigRequest) -> Result<(), VaultError>` ### Parameters #### Path Parameters - `cfg` (`LdapConfigRequest`) - Required - The LDAP configuration request object. ``` -------------------------------- ### Create Vault Client in CLI Mode Source: https://github.com/michaelklishin/vault-client-rs/blob/main/README.md Set up a VaultClient for short-lived CLI sessions by disabling retries and Vault sealing retry loops using `cli_mode(true)`. ```rust use vault_client_rs::VaultClient; let client = VaultClient::builder() .address("https://vault.example.com:8200") .token_str("hvs.EXAMPLE") .cli_mode(true) .build()?; ``` -------------------------------- ### Wrap and Unwrap Data with Vault Client Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/08-configuration-and-advanced.md Demonstrates wrapping arbitrary data using `sys.wrap` and then unwrapping it at the destination using `sys.unwrap`. Ensure the wrap token is securely transmitted. ```rust let wrap_info = client.sys().wrap( "secret/data/myapp", &serde_json::json!({"password": "secret"}), "5m" ).await?; println!("Wrap token: {}", wrap_info.token.expose_secret()); #[derive(serde::Deserialize)] struct Secret { password: String, } let secret: Secret = client.sys() .unwrap(wrap_info.token.expose_secret()) .await?; ``` -------------------------------- ### Create Client View with Wrap TTL Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/06-blocking-client.md Generate a client view configured with a specific wrap TTL (Time To Live) for operations that support it. The TTL is specified as a string. ```rust use vault_client_rs::blocking::BlockingVaultClient; // Assuming 'client' is an initialized BlockingVaultClient instance // let client = BlockingVaultClient::new(...)?; let wrapped_client = client.with_wrap_ttl("1h"); ``` -------------------------------- ### Web Service with Auto-Renewal Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/07-token-renewal.md Demonstrates setting up a web service that uses the Vault client with automatic token renewal. The client handles token renewal before expiry and re-authentication if renewal fails, simplifying credential management for handlers. ```rust use vault_client_rs::{VaultClient, AppRoleLogin}; use secrecy::SecretString; use std::sync::Arc; #[tokio::main] async fn main() -> Result<(), Box> { // Setup Vault with auto-renewal let login = AppRoleLogin { role_id: std::env::var("VAULT_ROLE_ID")?, secret_id: SecretString::from(std::env::var("VAULT_ROLE_SECRET_ID")?), }; let client = Arc::new( VaultClient::builder() .address("https://vault.example.com:8200") .auth_method(login) .build()? ); // Start token renewal let _token_daemon = client.start_token_renewal(); // Spawn web server let handler = warp::path!("api" / "secret") .map(move || { let client = Arc::clone(&client); async move { match client.kv2("secret").read_data::("myapp/config").await { Ok(config) => warp::reply::json(&config), Err(e) => { eprintln!("Read failed: {}", e); warp::reply::json(&serde_json::json!({"error": e.to_string()})) } } } }); warp::serve(handler) .run(([127, 0, 0, 1], 3030)) .await; Ok(()) } ``` -------------------------------- ### build Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/01-vault-client.md Constructs and returns a `VaultClient` instance. The build process may fail if essential configuration like the address is missing, the address is invalid, or if there are issues with the HTTP client or TLS certificate parsing. ```APIDOC ## build ### Description Build the `VaultClient`. ### Method `build(self) -> Result` ### Parameters None ### Response #### Success Response (VaultClient) Returns a `VaultClient` instance. #### Error Response Fails if: - `address` is not set - Address is not a valid URL - HTTP client configuration fails - TLS certificate parsing fails ### Request Example ```rust let client = VaultClient::builder() .address("https://vault.example.com:8200") .build()?; ``` ### Response Example None ``` -------------------------------- ### Create Blocking Client with New Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/06-blocking-client.md Instantiate a new blocking Vault client by providing the Vault server address and an authentication token. This method returns a Result, which will be Ok with the client or Err with a VaultError. ```rust use vault_client_rs::blocking::BlockingVaultClient; let client = BlockingVaultClient::new( "https://vault.example.com:8200", "hvs.EXAMPLE" )?; ``` -------------------------------- ### Kerberos Authentication Configuration Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/03-authentication.md Configure Kerberos authentication settings. ```APIDOC ## Kerberos Authentication Configuration ### Description Manages Kerberos authentication configuration. #### Read Configuration **`read_config() -> Result`** Read Kerberos configuration. #### Write Configuration **`write_config(cfg: &KerberosConfigRequest) -> Result<(), VaultError>`** Update configuration. **Parameters:** - **cfg** (`&KerberosConfigRequest`): The Kerberos configuration to write. ``` -------------------------------- ### ClientBuilder::from_env Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/01-vault-client.md Initializes the `ClientBuilder` with configuration values read from environment variables. It supports common Vault environment variables for address, token, namespace, and TLS settings. ```APIDOC ## ClientBuilder::from_env ### Description Create a pre-populated builder from environment variables. ### Method `ClientBuilder::from_env() -> Self` ### Parameters None ### Environment Variables Read: - `VAULT_ADDR` - `VAULT_TOKEN` - `VAULT_NAMESPACE` - `VAULT_SKIP_VERIFY` - `VAULT_CACERT` - `VAULT_CLIENT_CERT` - `VAULT_CLIENT_KEY` - `VAULT_CLIENT_TIMEOUT` - `VAULT_MAX_RETRIES` - `VAULT_WRAP_TTL` - `VAULT_CLI_MODE` ### Request Example ```rust let client = VaultClient::builder() .from_env() .build()?; ``` ### Response #### Success Response (Self) Returns `ClientBuilder` #### Response Example None ``` -------------------------------- ### Create Async Vault Client Source: https://github.com/michaelklishin/vault-client-rs/blob/main/README.md Instantiate a new VaultClient for asynchronous operations using the Vault server address and an authentication token. ```rust use vault_client_rs::VaultClient; let client = VaultClient::new("https://vault.example.com:8200", "hvs.EXAMPLE")?; ``` -------------------------------- ### PkiHandler - Configuration Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/02-secret-engines.md Provides methods for reading and writing PKI configuration. ```APIDOC ## PkiHandler - Configuration ### Description Methods for reading and writing PKI configuration. ### `read_config` #### Description Read PKI configuration. #### Returns - `Result` ### `write_config` #### Description Update PKI configuration. #### Parameters - **cfg** (`&PkiRevocationInfo`) - Required - PKI configuration to write. #### Returns - `Result<(), VaultError>` ``` -------------------------------- ### Token Creation Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/03-authentication.md Create a new token with specified properties. ```APIDOC ## Token Creation ### create(request: &TokenCreateRequest) Create a new token. **Parameters:** - `request` (&TokenCreateRequest) - Token configuration **TokenCreateRequest fields:** - `policies` (Option>) – List of policy names - `ttl` (Option) – TTL string (e.g., "4h") - `max_ttl` (Option) – Maximum TTL (cannot be renewed past this) - `display_name` (Option) – Token display name - `num_uses` (Option) – Limit token use count - `no_parent` (Option) – Make token an orphan - `no_default_policy` (Option) – Don't apply default policy - `renewable` (Option) – Allow renewal - `explicit_max_ttl` (Option) – Explicit max TTL **Returns:** `Result` – Auth response with token details ``` -------------------------------- ### Login Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/03-authentication.md Authenticate with LDAP credentials. ```APIDOC ## Login ### Description Authenticate with LDAP credentials. ### Method Signature `login(username: &str, password: &SecretString) -> Result` ### Parameters #### Path Parameters - `username` (str) - Required - LDAP username - `password` (`SecretString`) - Required - LDAP password ### Returns - `Result` ``` -------------------------------- ### Authenticate with Userpass Source: https://github.com/michaelklishin/vault-client-rs/blob/main/README.md Logs in using the Userpass authentication method. Requires a username and password. ```rust use secrecy::SecretString; use vault_client_rs::VaultClient; let client = VaultClient::builder() .address("https://vault.example.com:8200") .build()?; // Userpass let auth = client.auth().userpass().login("alice", &SecretString::from("password")).await?; ``` -------------------------------- ### Authenticate with AppRole Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/06-blocking-client.md Shows how to authenticate with Vault using the AppRole authentication method. The client token is then set on the client instance. ```rust use vault_client_rs::blocking::BlockingVaultClient; use secrecy::SecretString; let client = BlockingVaultClient::builder() .address("https://vault.example.com:8200") .build()?; let auth = client.auth().approle() .login("my-role-id", &SecretString::from("secret-id"))?; client.set_token(auth.client_token); ``` -------------------------------- ### Authenticate with LDAP Source: https://github.com/michaelklishin/vault-client-rs/blob/main/README.md Logs in using the LDAP authentication method. Requires a username and password. ```rust // LDAP let auth = client.auth().ldap().login("alice", &SecretString::from("password")).await?; ``` -------------------------------- ### Database Configuration Management Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/02-secret-engines.md APIs for reading and writing database connection configurations. ```APIDOC ## Read Database Configuration ### Description Read database connection configuration. ### Method `read_config(name: &str) -> Result` ### Parameters #### Path Parameters - **name** (string) - Required - Configuration name ``` ```APIDOC ## Write Database Configuration ### Description Create or update database connection. ### Method `write_config(name: &str, cfg: &DatabaseConfigRequest) -> Result<(), VaultError>` ### Parameters #### Path Parameters - **name** (string) - Required - Configuration name #### Request Body - **cfg** (DatabaseConfigRequest) - Required - The database configuration request object. ``` -------------------------------- ### Enable Vault Auth Method Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/04-system-operations.md Enables a new authentication method at a specified path with given parameters. Ensure the path and parameters are correctly configured for the desired auth method. ```rust let params = AuthMountParams::default(); client.sys().enable_auth("userpass", ¶ms).await?; ``` -------------------------------- ### Run All Tests Source: https://github.com/michaelklishin/vault-client-rs/blob/main/CONTRIBUTING.md Executes all tests in the project, including unit, mock, and integration tests. Requires Vault to be running and configured. ```bash VAULT_ADDR=http://127.0.0.1:8200 VAULT_TOKEN=myroot \ cargo nextest run --all-features ``` -------------------------------- ### Vault Client Configuration for CLI Tools Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/08-configuration-and-advanced.md Sets up the Vault client in CLI mode, disabling retries to ensure immediate failure and quick feedback, which is suitable for command-line interfaces. ```rust let client = VaultClient::builder() .address("https://vault.example.com:8200") .token_str("hvs.EXAMPLE") .cli_mode(true) // No retries, fail fast .build()?; ``` -------------------------------- ### Enable CLI Mode for Fast Failures Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/08-configuration-and-advanced.md Configure the client for short-lived command-line tool invocations by disabling retries and sealed vault retry loops for immediate failure. ```rust let client = VaultClient::builder() .address("https://vault.example.com:8200") .token_str("hvs.EXAMPLE") .cli_mode(true) .build()?; ``` -------------------------------- ### Namespace and Wrap TTL Overrides Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/06-blocking-client.md Details methods for creating client views with specific namespace or wrap TTL configurations. ```APIDOC ## with_namespace ### Description Return a client view with a different namespace. ### Signature `with_namespace(&self, ns: &str) -> Self` ### Parameters - **ns** (`&str`): The target namespace ### Returns A new client instance configured for the specified namespace. ## with_wrap_ttl ### Description Return a client view with a different wrap TTL. ### Signature `with_wrap_ttl(&self, ttl: &str) -> Self` ### Parameters - **ttl** (`&str`): The desired wrap TTL value (e.g., "1h", "5m") ### Returns A new client instance configured with the specified wrap TTL. ``` -------------------------------- ### Using SecretString for Sensitive Data Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/05-types-and-errors.md Demonstrates how to create and expose a SecretString. The secret is automatically zeroed out when the variable goes out of scope. ```rust use secrecy::SecretString; let password = SecretString::from("secret123"); println!("{}", password.expose_secret()); // Explicit // Zeroed on drop ``` -------------------------------- ### Authenticate with GitHub Source: https://github.com/michaelklishin/vault-client-rs/blob/main/README.md Logs in using the GitHub authentication method. Requires a GitHub personal access token. ```rust // GitHub let auth = client.auth().github().login(&SecretString::from("ghp_TOKEN")).await?; ``` -------------------------------- ### Customizing reqwest Client for Connection Pooling Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/08-configuration-and-advanced.md Creates a custom reqwest HTTP client with specific connection pooling settings and HTTP/2 prioritization, then integrates it with the Vault client. ```rust use reqwest::Client; let http_client = Client::builder() .pool_max_idle_per_host(10) // Connections per host .http2_prior_knowledge() // Force HTTP/2 .build()?; let vault_client = VaultClient::builder() .address("https://vault.example.com:8200") .token_str("hvs.EXAMPLE") .with_reqwest_client(http_client) .build()?; ``` -------------------------------- ### Enable Debug Logging with Tracing Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/08-configuration-and-advanced.md Initializes the tracing subscriber to emit logs at the DEBUG level. This is useful for observing authentication attempts, token renewals, retries, and circuit breaker states. ```rust tracing_subscriber::fmt() .with_max_level(tracing::Level::DEBUG) .init(); ``` -------------------------------- ### Configure Vault Client with Circuit Breaker Source: https://github.com/michaelklishin/vault-client-rs/blob/main/README.md Initialize a VaultClient with a circuit breaker enabled for fault tolerance. This monitors failures and short-circuits requests after a threshold. ```rust use vault_client_rs::{VaultClient, CircuitBreakerConfig}; let client = VaultClient::builder() .address("https://vault.example.com:8200") .token_str("hvs.EXAMPLE") .circuit_breaker(CircuitBreakerConfig::default()) .build()?; ``` -------------------------------- ### Create New Token Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/03-authentication.md Create a new token with specified properties like policies, TTL, and display name. This requires the `TokenCreateRequest` struct and returns authentication information. ```rust use vault_client_rs::TokenCreateRequest; let child = client.auth().token().create(&TokenCreateRequest { policies: Some(vec!["read-secret".into()]), ttl: Some("4h".into()), display_name: Some("my-app".into()), ..Default::default() }).await?; println!("Token: {}", child.client_token.expose_secret()); ``` -------------------------------- ### Run All Tests (Nu Shell) Source: https://github.com/michaelklishin/vault-client-rs/blob/main/CONTRIBUTING.md Executes all tests in the project using `cargo-nextest` within the Nu shell, with Vault environment variables pre-configured. ```nu with-env { VAULT_ADDR: "http://127.0.0.1:8200", VAULT_TOKEN: myroot } { cargo nextest run --all-features } ``` -------------------------------- ### Configure Response Wrapping TTL Source: https://github.com/michaelklishin/vault-client-rs/blob/main/README.md Creates a client instance that will wrap the next response with a specified Time-To-Live (TTL). This is useful for transiently securing sensitive API responses. ```rust // Wrap the next response with a TTL let wrapping_client = client.with_wrap_ttl("5m"); ``` -------------------------------- ### Initialization Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/04-system-operations.md Initializes an uninitialized Vault. This operation must be called exactly once before any other operations. ```APIDOC ## Initialization ### Description Initialize an uninitialized Vault. Must be called exactly once before any other operations. ### Method ```rust init(params: &InitParams) ``` ### Parameters #### Request Body - **params** (`&InitParams`) - Required - Initialization parameters - **secret_shares** (`Option`) - Number of unseal keys to split (default: 5) - **secret_threshold** (`Option`) - Number needed to unseal (default: 3) - **pgp_keys** (`Option>`) - PGP public keys for encrypting keys (optional) ### Returns `Result` - **keys** (`Vec`) - Unseal keys (PGP-encrypted if pgp_keys provided) - **keys_base64** (`Vec`) - Base64-encoded unseal keys - **root_token** (`SecretString`) - Initial root token - **root_token_pgp_fingerprint** (`Option`) ### Request Example ```rust use vault_client_rs::InitParams; let response = client.sys().init(&InitParams { secret_shares: Some(5), secret_threshold: Some(3), pgp_keys: None, ..Default::default() }).await?; println!("Root token: {}", response.root_token.expose_secret()); ``` ``` -------------------------------- ### Read Lease Information in Rust Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/04-system-operations.md Use this to look up details about an existing lease. Requires the lease ID as a string. ```rust let info = client.sys().read_lease("database/creds/my-role/abc123").await?; println!("TTL: {} seconds", info.ttl); ``` -------------------------------- ### Configure Custom CA Certificate Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/08-configuration-and-advanced.md Provide a custom CA certificate in PEM format for TLS validation. ```rust use std::fs; let ca_cert = fs::read("ca.pem")?; let client = VaultClient::builder() .address("https://vault.example.com:8200") .token_str("hvs.EXAMPLE") .ca_cert_pem(ca_cert) .build()?; ``` -------------------------------- ### Add vault-client-rs to Dependencies Source: https://github.com/michaelklishin/vault-client-rs/blob/main/README.md Include the vault-client-rs crate in your Cargo.toml file. Specify features like 'blocking' or 'auto-renew' as needed. ```toml vault-client-rs = "0.7" ``` ```toml vault-client-rs = { version = "0.7", features = ["blocking"] } ``` ```toml vault-client-rs = { version = "0.7", features = ["auto-renew"] } ``` -------------------------------- ### Configure Vault Client with Retry Logic Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/08-configuration-and-advanced.md Sets up a Vault client with custom retry attempts and initial delay. The client will automatically retry requests based on specific error conditions with exponential backoff. ```rust let client = VaultClient::builder() .address("https://vault.example.com:8200") .token_str("hvs.EXAMPLE") .max_retries(5) .initial_retry_delay(Duration::from_secs(1)) .build()?; // If request fails with 503, will retry with delays: // 1s, 2s, 4s, 8s, 16s (capped at 30s max) let result = client.read::("path").await?; ``` -------------------------------- ### Create TOTP Key Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/02-secret-engines.md Use this snippet to create a new TOTP key. You can specify whether to generate a new key or import an existing one, along with issuer and account name details. ```rust use vault_client_rs::TotpKeyRequest; let totp = client.totp("totp"); totp.create_key("my-app", &TotpKeyRequest { generate: true, issuer: Some("MyApp".into()), account_name: Some("alice@example.com".into()), ..Default::default() }).await?; ``` -------------------------------- ### Backup and Restore Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/04-system-operations.md Functions for performing database backups and restoring Vault from a backup. ```APIDOC ## database_backup() ### Description Create a full database backup. ### Method Rust Function ### Signature `database_backup() -> Result, VaultError>` ``` ```APIDOC ## raft_storage_restore(backup: &[u8]) ### Description Restore from a backup. ### Method Rust Function ### Signature `raft_storage_restore(backup: &[u8]) -> Result<(), VaultError>` ``` -------------------------------- ### Enable Debug Tracing for Vault Client Source: https://github.com/michaelklishin/vault-client-rs/blob/main/_autodocs/07-token-renewal.md Integrate with the `tracing` crate to enable debug logs for the Vault client, which provides insights into daemon status and renewal operations. ```rust // Enable debug logs tracing_subscriber::fmt() .with_max_level(tracing::Level::DEBUG) .init(); let client = VaultClient::from_env()?; let _daemon = client.start_token_renewal(); // Logs: "Token renewal daemon started", "Renewing token", etc. ``` -------------------------------- ### Run Integration Tests Source: https://github.com/michaelklishin/vault-client-rs/blob/main/CONTRIBUTING.md Executes integration tests that require a running Vault instance. Sets necessary environment variables for Vault address and token. ```bash VAULT_ADDR=http://127.0.0.1:8200 VAULT_TOKEN=myroot \ cargo nextest run --all-features -E 'binary(integration)' ```