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
// Copyright (C) Microsoft Corporation. All rights reserved.
use crate::{
client::{
backend::Backend,
io::{create_dir_all, read_json, write_json},
},
Error, Result,
};
use home::home_dir;
use serde::{Deserialize, Serialize};
use std::{
fmt::{self, Display},
path::PathBuf,
};
use url::Url;
/// Value that is printed upon trying to show a debug version of a `Secret`
const REDACTED: &str = "[redacted secret]";
/// Default Freta Endpoint
const DEFAULT_ENDPOINT: &str = "https://freta.microsoft.com/";
#[derive(Serialize, Deserialize, Clone)]
/// Client Secret
///
/// This is an opaque type that makes it such that secrets are not accidentally
/// logged.
pub struct Secret(String);
impl Secret {
#[must_use]
/// Create a new `Secret`
pub fn new<S>(secret: S) -> Self
where
S: Into<String>,
{
Self(secret.into())
}
/// Unwrap the secret for use.
///
/// Requiring the use of `get_secret` requires being intentional about using
/// the secret.
pub(crate) fn get_secret(&self) -> &str {
self.0.as_ref()
}
}
impl fmt::Debug for Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{REDACTED}")
}
}
impl From<String> for Secret {
fn from(secret: String) -> Self {
Self::new(secret)
}
}
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
/// AAD App client id
pub struct ClientId(String);
impl ClientId {
#[must_use]
/// Create a new `ClientId`
pub const fn new(secret: String) -> Self {
Self(secret)
}
/// Returns the client id as a str
pub(crate) fn as_str(&self) -> &str {
self.0.as_ref()
}
}
#[derive(Serialize, Deserialize)]
/// Freta client Config
pub struct Config {
/// URL for the Freta API.
///
/// NOTE: For the public Freta service, this should always be `https://freta.microsoft.com`
pub api_url: Url,
/// AAD app registration client id
pub client_id: ClientId,
/// Tenant of the AAD app registration for the client
pub tenant_id: String,
/// Client Secrt for custom app registrations to connect to Freta
pub client_secret: Option<Secret>,
/// AAD App registration scope
pub scope: Option<String>,
/// Do not load or save cached login tokens
#[serde(default)]
pub ignore_login_cache: bool,
}
impl Default for Config {
fn default() -> Self {
Self {
#[allow(clippy::expect_used)]
api_url: Url::parse(DEFAULT_ENDPOINT).expect("default URL failed"),
client_id: ClientId::new("574efb07-14a8-4232-a200-89714a0324c9".into()),
tenant_id: "common".into(),
client_secret: None,
scope: Some("api://a934fc14-92d7-4127-aecd-bddab35935da/.default".into()),
ignore_login_cache: false,
}
}
}
impl fmt::Debug for Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("Config");
d.field("api url", &self.api_url.as_str());
d.field("client id", &self.client_id.as_str());
d.field("tenant id", &self.tenant_id.as_str());
d.field("ignore login cache", &self.ignore_login_cache);
if self.client_secret.is_some() {
d.field("client secret", &REDACTED);
}
if let Some(scope) = &self.scope {
d.field("scope", &scope);
}
d.finish()
}
}
/// Implement `Display` for the Config as `Debug` for now
impl Display for Config {
#[allow(clippy::use_debug)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl Config {
/// Get the path for the config file
fn get_path() -> Result<PathBuf> {
Ok(get_config_dir()?.join("cli.config"))
}
/// Load the user's current configuration from `~/.config/freta/cli.config`
/// or use the default if that does not exist
///
/// # Errors
/// This will return an error in the following cases:
/// 1. The path loading the configuration file cannot be determined
/// 2. Loading the configuration file fails
pub async fn load() -> Result<Self> {
let path = Self::get_path()?;
if path.exists() {
read_json(path).await
} else {
Ok(Self::default())
}
}
/// Create the config directory
///
/// # Errors
/// This will return an error in the following cases:
/// 1. The path loading the configuration file cannot be determined
/// 2. The directory for the configuration file cannot be created
async fn create_config_dir() -> Result<()> {
let path = get_config_dir()?;
create_dir_all(path).await
}
/// Save the user's configuration to `~/.config/freta/cli.config`
///
/// At the moment, client configuration only includes login configuration
/// information. Therefore, on any change, log the user out and log them
/// back in.
///
/// # Errors
/// This will return an error if the configuration file cannot be saved
pub async fn save(&self) -> Result<()> {
Self::create_config_dir().await?;
let path = Self::get_path()?;
write_json(path, self).await?;
Backend::logout().await?;
Ok(())
}
/// Get the JWT token scope for the current configuration
pub(crate) fn get_scope(&self) -> String {
self.scope.as_ref().map_or_else(
|| {
let mut scope = self.api_url.clone();
scope.set_path(".default");
scope.to_string().replacen("https://", "api://", 1)
},
std::clone::Clone::clone,
)
}
}
/// return expaneded version of `$HOME/.config/freta/`
///
/// # Errors
/// This will return an error if the user's home directory cannot be determined
pub(crate) fn get_config_dir() -> Result<PathBuf> {
home_dir()
.ok_or(Error::MissingHome)
.map(|x| x.join(".config/freta/"))
}