Skip to main content

hc_vault/database/
get_credentials.rs

1use crate::Auth;
2use crate::Client;
3use crate::Error;
4
5use serde::Deserialize;
6use std::time::Duration;
7
8#[derive(Deserialize)]
9struct DBCreds {
10    username: String,
11    password: String,
12}
13
14#[allow(dead_code)]
15#[derive(Deserialize)]
16struct DBCredsResponse {
17    lease_id: String,
18    lease_duration: u64,
19    renewable: bool,
20    data: DBCreds,
21}
22
23/// This struct holds Database Credentials returned by vault
24#[derive(Debug)]
25pub struct DatabaseCreds {
26    /// The username to use when logging in to the database
27    pub username: String,
28    /// The password to use when logging in to the database
29    pub password: String,
30    /// The duration for which these credentials are valid for
31    pub duration: Duration,
32}
33
34impl PartialEq for DatabaseCreds {
35    fn eq(&self, other: &Self) -> bool {
36        self.username == other.username
37            && self.password == other.password
38            && self.duration == other.duration
39    }
40}
41
42/// This function is used to actually load the Database credentials from vault
43pub async fn get_credentials(
44    client: &Client<impl Auth>,
45    name: &str,
46) -> Result<DatabaseCreds, Error> {
47    let path = format!("database/creds/{}", name);
48    let response = match client
49        .vault_request::<String>(reqwest::Method::GET, &path, None)
50        .await
51    {
52        Err(e) => return Err(e),
53        Ok(res) => res,
54    };
55
56    let resp_body = match response.json::<DBCredsResponse>().await {
57        Err(e) => return Err(Error::from(e)),
58        Ok(body) => body,
59    };
60
61    Ok(DatabaseCreds {
62        username: resp_body.data.username,
63        password: resp_body.data.password,
64        duration: Duration::from_secs(resp_body.lease_duration),
65    })
66}