|
| 1 | +use std::{borrow::Cow, fs, io, path::Path}; |
| 2 | + |
| 3 | +use env_capture::{Env, IgnoreAsciiCase}; |
| 4 | +use oauth10a::{credentials::Credentials, url::Url}; |
| 5 | + |
| 6 | +use crate::{ |
| 7 | + DEFAULT_SSH_GATEWAY, PartialCredentials, |
| 8 | + clever_tools::{CleverTools, CleverToolsConfig, CleverToolsConfigError}, |
| 9 | + default_api_host, default_auth_bridge_host, |
| 10 | +}; |
| 11 | + |
| 12 | +// PARTIAL OAUTH ERROR ///////////////////////////////////////////////////////// |
| 13 | + |
| 14 | +#[derive(Debug, thiserror::Error)] |
| 15 | +pub enum PartialOAuthError { |
| 16 | + #[error("missing token")] |
| 17 | + Token, |
| 18 | + #[error("missing secret")] |
| 19 | + Secret, |
| 20 | + #[error("missing consumer token")] |
| 21 | + ConsumerKey, |
| 22 | + #[error("missing consumer secret")] |
| 23 | + ConsumerSecret, |
| 24 | +} |
| 25 | + |
| 26 | +// CLEVER ENV ////////////////////////////////////////////////////////////////// |
| 27 | + |
| 28 | +#[derive(Debug, thiserror::Error)] |
| 29 | +pub enum CleverEnvError { |
| 30 | + #[error("failed to capture environnement, {0}")] |
| 31 | + Capture(#[from] env_capture::Error), |
| 32 | + #[error(transparent)] |
| 33 | + CleverToolsConfigFile(#[from] CleverToolsConfigError), |
| 34 | + #[error("partial OAuth credentials: {0}")] |
| 35 | + PartialOAuth(#[from] PartialOAuthError), |
| 36 | + #[error("failed to create configuration directory")] |
| 37 | + ConfigDir(io::Error), |
| 38 | +} |
| 39 | + |
| 40 | +/// Snapshot of the clever environment variables, hydrated with the OAuth |
| 41 | +/// configuration from the main configuration file of the `clever-tools`, if any. |
| 42 | +#[derive(Debug, serde::Deserialize)] |
| 43 | +pub struct CleverEnv { |
| 44 | + #[serde(rename = "API_HOST")] |
| 45 | + pub(crate) api_host: Option<Url>, |
| 46 | + #[serde(rename = "AUTH_BRIDGE_API")] |
| 47 | + pub(crate) auth_bridge_host: Option<Url>, |
| 48 | + #[serde(rename = "SSH_GATEWAY")] |
| 49 | + pub(crate) ssh_gateway: Option<Box<str>>, |
| 50 | + #[serde(rename = "", flatten, default)] |
| 51 | + pub(crate) credentials: Option<PartialCredentials>, |
| 52 | + #[serde(skip)] |
| 53 | + pub(crate) config_dir: Option<Box<Path>>, |
| 54 | +} |
| 55 | + |
| 56 | +impl CleverEnv { |
| 57 | + pub fn from_env() -> Result<Self, CleverEnvError> { |
| 58 | + let env = Env::<IgnoreAsciiCase>::from_env(); |
| 59 | + |
| 60 | + let mut env = env.with_prefix("CLEVER_").parse::<Self>()?; |
| 61 | + |
| 62 | + match &mut env.credentials { |
| 63 | + credentials @ None => { |
| 64 | + trace!("credentials not found in current process environment"); |
| 65 | + |
| 66 | + let config_dir = CleverToolsConfig::default_config_dir()?; |
| 67 | + |
| 68 | + let config_path = CleverToolsConfig::config_path_in(&config_dir); |
| 69 | + |
| 70 | + if config_path.exists() { |
| 71 | + env.config_dir.replace(config_dir.into()); |
| 72 | + |
| 73 | + let CleverToolsConfig { |
| 74 | + oauth_token, |
| 75 | + oauth_secret, |
| 76 | + } = CleverToolsConfig::from_path(&config_path)?; |
| 77 | + |
| 78 | + *credentials = Some(Credentials::OAuth1 { |
| 79 | + token: oauth_token, |
| 80 | + secret: oauth_secret, |
| 81 | + consumer_key: None, |
| 82 | + consumer_secret: None, |
| 83 | + }); |
| 84 | + |
| 85 | + trace!("using credentials from `clever-tools` configuration file"); |
| 86 | + } |
| 87 | + } |
| 88 | + Some(Credentials::OAuth1 { |
| 89 | + consumer_key: Some(_), |
| 90 | + consumer_secret: None, |
| 91 | + .. |
| 92 | + }) => { |
| 93 | + return Err(CleverEnvError::PartialOAuth( |
| 94 | + PartialOAuthError::ConsumerSecret, |
| 95 | + )); |
| 96 | + } |
| 97 | + Some(Credentials::OAuth1 { |
| 98 | + consumer_key: None, |
| 99 | + consumer_secret: Some(_), |
| 100 | + .. |
| 101 | + }) => return Err(CleverEnvError::PartialOAuth(PartialOAuthError::ConsumerKey)), |
| 102 | + Some(_) => trace!("using credentials from environment"), |
| 103 | + } |
| 104 | + |
| 105 | + Ok(env) |
| 106 | + } |
| 107 | + |
| 108 | + pub fn env_api_host(&self) -> Option<&Url> { |
| 109 | + self.api_host.as_ref() |
| 110 | + } |
| 111 | + |
| 112 | + pub fn api_host(&self) -> &Url { |
| 113 | + match &self.api_host { |
| 114 | + None => default_api_host(), |
| 115 | + Some(v) => v, |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + pub fn env_auth_bridge_host(&self) -> Option<&Url> { |
| 120 | + self.auth_bridge_host.as_ref() |
| 121 | + } |
| 122 | + |
| 123 | + pub fn auth_bridge_host(&self) -> &Url { |
| 124 | + match &self.auth_bridge_host { |
| 125 | + None => default_auth_bridge_host(), |
| 126 | + Some(v) => v, |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + pub fn env_ssh_gateway(&self) -> Option<&str> { |
| 131 | + self.ssh_gateway.as_deref() |
| 132 | + } |
| 133 | + |
| 134 | + pub const fn ssh_gateway(&self) -> &str { |
| 135 | + match &self.ssh_gateway { |
| 136 | + None => DEFAULT_SSH_GATEWAY, |
| 137 | + Some(v) => v, |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + pub const fn env_oauth_consumer_key(&self) -> Option<&str> { |
| 142 | + match self.credentials { |
| 143 | + Some(Credentials::OAuth1 { |
| 144 | + consumer_key: Some(ref v), |
| 145 | + .. |
| 146 | + }) => Some(v), |
| 147 | + _ => None, |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + pub const fn oauth_consumer_key(&self) -> &str { |
| 152 | + match self.env_oauth_consumer_key() { |
| 153 | + Some(x) => x, |
| 154 | + None => CleverTools::CONSUMER_KEY, |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + pub const fn env_oauth_consumer_secret(&self) -> Option<&str> { |
| 159 | + match self.credentials { |
| 160 | + Some(Credentials::OAuth1 { |
| 161 | + consumer_secret: Some(ref v), |
| 162 | + .. |
| 163 | + }) => Some(v), |
| 164 | + _ => None, |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + pub const fn oauth_consumer_secret(&self) -> &str { |
| 169 | + match self.env_oauth_consumer_secret() { |
| 170 | + Some(v) => v, |
| 171 | + None => CleverTools::CONSUMER_SECRET, |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + /// Returns the path to the directory where configuration files of clever apps are stored. |
| 176 | + pub fn config_dir(&self) -> Result<Cow<'_, Path>, CleverEnvError> { |
| 177 | + let path = match self.config_dir { |
| 178 | + Some(ref config_dir) => Cow::Borrowed(&**config_dir), |
| 179 | + None => Cow::Owned(CleverToolsConfig::default_config_dir()?), |
| 180 | + }; |
| 181 | + |
| 182 | + fs::create_dir_all(&*path).map_err(CleverEnvError::ConfigDir)?; |
| 183 | + |
| 184 | + Ok(path) |
| 185 | + } |
| 186 | + |
| 187 | + pub fn credentials(&self) -> Option<&PartialCredentials> { |
| 188 | + self.credentials.as_ref() |
| 189 | + } |
| 190 | +} |
| 191 | + |
| 192 | +#[cfg(test)] |
| 193 | +mod tests { |
| 194 | + use env_capture::set_tmp_var; |
| 195 | + use oauth10a::credentials::Credentials; |
| 196 | + |
| 197 | + use crate::clever_env::CleverEnv; |
| 198 | + |
| 199 | + #[test] |
| 200 | + fn test_env() { |
| 201 | + let _ = unsafe { set_tmp_var("RUST_LOG", "trace") }; |
| 202 | + |
| 203 | + tracing_subscriber::fmt::fmt() |
| 204 | + .with_level(true) |
| 205 | + .with_line_number(true) |
| 206 | + .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) |
| 207 | + .init(); |
| 208 | + |
| 209 | + let _ = unsafe { set_tmp_var("CLEVER_TOKEN", "my_token") }; |
| 210 | + let _ = unsafe { set_tmp_var("CLEVER_SECRET", "my_secret") }; |
| 211 | + |
| 212 | + if let Credentials::OAuth1 { |
| 213 | + token, |
| 214 | + secret, |
| 215 | + consumer_key, |
| 216 | + consumer_secret, |
| 217 | + } = CleverEnv::from_env().unwrap().credentials().unwrap() |
| 218 | + { |
| 219 | + dbg!(token, secret, consumer_key, consumer_secret); |
| 220 | + } |
| 221 | + } |
| 222 | +} |
0 commit comments