1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
use std::collections::BTreeMap;
use std::io::{BufRead, Write};
use std::path::Path;
use std::process::Output;
use teller_providers::config::PathMap;
use teller_providers::Provider;
// use csv::WriterBuilder;
use teller_providers::{config::KV, registry::Registry, Result as ProviderResult};
use crate::redact::Redactor;
use crate::template;
use crate::{
config::{Config, Match},
exec, export, scan, Error, Result,
};
pub struct Teller {
registry: Registry,
config: Config,
}
impl Teller {
/// Build from config
///
/// # Errors
///
/// This function will return an error if loading fails
pub async fn from_config(config: &Config) -> teller_providers::Result<Self> {
let registry = Registry::new(&config.providers).await?;
Ok(Self {
registry,
config: config.clone(),
})
}
/// Build from YAML
///
/// # Errors
///
/// This function will return an error if loading fails
pub async fn from_yaml(file: &Path) -> Result<Self> {
let config = Config::from_path(file)?;
Self::from_config(&config).await.map_err(Error::Provider)
}
/// Collects kvs from all provider maps in the current configuration
///
/// # Errors
///
/// This function will return an error if IO fails
pub async fn collect(&self) -> ProviderResult<Vec<KV>> {
let mut res = Vec::new();
for (name, providercfg) in &self.config.providers {
if let Some(provider) = self.registry.get(name) {
for pm in &providercfg.maps {
let kvs = provider.get(pm).await?;
res.push(kvs);
}
}
}
Ok(res.into_iter().flatten().collect::<Vec<_>>())
}
/// Put a list of KVs into a list of providers, on a specified path
///
/// # Errors
///
/// This function will return an error if put fails
pub async fn put(&self, kvs: &[KV], map_id: &str, providers: &[String]) -> Result<()> {
// a target provider has to have the specified path id
for provider_name in providers {
let (provider, pm) = self.get_pathmap_on_provider(map_id, provider_name)?;
provider.put(pm, kvs).await?;
}
Ok(())
}
/// Delete a list of keys or a complete path for every provider in the list
///
/// # Errors
///
/// This function will return an error if delete fails
pub async fn delete(&self, keys: &[String], map_id: &str, providers: &[String]) -> Result<()> {
// a target provider has to have the specified path id
for provider_name in providers {
let (provider, pm) = self.get_pathmap_on_provider(map_id, provider_name)?;
// 1. if keys is empty, use the default pathmap
// 2. otherwise, create a new pathmap, with a subset of keys
if keys.is_empty() {
provider.del(pm).await?;
} else {
let mut subset_keys = BTreeMap::new();
for key in keys {
subset_keys.insert(key.clone(), key.clone());
}
let mut new_pm = pm.clone();
new_pm.keys = subset_keys;
provider.del(&new_pm).await?;
}
}
Ok(())
}
/// Get a provider and pathmap from configuration and registry
///
/// # Errors
///
/// This function will return an error if operation fails
#[allow(clippy::borrowed_box)]
pub fn get_pathmap_on_provider(
&self,
map_id: &str,
provider_name: &String,
) -> Result<(&Box<dyn Provider + Send + Sync>, &PathMap)> {
let pconf = self.config.providers.get(provider_name).ok_or_else(|| {
Error::Message(format!(
"cannot find provider '{provider_name}' path configuration"
))
})?;
let pm = pconf.maps.iter().find(|m| m.id == map_id).ok_or_else(|| {
Error::Message(format!(
"cannot find path id '{map_id}' in provider '{provider_name}'"
))
})?;
let provider = self.registry.get(provider_name).ok_or_else(|| {
Error::Message(format!("cannot get initialized provider '{provider_name}'"))
})?;
Ok((provider, pm))
}
/// Run an external command with provider based environment variables
///
/// # Errors
///
/// This function will return an error if command fails
pub async fn run<'a>(&self, cmd: &[&str], opts: &exec::Opts<'a>) -> Result<Output> {
let cmd = shell_words::join(cmd);
let kvs = self.collect().await?;
let res = exec::cmd(
cmd.as_str(),
&kvs.iter()
.map(|kv| (kv.key.clone(), kv.value.clone()))
.collect::<Vec<_>>()[..],
opts,
)?;
Ok(res)
}
/// Redact streams
///
/// # Errors
///
/// This function will return an error if Is or collecting keys fails
#[allow(clippy::future_not_send)]
pub async fn redact<R: BufRead, W: Write>(&self, reader: R, writer: W) -> Result<()> {
let kvs = self.collect().await?;
let redactor = Redactor::new();
redactor.redact(reader, writer, kvs.as_slice())?;
Ok(())
}
/// Populate a custom template with KVs
///
/// # Errors
///
/// This function will return an error if template rendering fails
pub async fn template(&self, template: &str) -> Result<String> {
let kvs = self.collect().await?;
let out = template::render(template, kvs)?; // consumes kvs
Ok(out)
}
/// Export KV data
///
/// # Errors
///
/// This function will return an error if export fails
pub async fn export<'a>(&self, format: &export::Format) -> Result<String> {
let kvs = self.collect().await?;
format.export(&kvs)
}
/// Scan a folder recursively for secrets or values
///
/// # Errors
///
/// This function will return an error if IO fails
pub fn scan(&self, root: &str, kvs: &[KV], opts: &scan::Opts) -> Result<Vec<Match>> {
scan::scan_root(root, kvs, opts)
}
/// Copy from provider to target provider.
/// Note: `replace` will first delete data at target, then copy.
///
/// # Errors
///
/// This function will return an error if copy fails
pub async fn copy(
&self,
from_provider: &str,
from_map_id: &str,
to_provider: &str,
to_map_id: &str,
replace: bool,
) -> Result<()> {
// XXX fix &str, &String params
let (from_provider, from_pm) =
self.get_pathmap_on_provider(from_map_id, &from_provider.to_string())?;
let data = from_provider.get(from_pm).await?;
let (to_provider, to_pm) =
self.get_pathmap_on_provider(to_map_id, &to_provider.to_string())?;
if replace {
to_provider.del(to_pm).await?;
}
to_provider.put(to_pm, &data).await?;
Ok(())
}
}