use std::io::IsTerminal;
use std::path::PathBuf;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use anyhow::{Context, Result};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use crate::keyring_store;
use crate::oauth;
const CONSOLE_URL_CACHE_TTL_DAYS: i64 = 7;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthKind {
#[default]
ApiKey,
OAuth,
}
impl AuthKind {
pub const fn as_str(self) -> &'static str {
match self {
AuthKind::ApiKey => "api_key",
AuthKind::OAuth => "oauth",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CredentialStorage {
#[default]
File,
OsStore,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum OutputFormat {
#[default]
Text,
Json,
#[value(alias = "agents")]
#[serde(alias = "agents")]
Toon,
}
impl OutputFormat {
pub fn as_str(&self) -> &'static str {
match self {
OutputFormat::Text => "text",
OutputFormat::Json => "json",
OutputFormat::Toon => "toon",
}
}
}
impl std::fmt::Display for OutputFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Region {
Us1,
Us2,
Us3,
Eu1,
Eu2,
Ap1,
Ap2,
Ap3,
Stg1,
#[serde(untagged)]
Custom(String),
}
impl Region {
pub fn api_endpoint(&self) -> &str {
match self {
Region::Us1 => "https://api.us1.coralogix.com",
Region::Us2 => "https://api.us2.coralogix.com",
Region::Us3 => "https://api.us3.coralogix.com",
Region::Eu1 => "https://api.eu1.coralogix.com",
Region::Eu2 => "https://api.eu2.coralogix.com",
Region::Ap1 => "https://api.ap1.coralogix.com",
Region::Ap2 => "https://api.ap2.coralogix.com",
Region::Ap3 => "https://api.ap3.coralogix.com",
Region::Stg1 => "https://api.stg1.coralogix.net",
Region::Custom(url) => url.as_str(),
}
}
pub fn app_url_template(&self) -> Option<&str> {
match self {
Region::Us1 => Some("app.coralogix.us"),
Region::Us2 => Some("app.cx498.coralogix.com"),
Region::Us3 => Some("app.us3.coralogix.com"),
Region::Eu1 => Some("coralogix.com"),
Region::Eu2 => Some("app.eu2.coralogix.com"),
Region::Ap1 => Some("app.coralogix.in"),
Region::Ap2 => Some("app.coralogixsg.com"),
Region::Ap3 => Some("app.ap3.coralogix.com"),
Region::Stg1 => Some("app.stg1.coralogix.net"),
Region::Custom(_) => None,
}
}
}
impl std::fmt::Display for Region {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Region::Us1 => write!(f, "us1"),
Region::Us2 => write!(f, "us2"),
Region::Us3 => write!(f, "us3"),
Region::Eu1 => write!(f, "eu1"),
Region::Eu2 => write!(f, "eu2"),
Region::Ap1 => write!(f, "ap1"),
Region::Ap2 => write!(f, "ap2"),
Region::Ap3 => write!(f, "ap3"),
Region::Stg1 => write!(f, "stg1"),
Region::Custom(s) => write!(f, "{s}"),
}
}
}
impl std::str::FromStr for Region {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self> {
Ok(match s.to_lowercase().as_str() {
"us1" => Region::Us1,
"us2" => Region::Us2,
"us3" => Region::Us3,
"eu1" => Region::Eu1,
"eu2" => Region::Eu2,
"ap1" => Region::Ap1,
"ap2" => Region::Ap2,
"ap3" => Region::Ap3,
"stg1" => Region::Stg1,
other => Region::Custom(other.to_string()),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ManagedCompletion {
pub shell: String,
pub path: PathBuf,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
#[serde(default = "default_profile")]
pub default_profile: String,
#[serde(default)]
pub default_output_format: OutputFormat,
#[serde(
default = "default_max_dataprime_direct_output_size",
with = "max_size_serde"
)]
pub max_dataprime_direct_output_size: Option<usize>,
#[serde(default = "default_temp_dir")]
pub temp_dir: String,
#[serde(default = "default_true")]
pub allow_risky_commands: bool,
#[serde(default = "default_true")]
pub olly_enabled: bool,
#[serde(default)]
pub read_only: bool,
#[serde(default)]
pub no_console_link: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub managed_completions: Vec<ManagedCompletion>,
}
fn default_profile() -> String {
"default".to_string()
}
fn default_true() -> bool {
true
}
fn default_max_dataprime_direct_output_size() -> Option<usize> {
Some(100 * 1024) }
fn default_temp_dir() -> String {
"/tmp/".to_string()
}
impl Default for Config {
fn default() -> Self {
Self {
default_profile: default_profile(),
default_output_format: OutputFormat::default(),
max_dataprime_direct_output_size: default_max_dataprime_direct_output_size(),
temp_dir: default_temp_dir(),
allow_risky_commands: true,
olly_enabled: true,
read_only: false,
no_console_link: false,
managed_completions: vec![],
}
}
}
mod max_size_serde {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn serialize<S>(value: &Option<usize>, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match value {
Some(n) => (*n as i64).serialize(s),
None => (-1i64).serialize(s),
}
}
pub fn deserialize<'de, D>(de: D) -> Result<Option<usize>, D::Error>
where
D: Deserializer<'de>,
{
let n = i64::deserialize(de)?;
if n < 0 {
Ok(None)
} else {
Ok(Some(n as usize))
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct StoredOAuthTokens {
pub access_token: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id_token: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expiry: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Profile {
#[serde(default)]
pub auth: AuthKind,
#[serde(default)]
pub credential_storage: CredentialStorage,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub api_key: Option<String>,
pub region: Region,
pub label: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub oauth_client_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub oauth_base_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub oauth_tokens: Option<StoredOAuthTokens>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_output_format: Option<OutputFormat>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_tier: Option<crate::Tier>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub console_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cached_console_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cached_console_url_at: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cached_team_id: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cached_team_name: Option<String>,
}
#[derive(Debug, Clone)]
pub struct ResolvedConfig {
pub profile_name: String,
pub api_key: String,
pub auth_kind: AuthKind,
pub endpoint: String,
pub default_tier: crate::Tier,
pub console_url: Option<String>,
pub credentials_overridden: bool,
}
pub fn config_dir() -> Result<PathBuf> {
if let Ok(cx_home) = std::env::var("CX_HOME") {
return Ok(PathBuf::from(cx_home).join(".cx"));
}
let home = dirs::home_dir().context("Could not determine home directory")?;
Ok(home.join(".cx"))
}
pub fn config_file() -> Result<PathBuf> {
Ok(config_dir()?.join("config.toml"))
}
pub fn profiles_dir() -> Result<PathBuf> {
Ok(config_dir()?.join("profiles"))
}
pub fn profile_file(name: &str) -> Result<PathBuf> {
Ok(profiles_dir()?.join(format!("{name}.toml")))
}
pub fn list_profile_names() -> Result<Vec<String>> {
list_profile_names_from(&profiles_dir()?)
}
fn list_profile_names_from(dir: &PathBuf) -> Result<Vec<String>> {
if !dir.exists() {
return Ok(vec![]);
}
let mut names: Vec<String> = std::fs::read_dir(dir)?
.filter_map(|entry| {
let entry = entry.ok()?;
let path = entry.path();
if path.extension()?.to_str()? != "toml" {
return None;
}
Some(path.file_stem()?.to_str()?.to_string())
})
.collect();
names.sort();
Ok(names)
}
pub fn load_config() -> Result<Config> {
let path = config_file()?;
if !path.exists() {
return Ok(Config::default());
}
let raw = std::fs::read_to_string(&path)
.with_context(|| format!("Failed to read {}", path.display()))?;
toml::from_str(&raw).context("Failed to parse config.toml")
}
pub fn save_config(config: &Config) -> Result<()> {
let dir = config_dir()?;
std::fs::create_dir_all(&dir)?;
let path = config_file()?;
let content = toml::to_string_pretty(config).context("Failed to serialize config")?;
std::fs::write(&path, content)
.with_context(|| format!("Failed to write {}", path.display()))?;
Ok(())
}
pub fn first_profile_output_format(profiles: &[String]) -> Option<OutputFormat> {
let name = if profiles.is_empty() {
load_config().ok().map(|c| c.default_profile)
} else {
Some(profiles[0].clone())
};
name.and_then(|n| load_profile(&n).ok())
.and_then(|p| p.default_output_format)
}
pub fn load_profile(name: &str) -> Result<Profile> {
let path = profile_file(name)?;
let raw = std::fs::read_to_string(&path).with_context(|| {
format!("Profile '{name}' not found. Run `cx profiles add` to set it up.")
})?;
toml::from_str(&raw).with_context(|| format!("Failed to parse profile '{name}'"))
}
fn interactive_reauth_allowed() -> bool {
std::io::stdin().is_terminal()
&& std::io::stdout().is_terminal()
&& !crate::safety::is_agent_mode()
}
fn normalize_team_url(url: &str) -> &str {
url.trim().trim_end_matches('/')
}
struct TeamConflict {
explanation: String,
select: String,
recovery: String,
}
impl std::fmt::Display for TeamConflict {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}\n{}", self.explanation, self.recovery)
}
}
fn reauth_team_conflict(
profile_name: &str,
profile: &Profile,
whoami: &crate::identity::Whoami,
) -> Option<TeamConflict> {
let signed_in = whoami.team_name.as_deref().unwrap_or("unknown");
let conflict = |explanation: String, select: String| TeamConflict {
explanation,
recovery: format!(
"Tokens were not saved. Run `cx profiles refresh {profile_name}` and select {select}."
),
select,
};
if let Some(previous_id) = profile.cached_team_id {
let original = team_to_select(profile, &format!("team id {previous_id}"));
return match whoami.team_id {
Some(id) if id == previous_id => None,
Some(id) => Some(conflict(
format!(
"Signed in to team '{signed_in}' (id {id}), but profile '{profile_name}' was last used with {original}."
),
original,
)),
None => Some(conflict(
format!(
"Sign-in did not report a team id, so it was not saved for profile '{profile_name}'."
),
original,
)),
};
}
let previous_url = profile.cached_console_url.as_deref()?;
let previous_url = normalize_team_url(previous_url);
let select = team_to_select(profile, previous_url);
match whoami
.team_url
.as_deref()
.map(normalize_team_url)
.filter(|url| !url.is_empty())
{
Some(url) if url == previous_url => None,
Some(url) => Some(conflict(
format!(
"Signed in to team '{signed_in}' ({url}), but profile '{profile_name}' was last used with {previous_url}."
),
select,
)),
None => Some(conflict(
format!(
"Sign-in did not report a team, so it was not saved for profile '{profile_name}'."
),
select,
)),
}
}
fn cached_display_name(profile: &Profile) -> Option<&str> {
profile
.cached_team_name
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty())
}
fn team_to_select(profile: &Profile, fallback: &str) -> String {
match cached_display_name(profile) {
Some(name) => match profile.cached_team_id {
Some(id) => format!("team '{name}' (id {id})"),
None => format!("team '{name}'"),
},
None => fallback.to_string(),
}
}
fn remember_signed_in_team(profile: &mut Profile, whoami: &crate::identity::Whoami) -> bool {
let mut changed = false;
if let Some(id) = whoami.team_id {
if profile.cached_team_id != Some(id) {
profile.cached_team_id = Some(id);
changed = true;
}
}
if let Some(name) = whoami
.team_name
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty())
{
if profile.cached_team_name.as_deref() != Some(name) {
profile.cached_team_name = Some(name.to_string());
changed = true;
}
}
if let Some(url) = whoami
.team_url
.as_deref()
.map(normalize_team_url)
.filter(|url| !url.is_empty())
{
if profile.cached_console_url.as_deref() != Some(url) {
profile.cached_console_url = Some(url.to_string());
}
profile.cached_console_url_at = Some(Utc::now());
changed = true;
}
changed
}
fn oauth_login_target(profile_name: &str, profile: &Profile) -> Result<(String, String)> {
let region_name = profile.region.to_string();
let base_url = profile
.oauth_base_url
.clone()
.unwrap_or_else(|| profile.region.api_endpoint().to_string());
let client_id = profile
.oauth_client_id
.clone()
.or_else(|| oauth::client_id_for_region(®ion_name).map(str::to_string))
.ok_or_else(|| {
anyhow::anyhow!(
"No OAuth client ID configured for profile '{profile_name}' \
(region: {region_name}).\n\
Run `cx profiles add {profile_name}` to reconfigure."
)
})?;
Ok((base_url, client_id))
}
async fn sign_in_to_profile_team(
profile_name: &str,
profile: &Profile,
base_url: &str,
client_id: &str,
region_overridden: bool,
) -> Result<(oauth::TokenResponse, crate::identity::Whoami)> {
let mut login = oauth::LoginOptions {
force_account_selection: false,
team_id: if region_overridden {
None
} else {
profile.cached_team_id
},
signup: false,
};
loop {
let tokens = oauth::browser_login(base_url, client_id, login.clone()).await?;
let client =
crate::api_client::CxClient::new(profile.region.api_endpoint(), &tokens.access_token)?;
let whoami = crate::identity::verify_identity(&client).await.context(
"Could not confirm which team this sign-in belongs to, so the new tokens were not saved.",
)?;
if region_overridden {
return Ok((tokens, whoami));
}
let Some(conflict) = reauth_team_conflict(profile_name, profile, &whoami) else {
return Ok((tokens, whoami));
};
eprintln!("{}", conflict.explanation);
let retry =
inquire::Confirm::new(&format!("Sign in again and select {}?", conflict.select))
.with_default(true)
.prompt()
.unwrap_or(false);
if !retry {
anyhow::bail!("{}", conflict.recovery);
}
login.force_account_selection = true;
}
}
fn keep_signed_in_tokens(
profile_name: &str,
profile: &mut Profile,
tokens: &oauth::TokenResponse,
) -> Result<String> {
if profile.credential_storage == CredentialStorage::OsStore {
match oauth::store_tokens_keyring(profile_name, tokens) {
Ok(()) => return Ok(tokens.access_token.clone()),
Err(err) => {
keyring_store::delete_profile(profile_name);
eprintln!(
"Warning: failed to store OAuth tokens in the OS credential store ({err}); \
migrated profile '{profile_name}' to file storage."
);
profile.credential_storage = CredentialStorage::File;
}
}
}
profile.oauth_tokens = Some(oauth::tokens_to_stored(tokens));
Ok(tokens.access_token.clone())
}
pub async fn refresh_oauth_profile(profile_name: &str) -> Result<()> {
let mut profile = load_profile(profile_name)?;
if profile.auth != AuthKind::OAuth {
anyhow::bail!(
"Profile '{profile_name}' uses an API key, so there is no sign-in to refresh.\n\
Run `cx profiles add {profile_name}` to change its credentials."
);
}
let (base_url, client_id) = oauth_login_target(profile_name, &profile)?;
let (tokens, whoami) =
sign_in_to_profile_team(profile_name, &profile, &base_url, &client_id, false).await?;
remember_signed_in_team(&mut profile, &whoami);
keep_signed_in_tokens(profile_name, &mut profile, &tokens)?;
save_profile(profile_name, &profile)?;
let team = whoami.team_name.as_deref().unwrap_or("this team");
println!("Signed in to team '{team}'. Profile '{profile_name}' is ready.");
Ok(())
}
async fn resolve_single(
profile_name: &str,
api_key_override: Option<&str>,
region_override: Option<&str>,
) -> Result<ResolvedConfig> {
if !profile_file(profile_name)?.exists() {
if let (Some(key), Some(region)) = (api_key_override, region_override) {
let region: Region = region.parse()?;
return Ok(ResolvedConfig {
profile_name: profile_name.to_string(),
endpoint: region.api_endpoint().to_string(),
api_key: key.to_string(),
auth_kind: AuthKind::ApiKey,
default_tier: crate::Tier::Archive,
console_url: None,
credentials_overridden: true,
});
}
}
let mut profile = load_profile(profile_name)?;
let stored_region = profile.region.clone();
let region_overridden = region_override.is_some();
if let Some(region) = region_override {
profile.region = region.parse()?;
}
let auth_kind = if api_key_override.is_some() {
AuthKind::ApiKey
} else {
profile.auth
};
let bearer = match auth_kind {
AuthKind::ApiKey => {
if let Some(key) = api_key_override {
key.to_string()
} else {
match profile.credential_storage {
CredentialStorage::OsStore => {
keyring_store::get_secret(profile_name, "api_key")?
}
CredentialStorage::File => profile.api_key.clone(),
}
.ok_or_else(|| {
anyhow::anyhow!(
"No API key found for profile '{profile_name}'.\n\
Run `cx profiles add {profile_name}` to set it up."
)
})?
}
}
AuthKind::OAuth => {
debug_assert!(api_key_override.is_none());
let (base_url, client_id) = oauth_login_target(profile_name, &profile)?;
let storage = profile.credential_storage;
let resolved = oauth::resolve_token(
profile_name,
&base_url,
&client_id,
storage,
profile.oauth_tokens.as_ref(),
)
.await;
let (bearer, refreshed, os_store_fallback_reason, persist_profile) = match resolved {
Ok(oauth::TokenResolution {
bearer,
refreshed_tokens,
os_store_fallback_reason,
}) => {
let persist = refreshed_tokens.is_some();
(bearer, refreshed_tokens, os_store_fallback_reason, persist)
}
Err(error) if oauth::is_reauth_required(&error) && interactive_reauth_allowed() => {
eprintln!(
"OAuth session for profile '{profile_name}' expired. Sign in to continue."
);
let (tokens, whoami) = sign_in_to_profile_team(
profile_name,
&profile,
&base_url,
&client_id,
region_overridden,
)
.await?;
let team = whoami.team_name.as_deref().unwrap_or("this team");
eprintln!("Signed in to team '{team}'. Continuing.");
let bearer = if region_overridden {
tokens.access_token
} else {
remember_signed_in_team(&mut profile, &whoami);
keep_signed_in_tokens(profile_name, &mut profile, &tokens)?
};
(bearer, None, None, !region_overridden)
}
Err(error) => return Err(error),
};
if let Some(new_tokens) = refreshed {
profile.oauth_tokens = Some(new_tokens);
if os_store_fallback_reason.is_some() {
profile.credential_storage = CredentialStorage::File;
}
}
if persist_profile {
let mut to_save = profile.clone();
to_save.region = stored_region;
save_profile(profile_name, &to_save)?;
if os_store_fallback_reason.is_some() {
keyring_store::delete_profile(profile_name);
eprintln!(
"Warning: failed to store refreshed OAuth tokens in the OS credential \
store; migrated profile '{profile_name}' to file storage."
);
}
}
bearer
}
};
Ok(ResolvedConfig {
profile_name: profile_name.to_string(),
endpoint: profile.region.api_endpoint().to_string(),
api_key: bearer,
auth_kind,
default_tier: profile.default_tier.unwrap_or(crate::Tier::Archive),
console_url: profile
.console_url
.as_deref()
.map(|s| s.trim_end_matches('/').to_string()),
credentials_overridden: api_key_override.is_some(),
})
}
pub async fn resolve(
profile_override: Option<&str>,
api_key_override: Option<&str>,
region_override: Option<&str>,
) -> Result<ResolvedConfig> {
let config = load_config()?;
let name = profile_override.unwrap_or(&config.default_profile);
resolve_single(name, api_key_override, region_override).await
}
pub async fn resolve_all(
profiles: &[String],
api_key_override: Option<&str>,
region_override: Option<&str>,
) -> Result<Vec<ResolvedConfig>> {
if profiles.is_empty() {
let cfg = load_config()?;
return Ok(vec![
resolve_single(&cfg.default_profile, api_key_override, region_override).await?,
]);
}
let mut results = Vec::with_capacity(profiles.len());
for name in profiles {
results.push(resolve_single(name, api_key_override, region_override).await?);
}
Ok(results)
}
pub fn save_profile(name: &str, profile: &Profile) -> Result<()> {
let dir = profiles_dir()?;
std::fs::create_dir_all(&dir)?;
let path = dir.join(format!("{name}.toml"));
let content = toml::to_string_pretty(profile).context("Failed to serialize profile")?;
std::fs::write(&path, &content)
.with_context(|| format!("Failed to write {}", path.display()))?;
#[cfg(unix)]
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
.with_context(|| format!("Failed to set permissions on {}", path.display()))?;
Ok(())
}
pub fn load_cached_console_url(profile_name: &str) -> Option<String> {
let profile = load_profile(profile_name).ok()?;
let cached_at = profile.cached_console_url_at?;
if Utc::now() - cached_at < Duration::days(CONSOLE_URL_CACHE_TTL_DAYS) {
profile.cached_console_url
} else {
None
}
}
pub fn cache_team_identity(profile_name: &str, whoami: &crate::identity::Whoami) {
let Ok(mut profile) = load_profile(profile_name) else {
return;
};
if remember_signed_in_team(&mut profile, whoami) {
let _ = save_profile(profile_name, &profile);
}
}
pub fn has_managed_completions() -> bool {
load_config()
.map(|c| !c.managed_completions.is_empty())
.unwrap_or(false)
}
pub fn managed_completions() -> Result<Vec<ManagedCompletion>> {
Ok(load_config()?.managed_completions)
}
pub fn upsert_managed_completion(shell: &str, path: PathBuf) -> Result<()> {
let mut config = load_config().unwrap_or_default();
if let Some(existing) = config
.managed_completions
.iter_mut()
.find(|c| c.shell == shell)
{
existing.path = path;
} else {
config.managed_completions.push(ManagedCompletion {
shell: shell.to_string(),
path,
});
}
save_config(&config)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn output_format_as_str_is_toon() {
assert_eq!(OutputFormat::Toon.as_str(), "toon");
assert_eq!(OutputFormat::Toon.to_string(), "toon");
}
#[test]
fn output_format_serializes_as_toon() {
let json = serde_json::to_string(&OutputFormat::Toon).unwrap();
assert_eq!(json, "\"toon\"");
}
#[test]
fn output_format_deserializes_toon_and_agents_alias() {
let toon: OutputFormat = serde_json::from_str("\"toon\"").unwrap();
assert_eq!(toon, OutputFormat::Toon);
let agents: OutputFormat = serde_json::from_str("\"agents\"").unwrap();
assert_eq!(agents, OutputFormat::Toon);
}
#[test]
fn output_format_profile_toml_accepts_agents_alias() {
let profile: Profile =
toml::from_str("region = \"eu2\"\ndefault_output_format = \"agents\"\n").unwrap();
assert_eq!(profile.default_output_format, Some(OutputFormat::Toon));
}
#[test]
fn output_format_clap_parses_toon_and_agents_alias() {
use clap::ValueEnum;
assert_eq!(
OutputFormat::from_str("toon", true).unwrap(),
OutputFormat::Toon
);
assert_eq!(
OutputFormat::from_str("agents", true).unwrap(),
OutputFormat::Toon
);
}
#[test]
fn list_profile_names_sorted_and_filters_non_toml() {
let dir =
std::env::temp_dir().join(format!("cx_test_list_profiles_{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("prod.toml"), "").unwrap();
std::fs::write(dir.join("staging.toml"), "").unwrap();
std::fs::write(dir.join("alpha.toml"), "").unwrap();
std::fs::write(dir.join("ignored.txt"), "").unwrap();
std::fs::write(dir.join("also-ignored.json"), "").unwrap();
let names = list_profile_names_from(&dir).unwrap();
assert_eq!(names, vec!["alpha", "prod", "staging"]);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn list_profile_names_missing_dir_returns_empty() {
let dir = std::env::temp_dir().join("cx_test_nonexistent_profiles_dir_xyz_never_created");
let _ = std::fs::remove_dir_all(&dir);
let names = list_profile_names_from(&dir).unwrap();
assert!(names.is_empty());
}
#[test]
fn list_profile_names_empty_dir_returns_empty() {
let dir =
std::env::temp_dir().join(format!("cx_test_empty_profiles_{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let names = list_profile_names_from(&dir).unwrap();
assert!(names.is_empty());
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn managed_completion_roundtrips_through_toml() {
let mc = ManagedCompletion {
shell: "zsh".to_string(),
path: PathBuf::from("/home/user/.zfunc/_cx"),
};
let config = Config {
managed_completions: vec![mc.clone()],
..Config::default()
};
let toml = toml::to_string_pretty(&config).unwrap();
let restored: Config = toml::from_str(&toml).unwrap();
assert_eq!(restored.managed_completions.len(), 1);
assert_eq!(restored.managed_completions[0], mc);
}
#[test]
fn default_config_has_no_managed_completions() {
let config = Config::default();
assert!(config.managed_completions.is_empty());
}
#[test]
fn config_without_managed_completions_field_deserialises_ok() {
let toml = r#"
default_profile = "my-profile"
"#;
let config: Config = toml::from_str(toml).unwrap();
assert!(config.managed_completions.is_empty());
assert_eq!(config.default_profile, "my-profile");
}
#[test]
fn managed_completions_not_written_when_empty() {
let config = Config::default();
let toml = toml::to_string_pretty(&config).unwrap();
assert!(
!toml.contains("managed_completions"),
"empty managed_completions should be skipped in TOML output"
);
}
#[test]
fn resolved_config_carries_profile_name() {
let cfg = ResolvedConfig {
profile_name: "prod".to_string(),
api_key: "k".to_string(),
auth_kind: AuthKind::ApiKey,
endpoint: "https://api.eu2.coralogix.com".to_string(),
default_tier: crate::Tier::Archive,
console_url: None,
credentials_overridden: false,
};
assert_eq!(cfg.profile_name, "prod");
}
#[test]
fn region_api_endpoint_eu1() {
assert_eq!(Region::Eu1.api_endpoint(), "https://api.eu1.coralogix.com");
}
#[test]
fn region_api_endpoint_us1() {
assert_eq!(Region::Us1.api_endpoint(), "https://api.us1.coralogix.com");
}
#[test]
fn region_app_url_template_eu2() {
assert_eq!(
Region::Eu2.app_url_template(),
Some("app.eu2.coralogix.com")
);
}
#[test]
fn region_app_url_template_us2_uses_cx498() {
assert_eq!(
Region::Us2.app_url_template(),
Some("app.cx498.coralogix.com")
);
}
#[test]
fn region_app_url_template_custom_is_none() {
assert_eq!(
Region::Custom("https://api.myenv.example.com".into()).app_url_template(),
None
);
}
#[test]
fn every_named_region_has_an_app_url_template() {
let cases: &[(Region, &str)] = &[
(Region::Us1, "app.coralogix.us"),
(Region::Us2, "app.cx498.coralogix.com"),
(Region::Us3, "app.us3.coralogix.com"),
(Region::Eu1, "coralogix.com"),
(Region::Eu2, "app.eu2.coralogix.com"),
(Region::Ap1, "app.coralogix.in"),
(Region::Ap2, "app.coralogixsg.com"),
(Region::Ap3, "app.ap3.coralogix.com"),
(Region::Stg1, "app.stg1.coralogix.net"),
];
for (region, expected) in cases {
assert_eq!(region.app_url_template(), Some(*expected), "{region}");
}
}
#[test]
fn region_parses_from_str() {
let r: Region = "eu2".parse().unwrap();
assert_eq!(r.api_endpoint(), "https://api.eu2.coralogix.com");
}
#[test]
fn region_custom_roundtrip() {
let url = "https://custom.endpoint.io";
let r: Region = url.parse().unwrap();
assert_eq!(r.api_endpoint(), url);
}
#[test]
fn profile_without_auth_field_defaults_to_api_key() {
let toml = r#"
region = "eu1"
api_key = "mykey"
"#;
let p: Profile = toml::from_str(toml).unwrap();
assert_eq!(p.auth, AuthKind::ApiKey);
assert_eq!(p.api_key.as_deref(), Some("mykey"));
assert!(p.oauth_client_id.is_none());
assert!(p.oauth_base_url.is_none());
}
#[test]
fn oauth_profile_round_trips() {
let profile = Profile {
auth: AuthKind::OAuth,
credential_storage: CredentialStorage::OsStore,
api_key: None,
region: Region::Eu2,
label: Some("prod".to_string()),
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
console_url: None,
cached_console_url: None,
cached_console_url_at: None,
cached_team_id: None,
cached_team_name: None,
};
let toml = toml::to_string_pretty(&profile).unwrap();
let restored: Profile = toml::from_str(&toml).unwrap();
assert_eq!(restored.auth, AuthKind::OAuth);
assert_eq!(restored.credential_storage, CredentialStorage::OsStore);
assert!(restored.api_key.is_none());
assert!(restored.oauth_client_id.is_none());
assert!(restored.oauth_tokens.is_none());
}
#[test]
fn oauth_profile_file_storage_round_trips() {
let profile = Profile {
auth: AuthKind::OAuth,
credential_storage: CredentialStorage::File,
api_key: None,
region: Region::Eu2,
label: Some("prod".to_string()),
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: Some(StoredOAuthTokens {
access_token: "access-abc".to_string(),
refresh_token: Some("refresh-xyz".to_string()),
id_token: None,
expiry: Some(1_700_000_000),
}),
default_output_format: None,
default_tier: None,
console_url: None,
cached_console_url: None,
cached_console_url_at: None,
cached_team_id: None,
cached_team_name: None,
};
let toml = toml::to_string_pretty(&profile).unwrap();
let restored: Profile = toml::from_str(&toml).unwrap();
assert_eq!(restored.credential_storage, CredentialStorage::File);
let tokens = restored.oauth_tokens.expect("oauth_tokens persisted");
assert_eq!(tokens.access_token, "access-abc");
assert_eq!(tokens.refresh_token.as_deref(), Some("refresh-xyz"));
assert!(tokens.id_token.is_none());
assert_eq!(tokens.expiry, Some(1_700_000_000));
}
#[test]
fn custom_oauth_profile_preserves_client_id() {
let profile = Profile {
auth: AuthKind::OAuth,
credential_storage: CredentialStorage::OsStore,
api_key: None,
region: Region::Custom("https://api.myenv.coralogix.com".to_string()),
label: None,
oauth_client_id: Some("abc-123".to_string()),
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
console_url: None,
cached_console_url: None,
cached_console_url_at: None,
cached_team_id: None,
cached_team_name: None,
};
let toml = toml::to_string_pretty(&profile).unwrap();
let restored: Profile = toml::from_str(&toml).unwrap();
assert_eq!(restored.oauth_client_id.as_deref(), Some("abc-123"));
}
#[tokio::test]
async fn resolve_all_missing_profile_returns_error() {
let result = resolve_all(
&["cx_definitely_does_not_exist_xyz".to_string()],
None,
None,
)
.await;
assert!(result.is_err());
}
#[tokio::test]
async fn resolve_single_env_only_synthesises_when_profile_file_missing() {
let cfg = resolve_single(
"cx_envonly_missing_profile_xyz",
Some("env-key"),
Some("eu1"),
)
.await
.unwrap();
assert_eq!(cfg.profile_name, "cx_envonly_missing_profile_xyz");
assert_eq!(cfg.api_key, "env-key");
assert_eq!(cfg.endpoint, "https://api.eu1.coralogix.com");
}
#[tokio::test]
async fn resolve_single_env_only_requires_api_key_override() {
let result = resolve_single("cx_envonly_no_key_xyz", None, Some("eu1")).await;
assert!(result.is_err());
}
#[tokio::test]
async fn resolve_single_env_only_requires_region_override() {
let result = resolve_single("cx_envonly_no_region_xyz", Some("env-key"), None).await;
assert!(result.is_err());
}
#[test]
fn save_profile_empty_name_creates_hidden_file() {
let dir =
std::env::temp_dir().join(format!("cx_test_empty_profile_name_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("profiles")).unwrap();
std::fs::write(dir.join("profiles").join(".toml"), "region = \"eu1\"\n").unwrap();
let names = list_profile_names_from(&dir.join("profiles")).unwrap();
assert!(
names.is_empty() || !names.contains(&String::new()),
"empty-named profile should not appear in list, got: {names:?}"
);
std::fs::remove_dir_all(&dir).unwrap();
}
#[tokio::test]
#[ignore = "requires write access to ~/.cx; run with `cargo test -- --ignored`"]
async fn resolve_all_integration_multiple_profiles() {
let names = ["cx_inttest_multi_a", "cx_inttest_multi_b"];
for (i, name) in names.iter().enumerate() {
let profile = Profile {
auth: AuthKind::ApiKey,
credential_storage: CredentialStorage::File,
api_key: Some(format!("key-{i}")),
region: Region::Eu1,
label: None,
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
console_url: None,
cached_console_url: None,
cached_console_url_at: None,
cached_team_id: None,
cached_team_name: None,
};
save_profile(name, &profile).unwrap();
}
let configs = resolve_all(
&names.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
None,
None,
)
.await
.unwrap();
assert_eq!(configs.len(), 2);
assert_eq!(configs[0].profile_name, "cx_inttest_multi_a");
assert_eq!(configs[0].api_key, "key-0");
assert_eq!(configs[1].profile_name, "cx_inttest_multi_b");
assert_eq!(configs[1].api_key, "key-1");
for name in &names {
let _ = std::fs::remove_file(profile_file(name).unwrap());
}
}
#[tokio::test]
#[ignore = "requires write access to ~/.cx; run with `cargo test -- --ignored`"]
async fn resolve_all_integration_empty_slice_falls_back_to_default() {
let profile = Profile {
auth: AuthKind::ApiKey,
credential_storage: CredentialStorage::File,
api_key: Some("default-key".to_string()),
region: Region::Eu1,
label: None,
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
console_url: None,
cached_console_url: None,
cached_console_url_at: None,
cached_team_id: None,
cached_team_name: None,
};
save_profile("default", &profile).unwrap();
let configs = resolve_all(&[], None, None).await.unwrap();
assert_eq!(configs.len(), 1);
assert_eq!(configs[0].profile_name, "default");
}
#[tokio::test]
#[ignore = "requires write access to ~/.cx"]
async fn resolve_prefers_cli_override_over_file() {
let name = "cx_inttest_resolve_override";
let profile = Profile {
auth: AuthKind::ApiKey,
credential_storage: CredentialStorage::File,
api_key: Some("file-key".to_string()),
region: Region::Eu1,
label: None,
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
console_url: None,
cached_console_url: None,
cached_console_url_at: None,
cached_team_id: None,
cached_team_name: None,
};
save_profile(name, &profile).unwrap();
let config = resolve_single(name, Some("cli-key"), None).await.unwrap();
assert_eq!(config.api_key, "cli-key");
let _ = std::fs::remove_file(profile_file(name).unwrap());
}
#[tokio::test]
#[ignore = "requires write access to ~/.cx"]
async fn resolve_reads_from_file_storage() {
let name = "cx_inttest_resolve_file";
let profile = Profile {
auth: AuthKind::ApiKey,
credential_storage: CredentialStorage::File,
api_key: Some("file-key".to_string()),
region: Region::Eu1,
label: None,
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
console_url: None,
cached_console_url: None,
cached_console_url_at: None,
cached_team_id: None,
cached_team_name: None,
};
save_profile(name, &profile).unwrap();
let config = resolve_single(name, None, None).await.unwrap();
assert_eq!(config.api_key, "file-key");
let _ = std::fs::remove_file(profile_file(name).unwrap());
}
#[tokio::test]
#[ignore = "requires write access to ~/.cx"]
async fn resolve_errors_when_no_key_anywhere() {
let name = "cx_inttest_resolve_no_key";
let profile = Profile {
auth: AuthKind::ApiKey,
credential_storage: CredentialStorage::File,
api_key: None,
region: Region::Eu1,
label: None,
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
console_url: None,
cached_console_url: None,
cached_console_url_at: None,
cached_team_id: None,
cached_team_name: None,
};
save_profile(name, &profile).unwrap();
let result = resolve_single(name, None, None).await;
assert!(result.is_err());
let _ = std::fs::remove_file(profile_file(name).unwrap());
}
#[test]
fn load_cached_console_url_none_for_missing_profile() {
assert_eq!(
load_cached_console_url("cx_unittest_definitely_missing_profile_xyz"),
None
);
}
fn profile_with_cache(cached_at: Option<DateTime<Utc>>) -> Profile {
Profile {
auth: AuthKind::ApiKey,
credential_storage: CredentialStorage::File,
api_key: Some("k".to_string()),
region: Region::Eu1,
label: None,
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
console_url: None,
cached_console_url: Some("https://cached.app.eu2.coralogix.com".to_string()),
cached_console_url_at: cached_at,
cached_team_id: None,
cached_team_name: None,
}
}
#[test]
#[ignore = "requires write access to ~/.cx; run with `cargo test -- --ignored`"]
fn cache_team_identity_round_trips() {
let name = "cx_inttest_console_cache_roundtrip";
save_profile(name, &profile_with_cache(None)).unwrap();
cache_team_identity(
name,
&whoami(Some(12), "c4c", Some("https://fresh.app.eu2.coralogix.com")),
);
assert_eq!(
load_cached_console_url(name),
Some("https://fresh.app.eu2.coralogix.com".to_string())
);
let _ = std::fs::remove_file(profile_file(name).unwrap());
}
#[test]
#[ignore = "requires write access to ~/.cx; run with `cargo test -- --ignored`"]
fn load_cached_console_url_ignores_stale_entry() {
let name = "cx_inttest_console_cache_stale";
let stale = Utc::now() - Duration::days(CONSOLE_URL_CACHE_TTL_DAYS + 1);
save_profile(name, &profile_with_cache(Some(stale))).unwrap();
assert_eq!(load_cached_console_url(name), None);
let _ = std::fs::remove_file(profile_file(name).unwrap());
}
#[test]
#[ignore = "requires write access to ~/.cx; run with `cargo test -- --ignored`"]
fn load_cached_console_url_returns_fresh_entry() {
let name = "cx_inttest_console_cache_fresh";
let fresh = Utc::now() - Duration::days(CONSOLE_URL_CACHE_TTL_DAYS - 1);
save_profile(name, &profile_with_cache(Some(fresh))).unwrap();
assert_eq!(
load_cached_console_url(name),
Some("https://cached.app.eu2.coralogix.com".to_string())
);
let _ = std::fs::remove_file(profile_file(name).unwrap());
}
fn whoami(id: Option<i64>, name: &str, url: Option<&str>) -> crate::identity::Whoami {
crate::identity::Whoami {
team_id: id,
team_name: Some(name.to_string()),
user_name: None,
team_url: url.map(str::to_string),
}
}
#[test]
fn reauth_accepts_the_same_team_id() {
let mut profile = profile_with_cache(None);
profile.cached_team_id = Some(12);
let signed_in = whoami(Some(12), "c4c", Some("https://other.example"));
assert!(reauth_team_conflict("default", &profile, &signed_in).is_none());
}
#[test]
fn reauth_rejects_a_different_team_id() {
let mut profile = profile_with_cache(None);
profile.cached_team_id = Some(12);
let signed_in = whoami(Some(99), "other", Some("https://other.example"));
let msg = reauth_team_conflict("default", &profile, &signed_in)
.unwrap()
.to_string();
assert!(msg.contains("id 99"), "{msg}");
assert!(msg.contains("team id 12"), "{msg}");
assert!(
msg.contains("Run `cx profiles refresh default` and select team id 12."),
"{msg}"
);
}
#[test]
fn reauth_conflict_separates_explanation_retry_label_and_recovery() {
let mut profile = profile_with_cache(None);
profile.cached_team_id = Some(12);
profile.cached_team_name = Some("c4c".to_string());
let signed_in = whoami(Some(99), "other", Some("https://other.example"));
let conflict = reauth_team_conflict("default", &profile, &signed_in).unwrap();
assert!(
conflict
.explanation
.contains("last used with team 'c4c' (id 12)"),
"{}",
conflict.explanation
);
assert!(
!conflict.explanation.contains("Tokens were not saved"),
"the explanation is printed before the retry prompt and must not \
claim the flow already gave up: {}",
conflict.explanation
);
assert_eq!(conflict.select, "team 'c4c' (id 12)");
assert!(
conflict.recovery.starts_with("Tokens were not saved."),
"{}",
conflict.recovery
);
}
#[test]
fn reauth_recovery_hint_uses_the_cached_team_name() {
let mut profile = profile_with_cache(None);
profile.cached_team_id = Some(12);
profile.cached_team_name = Some("c4c".to_string());
let signed_in = whoami(Some(99), "other", Some("https://other.example"));
let msg = reauth_team_conflict("default", &profile, &signed_in)
.unwrap()
.to_string();
assert!(
msg.contains("Run `cx profiles refresh default` and select team 'c4c' (id 12)."),
"{msg}"
);
assert!(msg.contains("last used with team 'c4c' (id 12)"), "{msg}");
}
#[test]
fn remember_signed_in_team_refreshes_console_url_ttl_when_url_is_unchanged() {
let stale = Utc::now() - Duration::days(CONSOLE_URL_CACHE_TTL_DAYS + 1);
let mut profile = profile_with_cache(Some(stale));
let signed_in = whoami(Some(1), "c4c", Some("https://cached.app.eu2.coralogix.com"));
assert!(remember_signed_in_team(&mut profile, &signed_in));
let refreshed_at = profile.cached_console_url_at.expect("ttl refreshed");
assert!(refreshed_at > stale);
}
#[test]
fn reauth_rejects_a_different_team_url_when_no_id_is_cached() {
let profile = profile_with_cache(None);
let signed_in = whoami(
Some(2),
"other",
Some("https://other.app.eu2.coralogix.com"),
);
let msg = reauth_team_conflict("default", &profile, &signed_in)
.unwrap()
.to_string();
assert!(msg.contains("other.app.eu2.coralogix.com"), "{msg}");
assert!(msg.contains("cached.app.eu2.coralogix.com"), "{msg}");
}
#[test]
fn reauth_allows_sign_in_when_no_team_was_recorded() {
let mut profile = profile_with_cache(None);
profile.cached_console_url = None;
profile.cached_team_id = None;
let signed_in = whoami(Some(2), "c4c", Some("https://c4c.app.eu2.coralogix.com"));
assert!(reauth_team_conflict("default", &profile, &signed_in).is_none());
}
}