use std::io::IsTerminal;
use std::path::PathBuf;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use anyhow::{bail, Context, Result};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use crate::keyring_store;
use crate::oauth;
use crate::safety::KeychainSandbox;
const CONSOLE_URL_CACHE_TTL_DAYS: i64 = 7;
static INVALID_READ_ONLY_WARNING: std::sync::Once = std::sync::Once::new();
#[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)]
pub enum SandboxCredentialHint {
DefaultProfile,
ExplicitSingleProfile,
ExplicitMultipleProfiles,
OAuthRefresh,
}
#[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 strict_fields_validation: bool,
#[serde(default)]
pub no_console_link: bool,
#[serde(default = "default_true")]
pub auto_update_skills: 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 {
if cfg!(windows) {
let mut dir = std::env::temp_dir().to_string_lossy().into_owned();
if !dir.ends_with(std::path::MAIN_SEPARATOR) {
dir.push(std::path::MAIN_SEPARATOR);
}
dir
} else {
"/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,
strict_fields_validation: false,
no_console_link: false,
auto_update_skills: true,
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>,
}
pub fn normalize_labels<I, S>(values: I) -> Vec<String>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut out = Vec::new();
for value in values {
let trimmed = value.as_ref().trim();
if trimmed.is_empty() || out.iter().any(|existing| existing == trimmed) {
continue;
}
out.push(trimmed.to_string());
}
out
}
pub fn parse_given_label_args<S: AsRef<str>>(values: &[S]) -> Result<Vec<String>> {
let labels = parse_label_args(values);
if labels.is_empty() && !values.is_empty() {
bail!("--label needs at least one non-empty label.");
}
Ok(labels)
}
pub fn parse_label_args<I, S>(values: I) -> Vec<String>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut parts = Vec::new();
for value in values {
for part in value.as_ref().split(',') {
parts.push(part.to_string());
}
}
normalize_labels(parts)
}
pub(crate) fn has_any_label(labels: &[String], wanted: &[String]) -> bool {
wanted
.iter()
.any(|want| labels.iter().any(|have| have == want))
}
pub(crate) fn no_profiles_for_labels(labels: &[String]) -> String {
let quoted: Vec<String> = labels.iter().map(|label| format!("'{label}'")).collect();
match quoted.as_slice() {
[] => "No profiles matched.".to_string(),
[label] => format!("No profiles with label {label}."),
[head @ .., last] => format!("No profiles with label {} or {last}.", head.join(", ")),
}
}
fn names_with_any_label(entries: &[(String, Vec<String>)], wanted: &[String]) -> Vec<String> {
entries
.iter()
.filter(|(_, labels)| has_any_label(labels, wanted))
.map(|(name, _)| name.clone())
.collect()
}
pub fn select_profile_names(profiles: &[String], labels: &[String]) -> Result<Vec<String>> {
let mut selected: Vec<String> = profiles.to_vec();
if labels.is_empty() {
return Ok(selected);
}
let entries: Vec<(String, Vec<String>)> = list_profile_names()?
.into_iter()
.filter_map(|name| match load_profile(&name) {
Ok(profile) => Some((name, profile.labels)),
Err(error) => {
eprintln!("warning: skipping profile '{name}' in the --label scan: {error}");
None
}
})
.collect();
let matched = names_with_any_label(&entries, labels);
if matched.is_empty() {
bail!(
"{} Run `cx profiles list` to see each profile's labels, \
or `cx profiles add <name> --label <label>` to tag one.",
no_profiles_for_labels(labels)
);
}
for label in labels {
if !entries.iter().any(|(_, have)| have.contains(label)) {
eprintln!("warning: no profile has label '{label}'");
}
}
for name in matched {
if !selected.contains(&name) {
selected.push(name);
}
}
Ok(selected)
}
fn labels_from_file(label: Option<String>, labels: Option<Vec<String>>) -> Vec<String> {
if let Some(labels) = labels {
let normalized = normalize_labels(labels);
if !normalized.is_empty() {
return normalized;
}
}
match label {
Some(label) => normalize_labels([label]),
None => Vec::new(),
}
}
#[derive(Debug, Clone, Serialize)]
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,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub labels: Vec<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 = "std::ops::Not::not")]
pub read_only: bool,
#[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(Deserialize)]
struct ProfileDe {
#[serde(default)]
auth: AuthKind,
#[serde(default)]
credential_storage: CredentialStorage,
#[serde(default)]
api_key: Option<String>,
region: Region,
#[serde(default)]
label: Option<String>,
#[serde(default)]
labels: Option<Vec<String>>,
#[serde(default)]
oauth_client_id: Option<String>,
#[serde(default)]
oauth_base_url: Option<String>,
#[serde(default)]
oauth_tokens: Option<StoredOAuthTokens>,
#[serde(default)]
default_output_format: Option<OutputFormat>,
#[serde(default)]
default_tier: Option<crate::Tier>,
#[serde(default, deserialize_with = "deserialize_read_only")]
read_only: bool,
#[serde(default)]
console_url: Option<String>,
#[serde(default)]
cached_console_url: Option<String>,
#[serde(default)]
cached_console_url_at: Option<DateTime<Utc>>,
#[serde(default)]
cached_team_id: Option<i64>,
#[serde(default)]
cached_team_name: Option<String>,
}
fn deserialize_read_only<'de, D>(deserializer: D) -> std::result::Result<bool, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum ReadOnlyValue {
Bool(bool),
Invalid(toml::Value),
}
match ReadOnlyValue::deserialize(deserializer)? {
ReadOnlyValue::Bool(value) => Ok(value),
ReadOnlyValue::Invalid(value) => {
INVALID_READ_ONLY_WARNING.call_once(|| {
eprintln!(
"warning: ignoring invalid read_only value {value:?} in profile TOML; treating it as false"
);
});
Ok(false)
}
}
}
impl From<ProfileDe> for Profile {
fn from(file: ProfileDe) -> Self {
Self {
auth: file.auth,
credential_storage: file.credential_storage,
api_key: file.api_key,
region: file.region,
labels: labels_from_file(file.label, file.labels),
oauth_client_id: file.oauth_client_id,
oauth_base_url: file.oauth_base_url,
oauth_tokens: file.oauth_tokens,
default_output_format: file.default_output_format,
default_tier: file.default_tier,
read_only: file.read_only,
console_url: file.console_url,
cached_console_url: file.cached_console_url,
cached_console_url_at: file.cached_console_url_at,
cached_team_id: file.cached_team_id,
cached_team_name: file.cached_team_name,
}
}
}
impl<'de> Deserialize<'de> for Profile {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(ProfileDe::deserialize(deserializer)?.into())
}
}
#[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}'"))
}
pub fn migrate_managed_profiles_to_os_store() -> Result<()> {
migrate_managed_profiles_with(
crate::managed_policy::requires_os_store()?,
crate::safety::is_macos_keychain_sandboxed,
list_profile_names,
|name| {
load_profile(name)
.with_context(|| {
format!("Could not check profile '{name}' for plaintext credentials")
})
.and_then(|mut profile| migrate_profile_to_os_store(name, &mut profile))
.map(|_| ())
},
)
}
fn migrate_managed_profiles_with(
managed: bool,
keychain_sandboxed: impl FnOnce() -> bool,
list_profiles: impl FnOnce() -> Result<Vec<String>>,
migrate_profile: impl Fn(&str) -> Result<()>,
) -> Result<()> {
if !managed || keychain_sandboxed() {
return Ok(());
}
for name in list_profiles()? {
if let Err(err) = migrate_profile(&name) {
eprintln!("Warning: {err:#}");
}
}
Ok(())
}
fn migrate_profile_to_os_store(name: &str, profile: &mut Profile) -> Result<bool> {
migrate_profile_with(name, profile, store_profile_secrets, save_profile)
}
fn migrate_profile_with(
name: &str,
profile: &mut Profile,
store: impl FnOnce(&str, &Profile) -> Result<()>,
save: impl FnOnce(&str, &Profile) -> Result<()>,
) -> Result<bool> {
let has_plaintext = profile.api_key.is_some() || profile.oauth_tokens.is_some();
if profile.credential_storage == CredentialStorage::OsStore && !has_plaintext {
return Ok(false);
}
if profile.credential_storage == CredentialStorage::File {
store(name, profile).with_context(|| {
format!(
"Could not move the credentials of profile '{name}' into the OS credential \
store; its profile file was left unchanged"
)
})?;
}
profile.credential_storage = CredentialStorage::OsStore;
profile.api_key = None;
profile.oauth_tokens = None;
save(name, profile)?;
Ok(true)
}
fn store_profile_secrets(name: &str, profile: &Profile) -> Result<()> {
let stored = match profile.auth {
AuthKind::ApiKey => match profile.api_key.as_deref() {
Some(api_key) => keyring_store::store_secret(name, "api_key", api_key),
None => Ok(()),
},
AuthKind::OAuth => match profile.oauth_tokens.as_ref() {
Some(tokens) => oauth::store_stored_tokens_keyring(name, tokens),
None => Ok(()),
},
};
stored.inspect_err(|_| keyring_store::delete_profile(name))
}
fn interactive_reauth_allowed() -> bool {
std::io::stdin().is_terminal()
&& std::io::stdout().is_terminal()
&& !crate::safety::is_agent_mode()
}
fn reject_os_store_in_keychain_sandbox(
profile_name: &str,
credential_storage: CredentialStorage,
managed: bool,
has_api_key_override: bool,
keychain: KeychainSandbox,
credential_hint: SandboxCredentialHint,
) -> Result<()> {
let needs_blocked_keychain = match keychain {
KeychainSandbox::Unrestricted => false,
KeychainSandbox::ReadOnly => managed && credential_storage == CredentialStorage::File,
KeychainSandbox::Denied => managed || credential_storage == CredentialStorage::OsStore,
};
if !has_api_key_override && needs_blocked_keychain {
let remediation = if managed {
match credential_hint {
SandboxCredentialHint::DefaultProfile => {
"Set CX_API_KEY or pass --api-key, or run outside the sandbox."
}
SandboxCredentialHint::ExplicitSingleProfile => {
"Pass --api-key explicitly, or run outside the sandbox."
}
SandboxCredentialHint::ExplicitMultipleProfiles => "Run outside the sandbox.",
SandboxCredentialHint::OAuthRefresh => {
"Run `cx profiles refresh` outside the sandbox."
}
}
} else {
match credential_hint {
SandboxCredentialHint::DefaultProfile => {
"Set CX_API_KEY or pass --api-key, or configure file credential storage outside \
the sandbox."
}
SandboxCredentialHint::ExplicitSingleProfile => {
"Pass --api-key explicitly, or configure file credential storage outside the \
sandbox."
}
SandboxCredentialHint::ExplicitMultipleProfiles => {
"Configure file credential storage for each selected profile outside the sandbox."
}
SandboxCredentialHint::OAuthRefresh => {
"Run `cx profiles refresh` outside the sandbox, or reconfigure \
the profile with file credential storage outside the sandbox."
}
}
};
bail!(
"Profile '{profile_name}' requires the OS credential store, which is not accessed \
in this macOS sandbox to avoid a Keychain prompt. {remediation}"
);
}
Ok(())
}
fn reject_oauth_refresh_in_keychain_sandbox(
profile_name: &str,
credential_storage: CredentialStorage,
managed: bool,
keychain_sandboxed: bool,
) -> Result<()> {
let keychain = if keychain_sandboxed {
KeychainSandbox::Denied
} else {
KeychainSandbox::Unrestricted
};
reject_os_store_in_keychain_sandbox(
profile_name,
credential_storage,
managed,
false,
keychain,
SandboxCredentialHint::OAuthRefresh,
)
}
fn os_store_refresh_blocked_error(
profile_name: &str,
credential_hint: SandboxCredentialHint,
) -> anyhow::Error {
let alternative = match credential_hint {
SandboxCredentialHint::DefaultProfile => ", or set CX_API_KEY or pass --api-key",
SandboxCredentialHint::ExplicitSingleProfile => ", or pass --api-key explicitly",
SandboxCredentialHint::ExplicitMultipleProfiles | SandboxCredentialHint::OAuthRefresh => "",
};
anyhow::anyhow!(
"The OAuth session of profile '{profile_name}' has expired or is missing, and new tokens \
would be saved to the OS credential store, which is not written in this macOS sandbox \
to avoid a Keychain prompt. Run `cx profiles refresh {profile_name}` outside the \
sandbox{alternative}."
)
}
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(),
}
}
pub(crate) 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> {
let managed = crate::managed_policy::requires_os_store()?;
keep_signed_in_tokens_with(
profile_name,
profile,
tokens,
managed,
oauth::store_tokens_keyring,
)
}
fn keep_signed_in_tokens_with(
profile_name: &str,
profile: &mut Profile,
tokens: &oauth::TokenResponse,
managed: bool,
store: impl FnOnce(&str, &oauth::TokenResponse) -> Result<()>,
) -> Result<String> {
if managed {
profile.credential_storage = CredentialStorage::OsStore;
profile.oauth_tokens = None;
}
if profile.credential_storage == CredentialStorage::OsStore {
match store(profile_name, tokens) {
Ok(()) => return Ok(tokens.access_token.clone()),
Err(err) => {
keyring_store::delete_profile(profile_name);
if managed {
anyhow::bail!(
"Failed to store OAuth tokens in the OS credential store ({err}). \
File credential storage is disabled by your organization's policy."
);
}
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."
);
}
reject_oauth_refresh_in_keychain_sandbox(
profile_name,
profile.credential_storage,
crate::managed_policy::requires_os_store()?,
crate::safety::is_macos_keychain_sandboxed(),
)?;
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> {
resolve_single_with_credential_hint(
profile_name,
api_key_override,
region_override,
SandboxCredentialHint::DefaultProfile,
)
.await
}
async fn resolve_single_with_credential_hint(
profile_name: &str,
api_key_override: Option<&str>,
region_override: Option<&str>,
credential_hint: SandboxCredentialHint,
) -> 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 managed = crate::managed_policy::requires_os_store()?;
let keychain = crate::safety::macos_keychain_sandbox();
reject_os_store_in_keychain_sandbox(
profile_name,
profile.credential_storage,
managed,
api_key_override.is_some(),
keychain,
credential_hint,
)?;
if managed && api_key_override.is_none() {
migrate_profile_to_os_store(profile_name, &mut profile).with_context(|| {
format!(
"File credential storage is disabled by your organization's policy. Replace \
the profile with `cx profiles add {profile_name} --force`, or remove it with \
`cx profiles delete {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(),
keychain.allows_writes(),
)
.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_os_store_refresh_blocked(&error) => {
return Err(os_store_refresh_blocked_error(
profile_name,
credential_hint,
));
}
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 {
keep_refreshed_tokens(
&mut profile,
new_tokens,
os_store_fallback_reason.as_deref(),
managed,
)
.inspect_err(|_| keyring_store::delete_profile(profile_name))?;
}
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."
);
}
}
if profile.cached_team_id.is_none() && !region_overridden {
if let Some(whoami) =
crate::identity::lookup_whoami_bounded(profile.region.api_endpoint(), &bearer)
.await
{
cache_team_identity(profile_name, &whoami);
}
}
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(),
})
}
fn keep_refreshed_tokens(
profile: &mut Profile,
tokens: StoredOAuthTokens,
os_store_error: Option<&str>,
managed: bool,
) -> Result<()> {
if let Some(err) = os_store_error {
if managed {
anyhow::bail!(
"Failed to store refreshed OAuth tokens in the OS credential store ({err}). \
File credential storage is disabled by your organization's policy."
);
}
profile.credential_storage = CredentialStorage::File;
}
profile.oauth_tokens = Some(tokens);
Ok(())
}
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>> {
resolve_all_with_credential_hint(
profiles,
api_key_override,
region_override,
SandboxCredentialHint::DefaultProfile,
)
.await
}
pub async fn resolve_all_with_credential_hint(
profiles: &[String],
api_key_override: Option<&str>,
region_override: Option<&str>,
credential_hint: SandboxCredentialHint,
) -> Result<Vec<ResolvedConfig>> {
if profiles.is_empty() {
let cfg = load_config()?;
return Ok(vec![
resolve_single_with_credential_hint(
&cfg.default_profile,
api_key_override,
region_override,
credential_hint,
)
.await?,
]);
}
let mut results = Vec::with_capacity(profiles.len());
for name in profiles {
results.push(
resolve_single_with_credential_hint(
name,
api_key_override,
region_override,
credential_hint,
)
.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 keychain_sandbox_rejects_os_store_before_keychain_access() {
let err = reject_os_store_in_keychain_sandbox(
"sandbox-test",
CredentialStorage::OsStore,
false,
false,
KeychainSandbox::Denied,
SandboxCredentialHint::DefaultProfile,
)
.unwrap_err();
assert!(
err.to_string().contains("Keychain prompt"),
"unexpected error: {err}"
);
}
#[test]
fn keychain_sandbox_error_matches_profile_selection() {
let error_for = |hint| {
reject_os_store_in_keychain_sandbox(
"sandbox-test",
CredentialStorage::OsStore,
false,
false,
KeychainSandbox::Denied,
hint,
)
.unwrap_err()
.to_string()
};
assert!(error_for(SandboxCredentialHint::DefaultProfile).contains("CX_API_KEY"));
assert!(error_for(SandboxCredentialHint::ExplicitSingleProfile).contains("Pass --api-key"));
let multi = error_for(SandboxCredentialHint::ExplicitMultipleProfiles);
assert!(
multi.contains("each selected profile"),
"unexpected error: {multi}"
);
assert!(
!multi.contains("Pass --api-key"),
"unexpected error: {multi}"
);
}
#[test]
fn managed_keychain_sandbox_error_does_not_recommend_file_storage() {
let error_for = |hint| {
reject_os_store_in_keychain_sandbox(
"managed-profile",
CredentialStorage::OsStore,
true,
false,
KeychainSandbox::Denied,
hint,
)
.unwrap_err()
.to_string()
};
let default = error_for(SandboxCredentialHint::DefaultProfile);
assert!(
default.contains("CX_API_KEY")
&& default.contains("pass --api-key")
&& default.contains("run outside the sandbox")
&& !default.contains("file credential storage"),
"unexpected error: {default}"
);
let explicit = error_for(SandboxCredentialHint::ExplicitSingleProfile);
assert!(
explicit.contains("Pass --api-key explicitly")
&& !explicit.contains("file credential storage"),
"unexpected error: {explicit}"
);
let multi = error_for(SandboxCredentialHint::ExplicitMultipleProfiles);
assert!(
multi.contains("Run outside the sandbox")
&& !multi.contains("--api-key")
&& !multi.contains("file credential storage"),
"unexpected error: {multi}"
);
let refresh = error_for(SandboxCredentialHint::OAuthRefresh);
assert!(
refresh.contains("Run `cx profiles refresh` outside the sandbox")
&& !refresh.contains("file credential storage"),
"unexpected error: {refresh}"
);
}
#[test]
fn keychain_sandbox_allows_file_storage_and_api_key_overrides() {
assert!(reject_os_store_in_keychain_sandbox(
"file-profile",
CredentialStorage::File,
false,
false,
KeychainSandbox::Denied,
SandboxCredentialHint::DefaultProfile,
)
.is_ok());
assert!(reject_os_store_in_keychain_sandbox(
"override-profile",
CredentialStorage::OsStore,
false,
true,
KeychainSandbox::Denied,
SandboxCredentialHint::DefaultProfile,
)
.is_ok());
}
#[test]
fn keychain_sandbox_rejects_managed_file_profile_before_migration() {
for keychain in [KeychainSandbox::Denied, KeychainSandbox::ReadOnly] {
let err = reject_os_store_in_keychain_sandbox(
"managed-profile",
CredentialStorage::File,
true,
false,
keychain,
SandboxCredentialHint::DefaultProfile,
)
.unwrap_err();
assert!(
err.to_string().contains("OS credential store"),
"unexpected error for {keychain:?}: {err}"
);
}
}
#[test]
fn read_only_keychain_keeps_stored_credentials_readable() {
for (storage, managed) in [
(CredentialStorage::OsStore, false),
(CredentialStorage::OsStore, true),
(CredentialStorage::File, false),
] {
assert!(
reject_os_store_in_keychain_sandbox(
"read-only-profile",
storage,
managed,
false,
KeychainSandbox::ReadOnly,
SandboxCredentialHint::DefaultProfile,
)
.is_ok(),
"{storage:?} (managed: {managed}) must stay readable"
);
}
}
#[test]
fn os_store_refresh_blocked_error_matches_profile_selection() {
let error_for = |hint| os_store_refresh_blocked_error("oauth-profile", hint).to_string();
let default = error_for(SandboxCredentialHint::DefaultProfile);
assert!(
default.contains("Run `cx profiles refresh oauth-profile` outside the sandbox")
&& default.contains("CX_API_KEY"),
"unexpected error: {default}"
);
assert!(error_for(SandboxCredentialHint::ExplicitSingleProfile)
.contains("pass --api-key explicitly"));
let multi = error_for(SandboxCredentialHint::ExplicitMultipleProfiles);
assert!(!multi.contains("--api-key"), "unexpected error: {multi}");
}
#[test]
fn oauth_refresh_is_rejected_before_keychain_access_in_a_sandbox() {
let err = reject_oauth_refresh_in_keychain_sandbox(
"oauth-profile",
CredentialStorage::OsStore,
false,
true,
)
.unwrap_err();
assert!(
err.to_string()
.contains("Run `cx profiles refresh` outside the sandbox"),
"unexpected error: {err}"
);
assert!(
!err.to_string().contains("--api-key"),
"unexpected error: {err}"
);
assert!(reject_oauth_refresh_in_keychain_sandbox(
"file-profile",
CredentialStorage::File,
false,
true,
)
.is_ok());
}
#[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.labels.is_empty());
assert!(p.oauth_client_id.is_none());
assert!(p.oauth_base_url.is_none());
}
fn assert_no_legacy_label_key(toml_text: &str) {
assert!(
toml_text.lines().all(|line| {
let trimmed = line.trim_start();
!trimmed.starts_with("label ") && !trimmed.starts_with("label=")
}),
"legacy label key should not be written, got: {toml_text}"
);
}
fn profile_with_labels(labels: Vec<String>) -> Profile {
Profile {
auth: AuthKind::ApiKey,
credential_storage: CredentialStorage::File,
api_key: None,
region: Region::Eu1,
labels,
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
read_only: false,
console_url: None,
cached_console_url: None,
cached_console_url_at: None,
cached_team_id: None,
cached_team_name: None,
}
}
#[test]
fn normalize_labels_trims_drops_empties_and_duplicates() {
assert_eq!(
normalize_labels([" prod ", "", "prod", "eu", " eu ", " "]),
vec!["prod".to_string(), "eu".to_string()]
);
assert_eq!(
normalize_labels(["Prod", "prod"]),
vec!["Prod".to_string(), "prod".to_string()]
);
}
#[test]
fn parse_label_args_splits_commas_and_repeated_flags() {
assert_eq!(
parse_label_args([" prod, eu ", "eu", " staging ", ",", "prod"]),
vec!["prod".to_string(), "eu".to_string(), "staging".to_string()]
);
assert!(parse_label_args(["", " ", ","]).is_empty());
}
fn labelled(name: &str, labels: &[&str]) -> (String, Vec<String>) {
(
name.to_string(),
labels.iter().map(|l| l.to_string()).collect(),
)
}
fn strings(values: &[&str]) -> Vec<String> {
values.iter().map(|v| v.to_string()).collect()
}
#[test]
fn has_any_label_is_exact_and_any_match() {
let labels = strings(&["prod", "eu"]);
assert!(has_any_label(&labels, &strings(&["eu"])));
assert!(has_any_label(&labels, &strings(&["missing", "prod"])));
assert!(!has_any_label(&labels, &strings(&["PROD"])));
assert!(!has_any_label(&labels, &strings(&["pro"])));
assert!(!has_any_label(&labels, &[]));
assert!(!has_any_label(&[], &strings(&["prod"])));
}
#[test]
fn names_with_any_label_keeps_list_order_and_skips_unlabelled() {
let entries = vec![
labelled("a", &["prod", "eu"]),
labelled("b", &[]),
labelled("c", &["staging"]),
labelled("d", &["prod"]),
];
assert_eq!(
names_with_any_label(&entries, &strings(&["prod"])),
strings(&["a", "d"])
);
assert_eq!(
names_with_any_label(&entries, &strings(&["staging", "eu"])),
strings(&["a", "c"])
);
assert!(names_with_any_label(&entries, &strings(&["qa"])).is_empty());
}
#[test]
fn no_profiles_for_labels_message_lists_every_label() {
assert_eq!(
no_profiles_for_labels(&strings(&["prod"])),
"No profiles with label 'prod'."
);
assert_eq!(
no_profiles_for_labels(&strings(&["a", "b", "c"])),
"No profiles with label 'a', 'b' or 'c'."
);
}
#[test]
fn parse_given_label_args_rejects_only_a_given_but_empty_list() {
assert_eq!(
parse_given_label_args::<&str>(&[]).unwrap(),
Vec::<String>::new()
);
assert_eq!(parse_given_label_args(&["a,b"]).unwrap(), vec!["a", "b"]);
for raw in [vec![""], vec![","], vec![" ", ""]] {
let err = parse_given_label_args(&raw).unwrap_err().to_string();
assert!(err.contains("non-empty label"), "{raw:?}: {err}");
}
}
#[test]
fn select_profile_names_without_labels_returns_explicit_names_unchanged() {
assert_eq!(
select_profile_names(&strings(&["b", "a"]), &[]).unwrap(),
strings(&["b", "a"])
);
assert!(select_profile_names(&[], &[]).unwrap().is_empty());
}
#[test]
fn legacy_label_string_loads_as_one_item_list() {
let profile: Profile = toml::from_str("region = \"eu1\"\nlabel = \" prod \"\n").unwrap();
assert_eq!(profile.labels, vec!["prod".to_string()]);
}
#[test]
fn legacy_label_string_is_not_split_on_commas() {
let profile: Profile = toml::from_str("region = \"eu1\"\nlabel = \"prod,eu\"\n").unwrap();
assert_eq!(profile.labels, vec!["prod,eu".to_string()]);
}
#[test]
fn legacy_blank_label_loads_as_no_labels() {
let profile: Profile = toml::from_str("region = \"eu1\"\nlabel = \" \"\n").unwrap();
assert!(profile.labels.is_empty());
}
#[test]
fn labels_array_preserves_order_and_normalizes_on_load() {
let toml_text = r#"
region = "eu1"
labels = [" eu ", "prod", "eu", "", "staging"]
"#;
let profile: Profile = toml::from_str(toml_text).unwrap();
assert_eq!(
profile.labels,
vec!["eu".to_string(), "prod".to_string(), "staging".to_string()]
);
}
#[test]
fn labels_array_wins_over_legacy_label_unless_empty() {
let both: Profile =
toml::from_str("region = \"eu1\"\nlabel = \"old\"\nlabels = [\"prod\", \"eu\"]\n")
.unwrap();
assert_eq!(both.labels, vec!["prod".to_string(), "eu".to_string()]);
let empty_array: Profile =
toml::from_str("region = \"eu1\"\nlabel = \"old\"\nlabels = []\n").unwrap();
assert_eq!(empty_array.labels, vec!["old".to_string()]);
}
#[test]
fn labels_round_trip_writes_labels_key_only() {
let profile = profile_with_labels(vec!["prod".to_string(), "eu".to_string()]);
let toml_text = toml::to_string_pretty(&profile).unwrap();
assert!(
toml_text.contains("labels"),
"expected labels key, got: {toml_text}"
);
assert_no_legacy_label_key(&toml_text);
let restored: Profile = toml::from_str(&toml_text).unwrap();
assert_eq!(restored.labels, vec!["prod".to_string(), "eu".to_string()]);
}
#[test]
fn empty_labels_are_omitted_when_writing() {
let toml_text = toml::to_string_pretty(&profile_with_labels(Vec::new())).unwrap();
assert!(
!toml_text.contains("label"),
"empty labels should be omitted, got: {toml_text}"
);
}
#[test]
fn resave_preserves_legacy_label_values() {
let loaded: Profile = toml::from_str("region = \"eu1\"\nlabel = \"prod\"\n").unwrap();
assert_eq!(loaded.labels, vec!["prod".to_string()]);
let written = toml::to_string_pretty(&loaded).unwrap();
assert_no_legacy_label_key(&written);
let again: Profile = toml::from_str(&written).unwrap();
assert_eq!(again.labels, vec!["prod".to_string()]);
}
#[test]
fn oauth_profile_round_trips() {
let profile = Profile {
auth: AuthKind::OAuth,
credential_storage: CredentialStorage::OsStore,
api_key: None,
region: Region::Eu2,
labels: vec!["prod".to_string()],
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
read_only: true,
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_eq!(restored.labels, vec!["prod".to_string()]);
assert!(restored.read_only);
assert!(restored.oauth_client_id.is_none());
assert!(restored.oauth_tokens.is_none());
}
#[test]
fn invalid_profile_read_only_value_is_ignored() {
let profile: Profile =
toml::from_str("region = \"eu1\"\nread_only = \"yes\"\n").expect("valid TOML");
assert!(!profile.read_only);
}
#[test]
fn oauth_profile_file_storage_round_trips() {
let profile = Profile {
auth: AuthKind::OAuth,
credential_storage: CredentialStorage::File,
api_key: None,
region: Region::Eu2,
labels: vec!["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,
read_only: false,
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()),
labels: Vec::new(),
oauth_client_id: Some("abc-123".to_string()),
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
read_only: false,
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,
labels: Vec::new(),
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
read_only: false,
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,
labels: Vec::new(),
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
read_only: false,
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,
labels: Vec::new(),
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
read_only: false,
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,
labels: Vec::new(),
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
read_only: false,
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,
labels: Vec::new(),
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
read_only: false,
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,
labels: Vec::new(),
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
read_only: false,
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());
}
fn stored_tokens(access_token: &str) -> StoredOAuthTokens {
StoredOAuthTokens {
access_token: access_token.to_string(),
refresh_token: Some("refresh".to_string()),
id_token: None,
expiry: Some(1_900_000_000),
}
}
fn token_response(access_token: &str) -> oauth::TokenResponse {
oauth::TokenResponse {
access_token: access_token.to_string(),
token_type: "Bearer".to_string(),
expires_in: Some(3600),
refresh_token: Some("refresh".to_string()),
id_token: None,
scope: None,
}
}
#[test]
fn migration_stores_the_api_key_before_saving_the_profile() {
let events = std::cell::RefCell::new(Vec::new());
let mut profile = profile_with_labels(Vec::new());
profile.api_key = Some("key".to_string());
let migrated = migrate_profile_with(
"p",
&mut profile,
|name, profile| {
events
.borrow_mut()
.push(format!("store {name} {:?}", profile.api_key));
Ok(())
},
|name, profile| {
events.borrow_mut().push(format!(
"save {name} {:?} {:?}",
profile.credential_storage, profile.api_key
));
Ok(())
},
)
.expect("migration succeeds");
assert!(migrated);
assert_eq!(
events.into_inner(),
["store p Some(\"key\")", "save p OsStore None"]
);
}
#[test]
fn migration_hands_oauth_tokens_to_the_store_unchanged() {
let mut profile = profile_with_labels(Vec::new());
profile.auth = AuthKind::OAuth;
profile.oauth_tokens = Some(stored_tokens("access"));
let mut stored = None;
let mut saved = None;
migrate_profile_with(
"p",
&mut profile,
|_, profile| {
stored = profile.oauth_tokens.clone();
Ok(())
},
|_, profile| {
saved = Some(profile.clone());
Ok(())
},
)
.expect("migration succeeds");
assert_eq!(stored, Some(stored_tokens("access")));
let saved = saved.expect("profile saved");
assert_eq!(saved.credential_storage, CredentialStorage::OsStore);
assert_eq!(saved.oauth_tokens, None);
}
#[test]
fn failed_migration_leaves_the_profile_file_alone() {
let mut profile = profile_with_labels(Vec::new());
profile.api_key = Some("key".to_string());
let mut saved = false;
let err = migrate_profile_with(
"p",
&mut profile,
|_, _| Err(anyhow::anyhow!("keychain locked")),
|_, _| {
saved = true;
Ok(())
},
)
.expect_err("store failure is reported");
assert!(format!("{err:#}").contains("keychain locked"), "{err:#}");
assert!(!saved);
assert_eq!(profile.credential_storage, CredentialStorage::File);
assert_eq!(profile.api_key.as_deref(), Some("key"));
}
#[test]
fn migration_skips_profiles_already_in_the_os_store() {
let mut profile = profile_with_labels(Vec::new());
profile.credential_storage = CredentialStorage::OsStore;
let migrated = migrate_profile_with(
"p",
&mut profile,
|_, _| panic!("nothing to store"),
|_, _| panic!("nothing to save"),
)
.expect("nothing to migrate");
assert!(!migrated);
}
#[test]
fn migration_drops_stray_plaintext_from_os_store_profiles() {
let mut profile = profile_with_labels(Vec::new());
profile.credential_storage = CredentialStorage::OsStore;
profile.api_key = Some("stale".to_string());
let mut saved_without_key = false;
let migrated = migrate_profile_with(
"p",
&mut profile,
|_, _| panic!("the OS store already holds this profile's secret"),
|_, profile| {
saved_without_key = profile.api_key.is_none();
Ok(())
},
)
.expect("plaintext dropped");
assert!(migrated);
assert!(saved_without_key);
}
#[test]
fn managed_sign_in_moves_a_file_profile_to_the_os_store() {
let mut profile = profile_with_labels(Vec::new());
profile.auth = AuthKind::OAuth;
profile.oauth_tokens = Some(stored_tokens("old"));
let access_token =
keep_signed_in_tokens_with("p", &mut profile, &token_response("new"), true, |_, _| {
Ok(())
})
.expect("stored in the OS store");
assert_eq!(access_token, "new");
assert_eq!(profile.credential_storage, CredentialStorage::OsStore);
assert_eq!(profile.oauth_tokens, None);
}
#[test]
fn managed_sign_in_fails_instead_of_falling_back_to_file() {
let mut profile = profile_with_labels(Vec::new());
profile.auth = AuthKind::OAuth;
let err = keep_signed_in_tokens_with(
"cx_test_managed_sign_in",
&mut profile,
&token_response("new"),
true,
|_, _| Err(anyhow::anyhow!("keychain locked")),
)
.expect_err("policy forbids the file fallback");
assert!(err.to_string().contains("keychain locked"), "{err}");
assert_eq!(profile.oauth_tokens, None);
}
#[test]
fn unmanaged_sign_in_falls_back_to_file_when_the_os_store_fails() {
let mut profile = profile_with_labels(Vec::new());
profile.auth = AuthKind::OAuth;
profile.credential_storage = CredentialStorage::OsStore;
keep_signed_in_tokens_with(
"cx_test_unmanaged_sign_in",
&mut profile,
&token_response("new"),
false,
|_, _| Err(anyhow::anyhow!("keychain locked")),
)
.expect("falls back to file");
assert_eq!(profile.credential_storage, CredentialStorage::File);
assert_eq!(
profile.oauth_tokens.map(|tokens| tokens.access_token),
Some("new".to_string())
);
}
#[test]
fn managed_refresh_fails_instead_of_writing_tokens_to_file() {
let mut profile = profile_with_labels(Vec::new());
profile.credential_storage = CredentialStorage::OsStore;
let err = keep_refreshed_tokens(
&mut profile,
stored_tokens("new"),
Some("keychain locked"),
true,
)
.expect_err("policy forbids the file fallback");
assert!(err.to_string().contains("keychain locked"), "{err}");
assert_eq!(profile.credential_storage, CredentialStorage::OsStore);
assert_eq!(profile.oauth_tokens, None);
}
#[test]
fn unmanaged_refresh_falls_back_to_file_when_the_os_store_fails() {
let mut profile = profile_with_labels(Vec::new());
profile.credential_storage = CredentialStorage::OsStore;
keep_refreshed_tokens(
&mut profile,
stored_tokens("new"),
Some("keychain locked"),
false,
)
.expect("falls back to file");
assert_eq!(profile.credential_storage, CredentialStorage::File);
assert_eq!(profile.oauth_tokens, Some(stored_tokens("new")));
}
#[test]
fn file_profile_refresh_keeps_tokens_on_the_profile() {
let mut profile = profile_with_labels(Vec::new());
keep_refreshed_tokens(&mut profile, stored_tokens("new"), None, false)
.expect("file profile refresh");
assert_eq!(profile.credential_storage, CredentialStorage::File);
assert_eq!(profile.oauth_tokens, Some(stored_tokens("new")));
}
#[test]
fn unmanaged_profile_migration_does_not_list_profiles() {
let result = migrate_managed_profiles_with(
false,
|| false,
|| Err(anyhow::anyhow!("profile listing must not run")),
|_| Ok(()),
);
assert!(result.is_ok());
}
#[test]
fn managed_profile_migration_is_skipped_when_keychain_writes_are_blocked() {
let result = migrate_managed_profiles_with(
true,
|| true,
|| Err(anyhow::anyhow!("profile listing must not run")),
|_| Ok(()),
);
assert!(result.is_ok());
}
#[test]
fn managed_profile_migration_warns_and_continues_after_a_failed_profile() {
let migrated = std::cell::RefCell::new(Vec::new());
migrate_managed_profiles_with(
true,
|| false,
|| Ok(vec!["broken".into(), "working".into()]),
|name| {
migrated.borrow_mut().push(name.to_owned());
if name == "broken" {
anyhow::bail!("invalid profile")
}
Ok(())
},
)
.expect("one broken profile must not stop migration");
assert_eq!(*migrated.borrow(), vec!["broken", "working"]);
}
}