Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for custom secret types. #44

Merged
merged 1 commit into from
Feb 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ FEATURES

- Update tested Vault releases to include latest versions.
- Migrate CI testing to Github actions.
- Add support for custoim secret types (https://github.com/ChrisMacNaughton/vault-rs/pull/44).

The new secret types allow for managing arbitrary data in Vault
as long as the data is serializable!

BREAKING CHANGES

Expand Down
105 changes: 90 additions & 15 deletions src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,16 @@ pub enum HttpVerb {
LIST,
}

#[derive(Debug, Serialize)]
struct SecretContainer<T: Serialize> {
data: T,
}

#[derive(Debug, Deserialize, Serialize)]
struct DefaultSecretType<T: AsRef<str>> {
value: T,
}

/// endpoint response variants
#[derive(Debug)]
pub enum EndpointResponse<D> {
Expand Down Expand Up @@ -968,23 +978,49 @@ where
/// assert!(res.is_ok());
/// ```
pub fn set_secret<S1: Into<String>, S2: AsRef<str>>(&self, key: S1, value: S2) -> Result<()> {
let _ = self.post::<_, String>(
&format!("/v1/secret/data/{}", key.into())[..],
Some(
&format!(
"{{\"data\": {{\"value\": \"{}\"}}}}",
self.escape(value.as_ref())
)[..],
),
let secret = DefaultSecretType {
value: value.as_ref(),
};
self.set_custom_secret(key, &secret)
}

/// Saves a secret
///
/// ```
/// # extern crate hashicorp_vault as vault;
/// # use vault::Client;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize, Serialize)]
/// struct MyThing {
/// awesome: String,
/// thing: String,
/// }
/// let host = "http://127.0.0.1:8200";
/// let token = "test12345";
/// let client = Client::new(host, token).unwrap();
/// let secret = MyThing {
/// awesome: "I really am cool".into(),
/// thing: "this is also in the secret".into(),
/// };
/// let res = client.set_custom_secret("hello_set", &secret);
/// assert!(res.is_ok());
/// ```
pub fn set_custom_secret<S1, S2>(&self, secret_name: S1, secret: &S2) -> Result<()>
where
S1: Into<String>,
S2: Serialize,
{
let secret = SecretContainer { data: secret };
let json = serde_json::to_string(&secret)?;
let _ = self.put::<_, String>(
&format!("/v1/secret/data/{}", secret_name.into())[..],
Some(&json),
None,
)?;
Ok(())
}

fn escape<S: AsRef<str>>(&self, input: S) -> String {
input.as_ref().replace("\n", "\\n").replace("\"", "\\\"")
}

///
/// List secrets at specified path
///
Expand Down Expand Up @@ -1036,10 +1072,49 @@ where
/// assert_eq!(res.unwrap(), "world");
/// ```
pub fn get_secret<S: AsRef<str>>(&self, key: S) -> Result<String> {
let res = self.get::<_, String>(&format!("/v1/secret/data/{}", key.as_ref())[..], None)?;
let decoded: VaultResponse<SecretDataWrapper<SecretData>> = parse_vault_response(res)?;
let secret: DefaultSecretType<String> = self.get_custom_secret(key)?;
Ok(secret.value)
}

///
/// Fetches a saved secret
///
/// ```
/// # extern crate hashicorp_vault as vault;
/// # use vault::Client;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Deserialize, Serialize)]
/// struct MyThing {
/// awesome: String,
/// thing: String,
/// }
/// let host = "http://127.0.0.1:8200";
/// let token = "test12345";
/// let client = Client::new(host, token).unwrap();
/// let secret = MyThing {
/// awesome: "I really am cool".into(),
/// thing: "this is also in the secret".into(),
/// };
/// let res1 = client.set_custom_secret("custom_secret", &secret);
/// assert!(res1.is_ok());
/// let res2: Result<MyThing, _> = client.get_custom_secret("custom_secret");
/// assert!(res2.is_ok());
/// let thing = res2.unwrap();
/// assert_eq!(thing.awesome, "I really am cool");
/// assert_eq!(thing.thing, "this is also in the secret");
/// ```
pub fn get_custom_secret<S: AsRef<str>, S2: DeserializeOwned + std::fmt::Debug>(
&self,
secret_name: S,
) -> Result<S2> {
let res = self.get::<_, String>(
&format!("/v1/secret/data/{}", secret_name.as_ref())[..],
None,
)?;
let decoded: VaultResponse<SecretDataWrapper<S2>> = parse_vault_response(res)?;
match decoded.data {
Some(data) => Ok(data.data.value),
Some(data) => Ok(data.data),
_ => Err(Error::Vault(format!(
"No secret found in response: `{:#?}`",
decoded
Expand Down
20 changes: 20 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ mod tests {
use crate::client::{self, EndpointResponse};
use crate::Error;
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};

/// vault host for testing
const HOST: &str = "http://127.0.0.1:8200";
Expand Down Expand Up @@ -392,4 +393,23 @@ mod tests {
_ => panic!("expected empty response, received: {:?}", res),
}
}

#[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
struct CustomSecretType {
name: String,
}

#[test]
fn it_can_set_and_get_a_custom_secret_type() {
let input = CustomSecretType {
name: "test".into(),
};

let client = Client::new(HOST, TOKEN).unwrap();

let res = client.set_custom_secret("custom_type", &input);
assert!(res.is_ok());
let res: CustomSecretType = client.get_custom_secret("custom_type").unwrap();
assert_eq!(res, input);
}
}