use std::collections::BTreeMap;
use std::env;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;
use atomic_write_file::AtomicWriteFile;
use clap::ValueEnum;
use etcetera::base_strategy::{choose_native_strategy, BaseStrategy};
use serde::{Deserialize, Serialize};
use url::{Host, Url};
use zeroize::{Zeroize, Zeroizing};
use crate::credential_store::{CredentialReference, CredentialStore, OsCredentialStore};
use crate::error::CgdError;
pub const DEFAULT_API_BASE_URL: &str = "https://api.coragrid.com/";
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(15);
const CONFIG_FILE_NAME: &str = "config.toml";
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OutputFormat {
Table,
Json,
Jsonl,
Csv,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum ConfigSetKey {
ApiBaseUrl,
Workspace,
Output,
Timeout,
NoColor,
}
impl ConfigSetKey {
pub const fn as_str(self) -> &'static str {
match self {
Self::ApiBaseUrl => "api_base_url",
Self::Workspace => "workspace",
Self::Output => "output",
Self::Timeout => "timeout",
Self::NoColor => "no_color",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigProfiles {
pub current: String,
pub names: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CredentialReferenceRemoval {
pub removed: bool,
pub still_referenced: bool,
}
impl fmt::Display for OutputFormat {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::Table => "table",
Self::Json => "json",
Self::Jsonl => "jsonl",
Self::Csv => "csv",
})
}
}
impl FromStr for OutputFormat {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value.trim().to_ascii_lowercase().as_str() {
"table" => Ok(Self::Table),
"json" => Ok(Self::Json),
"jsonl" => Ok(Self::Jsonl),
"csv" => Ok(Self::Csv),
_ => Err("expected one of: table, json, jsonl, csv".to_owned()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CredentialKind {
ApiKey,
AccessToken,
}
impl fmt::Display for CredentialKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::ApiKey => "API key",
Self::AccessToken => "access token",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CredentialSource {
Environment,
OsCredentialStore,
}
impl fmt::Display for CredentialSource {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::Environment => "environment",
Self::OsCredentialStore => "OS credential store",
})
}
}
#[derive(Clone)]
pub struct Credential {
kind: CredentialKind,
source: CredentialSource,
value: Zeroizing<String>,
}
impl Credential {
pub(crate) fn new(
kind: CredentialKind,
source: CredentialSource,
mut value: String,
label: &str,
) -> Result<Self, CgdError> {
let trimmed = value.trim().to_owned();
value.zeroize();
if trimmed.is_empty() || trimmed.len() > 4096 || trimmed.chars().any(char::is_whitespace) {
return Err(CgdError::Configuration(format!(
"{label} is empty or malformed"
)));
}
Ok(Self {
kind,
source,
value: Zeroizing::new(trimmed),
})
}
pub fn bearer(&self) -> &str {
self.value.as_str()
}
pub const fn kind(&self) -> CredentialKind {
self.kind
}
pub const fn source(&self) -> CredentialSource {
self.source
}
pub fn source_description(&self) -> String {
format!("{} {}", self.source, self.kind)
}
}
impl fmt::Debug for Credential {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Credential")
.field("kind", &self.kind)
.field("source", &self.source)
.field("value", &"[REDACTED]")
.finish()
}
}
#[derive(Debug, Clone, Default)]
pub struct ConfigOverrides {
pub profile: Option<String>,
pub api_base_url: Option<String>,
pub output: Option<OutputFormat>,
pub timeout: Option<String>,
pub no_color: bool,
}
#[derive(Clone)]
pub struct EffectiveConfig {
pub profile: String,
pub api_base_url: Url,
pub output: OutputFormat,
pub timeout: Duration,
pub no_color: bool,
pub workspace: Option<String>,
pub credential_ref: Option<CredentialReference>,
pub credential: Option<Credential>,
pub config_path: PathBuf,
pub warnings: Vec<String>,
}
impl fmt::Debug for EffectiveConfig {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("EffectiveConfig")
.field("profile", &self.profile)
.field("api_base_url", &self.api_base_url)
.field("output", &self.output)
.field("timeout", &self.timeout)
.field("no_color", &self.no_color)
.field("workspace", &self.workspace)
.field("credential_ref", &self.credential_ref)
.field("credential", &self.credential)
.field("config_path", &self.config_path)
.field("warnings", &self.warnings)
.finish()
}
}
impl EffectiveConfig {
pub fn load(overrides: &ConfigOverrides) -> Result<Self, CgdError> {
Self::load_with_profile_policy(overrides, false)
}
pub fn load_for_profile_update(overrides: &ConfigOverrides) -> Result<Self, CgdError> {
Self::load_with_profile_policy(overrides, true)
}
pub fn load_for_credential_update(
overrides: &ConfigOverrides,
allow_missing_explicit_profile: bool,
) -> Result<Self, CgdError> {
let path = config_path()?;
let file = read_config(&path)?;
Self::resolve_with_profile_policy(
overrides,
file,
&ProcessEnvironment,
&IgnoredCredentialStore,
path,
allow_missing_explicit_profile,
)
}
fn load_with_profile_policy(
overrides: &ConfigOverrides,
allow_missing_explicit_profile: bool,
) -> Result<Self, CgdError> {
let path = config_path()?;
let file = read_config(&path)?;
Self::resolve_with_profile_policy(
overrides,
file,
&ProcessEnvironment,
&OsCredentialStore,
path,
allow_missing_explicit_profile,
)
}
#[cfg(test)]
fn resolve(
overrides: &ConfigOverrides,
file: ConfigFile,
environment: &dyn Environment,
credential_store: &dyn CredentialStore,
config_path: PathBuf,
) -> Result<Self, CgdError> {
Self::resolve_with_profile_policy(
overrides,
file,
environment,
credential_store,
config_path,
false,
)
}
fn resolve_with_profile_policy(
overrides: &ConfigOverrides,
file: ConfigFile,
environment: &dyn Environment,
credential_store: &dyn CredentialStore,
config_path: PathBuf,
allow_missing_explicit_profile: bool,
) -> Result<Self, CgdError> {
let env_profile = environment.get("CORAGRID_PROFILE");
let profile_name = overrides
.profile
.as_deref()
.or(env_profile.as_deref())
.or(file.current_profile.as_deref())
.unwrap_or("default")
.trim();
validate_profile_name(profile_name)?;
let profile = file.profiles.get(profile_name);
if profile.is_none()
&& (overrides.profile.is_some() || env_profile.is_some())
&& profile_name != "default"
&& !allow_missing_explicit_profile
{
return Err(CgdError::Configuration(format!(
"configuration profile {profile_name:?} does not exist"
)));
}
let env_api_url = environment.get("CORAGRID_API_BASE_URL");
let api_url_text = overrides
.api_base_url
.as_deref()
.or(env_api_url.as_deref())
.or(profile.and_then(|profile| profile.api_base_url.as_deref()))
.or(file.api_base_url.as_deref())
.unwrap_or(DEFAULT_API_BASE_URL);
let api_base_url = validate_api_base_url(api_url_text)?;
let env_output = environment
.get("CGD_OUTPUT")
.map(|value| <OutputFormat as FromStr>::from_str(&value))
.transpose()
.map_err(|message| CgdError::Configuration(format!("invalid CGD_OUTPUT: {message}")))?;
let output = overrides
.output
.or(env_output)
.or(profile.and_then(|profile| profile.default_output))
.or(file.default_output)
.unwrap_or(OutputFormat::Table);
let env_timeout = environment.get("CGD_TIMEOUT");
let timeout_text = overrides
.timeout
.as_deref()
.or(env_timeout.as_deref())
.or(profile.and_then(|profile| profile.timeout.as_deref()))
.or(file.timeout.as_deref());
let timeout = timeout_text
.map(parse_timeout)
.transpose()?
.unwrap_or(DEFAULT_TIMEOUT);
let env_no_color = environment
.get("CGD_NO_COLOR")
.map(|value| parse_bool("CGD_NO_COLOR", &value))
.transpose()?
.unwrap_or(false)
|| environment.get("NO_COLOR").is_some();
let no_color = overrides.no_color
|| env_no_color
|| profile
.and_then(|profile| profile.no_color)
.unwrap_or(false)
|| file.no_color.unwrap_or(false);
let workspace = environment
.get("CORAGRID_WORKSPACE")
.or_else(|| profile.and_then(|profile| profile.workspace.clone()))
.or(file.workspace);
let credential_ref = profile
.and_then(|profile| profile.credential_ref.as_deref())
.or(file.credential_ref.as_deref())
.map(CredentialReference::from_str)
.transpose()?;
let api_key = environment.get("CORAGRID_API_KEY");
let access_token = environment.get("CORAGRID_ACCESS_TOKEN");
let credential = match (api_key, access_token) {
(Some(_), Some(_)) => {
return Err(CgdError::Configuration(
"set only one of CORAGRID_API_KEY and CORAGRID_ACCESS_TOKEN".to_owned(),
));
}
(Some(value), None) => Some(Credential::new(
CredentialKind::ApiKey,
CredentialSource::Environment,
value,
"CORAGRID_API_KEY",
)?),
(None, Some(value)) => Some(Credential::new(
CredentialKind::AccessToken,
CredentialSource::Environment,
value,
"CORAGRID_ACCESS_TOKEN",
)?),
(None, None) => credential_ref
.as_ref()
.map(|reference| credential_store.get(reference))
.transpose()?
.flatten(),
};
let mut warnings = Vec::new();
if api_base_url.as_str() != DEFAULT_API_BASE_URL {
warnings.push(format!(
"using explicitly configured API endpoint {}",
display_origin(&api_base_url)
));
}
if workspace.is_some() {
warnings.push(
"workspace selection is recorded locally but is not sent by the company-only alpha API"
.to_owned(),
);
}
Ok(Self {
profile: profile_name.to_owned(),
api_base_url,
output,
timeout,
no_color,
workspace,
credential_ref,
credential,
config_path,
warnings,
})
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ConfigFile {
current_profile: Option<String>,
api_base_url: Option<String>,
default_output: Option<OutputFormat>,
timeout: Option<String>,
no_color: Option<bool>,
workspace: Option<String>,
credential_ref: Option<String>,
#[serde(default)]
profiles: BTreeMap<String, ProfileConfig>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ProfileConfig {
api_base_url: Option<String>,
workspace: Option<String>,
credential_ref: Option<String>,
default_output: Option<OutputFormat>,
timeout: Option<String>,
no_color: Option<bool>,
}
trait Environment {
fn get(&self, key: &str) -> Option<String>;
}
struct ProcessEnvironment;
impl Environment for ProcessEnvironment {
fn get(&self, key: &str) -> Option<String> {
env::var(key).ok()
}
}
fn config_path() -> Result<PathBuf, CgdError> {
let directories = choose_native_strategy().map_err(|error| {
CgdError::Configuration(format!(
"cannot determine the platform configuration directory: {error}"
))
})?;
Ok(
platform_config_directory(directories.config_dir(), directories.data_dir())
.join(CONFIG_FILE_NAME),
)
}
fn platform_config_directory(config_base: PathBuf, data_base: PathBuf) -> PathBuf {
#[cfg(target_os = "macos")]
{
let _ = config_base;
data_base.join("com.Coragrid.cgd")
}
#[cfg(target_os = "windows")]
{
let _ = data_base;
config_base.join("Coragrid").join("cgd").join("config")
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
let _ = data_base;
config_base.join("cgd")
}
}
fn read_config(path: &Path) -> Result<ConfigFile, CgdError> {
let text = match fs::read_to_string(path) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(ConfigFile::default());
}
Err(error) => {
return Err(CgdError::Configuration(format!(
"cannot read {}: {error}",
path.display()
)));
}
};
toml::from_str(&text).map_err(|error| {
CgdError::Configuration(format!("cannot parse {}: {error}", path.display()))
})
}
pub fn set_profile_value(
path: &Path,
profile_name: &str,
key: ConfigSetKey,
value: &str,
) -> Result<String, CgdError> {
validate_profile_name(profile_name)?;
let mut file = read_config(path)?;
let profile = file.profiles.entry(profile_name.to_owned()).or_default();
let normalized = match key {
ConfigSetKey::ApiBaseUrl => {
let normalized = validate_api_base_url(value)?.to_string();
profile.api_base_url = Some(normalized.clone());
normalized
}
ConfigSetKey::Workspace => {
let normalized = validate_workspace(value)?;
profile.workspace = Some(normalized.clone());
normalized
}
ConfigSetKey::Output => {
let output = <OutputFormat as FromStr>::from_str(value).map_err(|message| {
CgdError::Configuration(format!("invalid output value: {message}"))
})?;
profile.default_output = Some(output);
output.to_string()
}
ConfigSetKey::Timeout => {
let timeout = parse_timeout(value)?;
let normalized = humantime::format_duration(timeout).to_string();
profile.timeout = Some(normalized.clone());
normalized
}
ConfigSetKey::NoColor => {
let no_color = parse_bool("no_color", value)?;
profile.no_color = Some(no_color);
no_color.to_string()
}
};
write_config(path, &file)?;
Ok(normalized)
}
pub fn list_profiles(path: &Path) -> Result<ConfigProfiles, CgdError> {
let file = read_config(path)?;
let current = file
.current_profile
.clone()
.unwrap_or_else(|| "default".to_owned());
let mut names = file.profiles.keys().cloned().collect::<Vec<_>>();
if !names.iter().any(|name| name == "default") {
names.push("default".to_owned());
}
names.sort();
Ok(ConfigProfiles { current, names })
}
pub fn use_profile(path: &Path, profile_name: &str) -> Result<(), CgdError> {
validate_profile_name(profile_name)?;
let mut file = read_config(path)?;
if profile_name != "default" && !file.profiles.contains_key(profile_name) {
return Err(CgdError::Configuration(format!(
"configuration profile {profile_name:?} does not exist; create it with --profile {profile_name} config set"
)));
}
file.current_profile = Some(profile_name.to_owned());
write_config(path, &file)
}
pub fn set_profile_credential_reference(
path: &Path,
profile_name: &str,
reference: &CredentialReference,
) -> Result<(), CgdError> {
validate_profile_name(profile_name)?;
let mut file = read_config(path)?;
file.profiles
.entry(profile_name.to_owned())
.or_default()
.credential_ref = Some(reference.to_string());
write_config(path, &file)
}
pub fn clear_effective_credential_reference(
path: &Path,
profile_name: &str,
reference: &CredentialReference,
) -> Result<CredentialReferenceRemoval, CgdError> {
validate_profile_name(profile_name)?;
let mut file = read_config(path)?;
let expected = reference.to_string();
let mut removed = false;
if let Some(profile) = file.profiles.get_mut(profile_name)
&& profile.credential_ref.as_deref() == Some(expected.as_str())
{
profile.credential_ref = None;
removed = true;
} else if file.credential_ref.as_deref() == Some(expected.as_str()) {
file.credential_ref = None;
removed = true;
}
if removed {
write_config(path, &file)?;
}
let still_referenced = file.credential_ref.as_deref() == Some(expected.as_str())
|| file
.profiles
.values()
.any(|profile| profile.credential_ref.as_deref() == Some(expected.as_str()));
Ok(CredentialReferenceRemoval {
removed,
still_referenced,
})
}
fn validate_workspace(value: &str) -> Result<String, CgdError> {
let value = value.trim();
if value.is_empty()
|| value.len() > 128
|| !value
.chars()
.all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))
{
return Err(CgdError::Configuration(
"workspace selectors may contain only 1-128 ASCII letters, digits, '-' or '_'"
.to_owned(),
));
}
Ok(value.to_owned())
}
fn write_config(path: &Path, file: &ConfigFile) -> Result<(), CgdError> {
let parent = path.parent().ok_or_else(|| {
CgdError::Configuration(format!(
"configuration path {} has no parent",
path.display()
))
})?;
fs::create_dir_all(parent).map_err(|error| {
CgdError::Configuration(format!(
"cannot create configuration directory {}: {error}",
parent.display()
))
})?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(parent, fs::Permissions::from_mode(0o700)).map_err(|error| {
CgdError::Configuration(format!(
"cannot protect configuration directory {}: {error}",
parent.display()
))
})?;
}
let encoded = toml::to_string_pretty(file)
.map_err(|error| CgdError::Internal(format!("cannot encode configuration: {error}")))?;
let mut options = AtomicWriteFile::options();
#[cfg(unix)]
{
use atomic_write_file::unix::OpenOptionsExt as _;
use std::os::unix::fs::OpenOptionsExt as _;
options.preserve_mode(false).mode(0o600);
}
let mut destination = options.open(path).map_err(|error| {
CgdError::Configuration(format!(
"cannot open {} for update: {error}",
path.display()
))
})?;
use std::io::Write as _;
destination.write_all(encoded.as_bytes()).map_err(|error| {
CgdError::Configuration(format!("cannot write {}: {error}", path.display()))
})?;
destination.commit().map_err(|error| {
CgdError::Configuration(format!("cannot commit {}: {error}", path.display()))
})
}
fn validate_profile_name(value: &str) -> Result<(), CgdError> {
if value.is_empty()
|| value.len() > 64
|| !value
.chars()
.all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))
{
return Err(CgdError::Configuration(
"profile names may contain only 1-64 ASCII letters, digits, '-' or '_'".to_owned(),
));
}
Ok(())
}
struct IgnoredCredentialStore;
impl CredentialStore for IgnoredCredentialStore {
fn get(&self, _reference: &CredentialReference) -> Result<Option<Credential>, CgdError> {
Ok(None)
}
}
fn validate_api_base_url(value: &str) -> Result<Url, CgdError> {
let mut url = Url::parse(value.trim())
.map_err(|_| CgdError::Configuration("API base URL must be an absolute URL".to_owned()))?;
if !url.username().is_empty()
|| url.password().is_some()
|| url.query().is_some()
|| url.fragment().is_some()
{
return Err(CgdError::Configuration(
"API base URL cannot contain credentials, a query, or a fragment".to_owned(),
));
}
let host = url
.host()
.ok_or_else(|| CgdError::Configuration("API base URL must contain a host".to_owned()))?;
match url.scheme() {
"https" => {}
"http" if is_loopback_host(host) => {}
_ => {
return Err(CgdError::Configuration(
"API base URL must use HTTPS; HTTP is allowed only for a loopback host".to_owned(),
));
}
}
if !url.path().ends_with('/') {
let path = format!("{}/", url.path());
url.set_path(&path);
}
Ok(url)
}
fn is_loopback_host(host: Host<&str>) -> bool {
match host {
Host::Domain(domain) => domain.eq_ignore_ascii_case("localhost"),
Host::Ipv4(address) => address.is_loopback(),
Host::Ipv6(address) => address.is_loopback(),
}
}
pub(crate) fn is_loopback_url(url: &Url) -> bool {
url.host().is_some_and(is_loopback_host)
}
fn parse_timeout(value: &str) -> Result<Duration, CgdError> {
let duration = humantime::parse_duration(value.trim())
.map_err(|error| CgdError::Configuration(format!("invalid timeout {value:?}: {error}")))?;
if !(Duration::from_millis(100)..=Duration::from_secs(120)).contains(&duration) {
return Err(CgdError::Configuration(
"timeout must be between 100ms and 120s".to_owned(),
));
}
Ok(duration)
}
fn parse_bool(key: &str, value: &str) -> Result<bool, CgdError> {
match value.trim().to_ascii_lowercase().as_str() {
"1" | "true" | "yes" | "on" => Ok(true),
"0" | "false" | "no" | "off" => Ok(false),
_ => Err(CgdError::Configuration(format!(
"{key} must be true/false, yes/no, on/off, or 1/0"
))),
}
}
pub fn display_origin(url: &Url) -> String {
let host = url.host_str().unwrap_or("unknown");
match url.port() {
Some(port) => format!("{}://{host}:{port}", url.scheme()),
None => format!("{}://{host}", url.scheme()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
#[derive(Default)]
struct TestEnvironment(BTreeMap<String, String>);
struct TestCredentialStore {
credential: Option<(CredentialKind, String)>,
reads: Cell<usize>,
}
impl Default for TestCredentialStore {
fn default() -> Self {
Self {
credential: None,
reads: Cell::new(0),
}
}
}
impl CredentialStore for TestCredentialStore {
fn get(&self, _reference: &CredentialReference) -> Result<Option<Credential>, CgdError> {
self.reads.set(self.reads.get() + 1);
self.credential
.as_ref()
.map(|(kind, value)| {
Credential::new(
*kind,
CredentialSource::OsCredentialStore,
value.clone(),
"test credential",
)
})
.transpose()
}
}
impl Environment for TestEnvironment {
fn get(&self, key: &str) -> Option<String> {
self.0.get(key).cloned()
}
}
fn resolve(
overrides: ConfigOverrides,
file_text: &str,
environment: TestEnvironment,
) -> Result<EffectiveConfig, CgdError> {
let file: ConfigFile = toml::from_str(file_text).unwrap_or_default();
let credential_store = TestCredentialStore::default();
EffectiveConfig::resolve(
&overrides,
file,
&environment,
&credential_store,
PathBuf::from("/test/config.toml"),
)
}
#[test]
fn precedence_is_flags_then_environment_then_profile_then_global_then_defaults() {
let file = r#"
current_profile = "team"
api_base_url = "https://global.example/"
default_output = "table"
timeout = "30s"
[profiles.team]
api_base_url = "https://profile.example/"
default_output = "json"
timeout = "20s"
"#;
let environment = TestEnvironment(BTreeMap::from([
(
"CORAGRID_API_BASE_URL".to_owned(),
"https://env.example/".to_owned(),
),
("CGD_OUTPUT".to_owned(), "jsonl".to_owned()),
("CGD_TIMEOUT".to_owned(), "10s".to_owned()),
]));
let config = resolve(
ConfigOverrides {
api_base_url: Some("https://flag.example/".to_owned()),
output: Some(OutputFormat::Csv),
timeout: Some("5s".to_owned()),
..ConfigOverrides::default()
},
file,
environment,
)
.unwrap();
assert_eq!(config.api_base_url.as_str(), "https://flag.example/");
assert_eq!(config.output, OutputFormat::Csv);
assert_eq!(config.timeout, Duration::from_secs(5));
}
#[test]
fn credential_debug_output_is_redacted_and_dual_environment_sources_fail() {
let credential = Credential::new(
CredentialKind::ApiKey,
CredentialSource::Environment,
"key_public.secret".to_owned(),
"test credential",
)
.unwrap();
let debug = format!("{credential:?}");
assert!(!debug.contains("key_public.secret"));
assert!(debug.contains("REDACTED"));
let environment = TestEnvironment(BTreeMap::from([
("CORAGRID_API_KEY".to_owned(), "one".to_owned()),
("CORAGRID_ACCESS_TOKEN".to_owned(), "two".to_owned()),
]));
assert!(resolve(ConfigOverrides::default(), "", environment).is_err());
}
#[test]
fn environment_credentials_override_the_configured_os_store() {
let file: ConfigFile = toml::from_str(
r#"
credential_ref = "os-keyring:cgd/default"
"#,
)
.unwrap();
let environment = TestEnvironment(BTreeMap::from([(
"CORAGRID_API_KEY".to_owned(),
"environment-secret".to_owned(),
)]));
let store = TestCredentialStore {
credential: Some((CredentialKind::ApiKey, "stored-secret".to_owned())),
reads: Cell::new(0),
};
let config = EffectiveConfig::resolve(
&ConfigOverrides::default(),
file,
&environment,
&store,
PathBuf::from("/test/config.toml"),
)
.unwrap();
assert_eq!(store.reads.get(), 0);
let credential = config.credential.unwrap();
assert_eq!(credential.bearer(), "environment-secret");
assert_eq!(credential.source(), CredentialSource::Environment);
}
#[test]
fn profile_credential_reference_loads_from_the_os_store() {
let file: ConfigFile = toml::from_str(
r#"
current_profile = "team"
[profiles.team]
credential_ref = "os-keyring:cgd/team"
"#,
)
.unwrap();
let store = TestCredentialStore {
credential: Some((CredentialKind::ApiKey, "stored-secret".to_owned())),
reads: Cell::new(0),
};
let config = EffectiveConfig::resolve(
&ConfigOverrides::default(),
file,
&TestEnvironment::default(),
&store,
PathBuf::from("/test/config.toml"),
)
.unwrap();
assert_eq!(store.reads.get(), 1);
assert_eq!(
config.credential_ref.unwrap().to_string(),
"os-keyring:cgd/team"
);
let credential = config.credential.unwrap();
assert_eq!(credential.bearer(), "stored-secret");
assert_eq!(credential.source(), CredentialSource::OsCredentialStore);
assert_eq!(
credential.source_description(),
"OS credential store API key"
);
}
#[test]
fn transport_security_rejects_remote_plaintext_and_url_credentials() {
for invalid in [
"http://api.coragrid.com",
"https://user:secret@api.coragrid.com",
"https://api.coragrid.com?token=secret",
] {
assert!(
validate_api_base_url(invalid).is_err(),
"accepted {invalid}"
);
}
assert!(validate_api_base_url("http://127.0.0.1:8080").is_ok());
assert!(validate_api_base_url("http://[::1]:8080").is_ok());
}
#[test]
fn platform_config_directory_preserves_the_approved_native_layout() {
let config = PathBuf::from("config-base");
let data = PathBuf::from("data-base");
let actual = platform_config_directory(config, data);
#[cfg(target_os = "macos")]
assert_eq!(actual, PathBuf::from("data-base/com.Coragrid.cgd"));
#[cfg(target_os = "windows")]
assert_eq!(actual, PathBuf::from(r"config-base\Coragrid\cgd\config"));
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
assert_eq!(actual, PathBuf::from("config-base/cgd"));
}
#[test]
fn profile_updates_are_validated_atomic_and_non_secret() {
let directory = std::env::temp_dir().join(format!(
"cgd-config-test-{}-{}",
std::process::id(),
rand::random::<u64>()
));
let path = directory.join("config.toml");
assert_eq!(
set_profile_value(
&path,
"team",
ConfigSetKey::ApiBaseUrl,
"https://api.example.test"
)
.unwrap(),
"https://api.example.test/"
);
assert_eq!(
set_profile_value(&path, "team", ConfigSetKey::Timeout, "5s").unwrap(),
"5s"
);
use_profile(&path, "team").unwrap();
let profiles = list_profiles(&path).unwrap();
assert_eq!(profiles.current, "team");
assert_eq!(profiles.names, ["default", "team"]);
let reference = CredentialReference::for_profile("team").unwrap();
set_profile_credential_reference(&path, "team", &reference).unwrap();
let removal = clear_effective_credential_reference(&path, "team", &reference).unwrap();
assert!(removal.removed);
assert!(!removal.still_referenced);
let written = fs::read_to_string(&path).unwrap();
assert!(written.contains("current_profile = \"team\""));
assert!(written.contains("api_base_url = \"https://api.example.test/\""));
assert!(!written.to_ascii_lowercase().contains("secret"));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o600
);
}
fs::remove_dir_all(directory).unwrap();
}
}