kraken_async_rs/secrets/
secrets_provider.rsuse dotenvy::dotenv;
use secrecy::Secret;
use std::env;
use std::fmt::Debug;
#[derive(Debug, Clone)]
pub struct Secrets {
pub key: Secret<String>,
pub secret: Secret<String>,
}
pub trait SecretsProvider: Send + Sync + Debug {
fn get_secrets(&mut self) -> Secrets;
}
#[derive(Debug, Clone)]
pub struct EnvSecretsProvider<'a> {
key_name: &'a str,
secret_name: &'a str,
secrets: Option<Secrets>,
}
impl<'a> EnvSecretsProvider<'a> {
pub fn new(key_name: &'a str, secret_name: &'a str) -> EnvSecretsProvider<'a> {
EnvSecretsProvider {
key_name,
secret_name,
secrets: None,
}
}
}
impl<'a> SecretsProvider for EnvSecretsProvider<'a> {
fn get_secrets(&mut self) -> Secrets {
if self.secrets.is_none() {
self.set_secrets();
}
self.secrets.clone().unwrap()
}
}
impl<'a> EnvSecretsProvider<'a> {
fn set_secrets(&mut self) {
dotenv().ok();
let key = Secret::new(match env::var(self.key_name) {
Ok(secret) => secret,
_ => panic!("Error retrieving Kraken key from env"),
});
let secret = Secret::new(match env::var(self.secret_name) {
Ok(secret) => secret,
_ => panic!("Error retrieving Kraken secret from env"),
});
self.secrets = Some(Secrets { key, secret });
}
}
#[derive(Debug, Clone)]
pub struct StaticSecretsProvider<'a> {
key: &'a str,
secret: &'a str,
}
impl<'a> StaticSecretsProvider<'a> {
pub fn new(key: &'a str, secret: &'a str) -> StaticSecretsProvider<'a> {
StaticSecretsProvider { key, secret }
}
}
impl<'a> SecretsProvider for StaticSecretsProvider<'a> {
fn get_secrets(&mut self) -> Secrets {
Secrets {
key: Secret::new(self.key.to_string()),
secret: Secret::new(self.secret.to_string()),
}
}
}
#[cfg(test)]
mod tests {
use crate::secrets::secrets_provider::{EnvSecretsProvider, SecretsProvider};
use secrecy::ExposeSecret;
#[test]
fn test_env_secrets_provider() {
let key_name = "TEST_KEY";
let secret_name = "TEST_SECRET";
let key = "api-key";
let secret = "api-secret";
std::env::set_var(key_name, key);
std::env::set_var(secret_name, secret);
let mut secrets_provider = EnvSecretsProvider::new(key_name, secret_name);
let secrets = secrets_provider.get_secrets();
assert_eq!(key, secrets.key.expose_secret());
assert_eq!(secret, secrets.secret.expose_secret());
}
}