use std::io::IsTerminal;
#[cfg(any(target_os = "macos", test))]
use anyhow::Context;
use anyhow::Result;
use inquire::{Confirm, Password, PasswordDisplayMode, Select, Text};
use crate::config::{
has_managed_completions, list_profile_names, load_config, load_profile, profile_file,
save_config, save_profile, AuthKind, CredentialStorage, OutputFormat, Profile, Region,
};
use crate::keyring_store;
use crate::oauth;
use crate::region::{region_from_url, RegionMatch};
const AUTH_METHODS: &[&str] = &["OAuth (browser login)", "API key (paste manually)"];
#[cfg(any(target_os = "macos", test))]
const API_KEY_SECRET: &str = "api_key";
#[cfg(any(target_os = "macos", test))]
const OAUTH_SECRETS: &[&str] = &[
"oauth_access_token",
"oauth_refresh_token",
"oauth_id_token",
"oauth_token_expiry",
];
const CUSTOM_ENDPOINT_OPTION: &str = "Custom endpoint (BYOC / private link)";
const PICKER_REGIONS: &[Region] = &[
Region::Us1,
Region::Us2,
Region::Us3,
Region::Eu1,
Region::Eu2,
Region::Ap1,
Region::Ap2,
Region::Ap3,
];
const REGION_DEFAULT_CURSOR: usize = 4;
fn region_option_label(region: &Region) -> String {
match region.app_url_template() {
Some(template) => format!("({region}) {template}"),
None => region.to_string(),
}
}
fn region_picker_options() -> Vec<String> {
PICKER_REGIONS
.iter()
.map(region_option_label)
.chain([CUSTOM_ENDPOINT_OPTION.to_string()])
.collect()
}
fn is_picker_region(region: &Region) -> bool {
PICKER_REGIONS.iter().any(|r| r == region)
}
#[derive(Debug)]
enum RegionChoice {
Known(Region),
Custom { base_url: String },
}
const OUTPUT_FORMATS: &[&str] = &["text", "json", "toon"];
#[derive(Clone, Copy, PartialEq, Eq)]
enum OsStorePlatform {
LinuxMusl,
Macos { apple_signed: bool },
Windows,
Other,
}
fn current_os_store_platform() -> OsStorePlatform {
if cfg!(all(target_os = "linux", target_env = "musl")) {
OsStorePlatform::LinuxMusl
} else if cfg!(target_os = "macos") {
OsStorePlatform::Macos {
apple_signed: apple_developer_id(),
}
} else if cfg!(target_os = "windows") {
OsStorePlatform::Windows
} else {
OsStorePlatform::Other
}
}
fn apple_developer_id() -> bool {
#[cfg(target_os = "macos")]
{
crate::code_sign::has_apple_developer_id()
}
#[cfg(not(target_os = "macos"))]
{
false
}
}
fn os_store_offered_on(platform: OsStorePlatform) -> bool {
!matches!(platform, OsStorePlatform::LinuxMusl)
}
fn credential_storage_options_for(
platform: OsStorePlatform,
managed: bool,
keychain_sandboxed: bool,
) -> Vec<(&'static str, CredentialStorage)> {
if keychain_sandboxed {
return vec![("file", CredentialStorage::File)];
}
if managed {
return vec![("os-store (encrypted)", CredentialStorage::OsStore)];
}
let mut options = vec![("file", CredentialStorage::File)];
if os_store_offered_on(platform) {
options.push(("os-store (encrypted)", CredentialStorage::OsStore));
}
options
}
fn default_credential_storage(
platform: OsStorePlatform,
managed: bool,
keychain_sandboxed: bool,
) -> CredentialStorage {
if keychain_sandboxed {
return CredentialStorage::File;
}
if managed {
return CredentialStorage::OsStore;
}
if let Some(storage) = credential_storage_override() {
return storage;
}
match platform {
OsStorePlatform::Macos { .. } | OsStorePlatform::Windows => CredentialStorage::OsStore,
OsStorePlatform::LinuxMusl | OsStorePlatform::Other => CredentialStorage::File,
}
}
fn credential_storage_override() -> Option<CredentialStorage> {
credential_storage_override_from(std::env::var("CX_CREDENTIAL_STORAGE").ok().as_deref())
}
fn credential_storage_override_from(value: Option<&str>) -> Option<CredentialStorage> {
if value == Some("file") {
return Some(CredentialStorage::File);
}
None
}
fn reject_file_storage_override(managed: bool, value: Option<&str>) -> Result<()> {
if managed && credential_storage_override_from(value) == Some(CredentialStorage::File) {
anyhow::bail!(
"File credential storage is disabled by your organization's policy. \
Credentials must be stored in the OS credential store."
);
}
Ok(())
}
fn warn_invalid_credential_storage_override() {
if let Some(warning) = invalid_credential_storage_override_warning(
std::env::var("CX_CREDENTIAL_STORAGE").ok().as_deref(),
) {
eprintln!("{warning}");
}
}
fn invalid_credential_storage_override_warning(value: Option<&str>) -> Option<String> {
value.filter(|value| *value != "file").map(|value| {
format!("Warning: ignoring CX_CREDENTIAL_STORAGE={value:?}; only \"file\" is supported.")
})
}
fn credential_storage_cursor(
platform: OsStorePlatform,
managed: bool,
keychain_sandboxed: bool,
) -> usize {
let preferred = default_credential_storage(platform, managed, keychain_sandboxed);
credential_storage_options_for(platform, managed, keychain_sandboxed)
.iter()
.position(|(_, storage)| *storage == preferred)
.unwrap_or(0)
}
fn credential_storage_help_message(file_description: &str) -> String {
credential_storage_help(file_description, current_os_store_platform())
}
fn credential_storage_help(file_description: &str, platform: OsStorePlatform) -> String {
match platform {
OsStorePlatform::LinuxMusl => {
format!(
"Linux musl builds do not have an OS credential store. 'file' {file_description}"
)
}
OsStorePlatform::Macos {
apple_signed: false,
} => format!(
"'os-store' is preselected and stores the secret in the macOS Keychain via \
/usr/bin/security, so a Homebrew upgrade does not prompt again. Any process running \
as your user can read that secret through the same tool. 'file' {file_description} \
Falls back to file if the Keychain is unavailable."
),
OsStorePlatform::Macos { apple_signed: true } => format!(
"'os-store' is preselected and stores the secret in the macOS Keychain with an ACL \
tied to this Developer ID-signed cx. 'file' {file_description} Falls back to file \
if the Keychain is unavailable."
),
OsStorePlatform::Windows => format!(
"'os-store' is preselected and stores the secret in Windows Credential Manager. \
'file' {file_description} Falls back to file if Windows Credential Manager is \
unavailable."
),
OsStorePlatform::Other => format!(
"'file' is preselected and {file_description} 'os-store' uses the OS credential store \
(Linux Secret Service). Falls back to file if the OS store is unavailable."
),
}
}
fn select_credential_storage(
prompt: &str,
help_message: &str,
managed: bool,
keychain_sandboxed: bool,
) -> Result<CredentialStorage> {
if keychain_sandboxed {
return Ok(CredentialStorage::File);
}
if managed {
return Ok(CredentialStorage::OsStore);
}
if let Some(storage) = credential_storage_override() {
return Ok(storage);
}
let platform = current_os_store_platform();
let options = credential_storage_options_for(platform, managed, keychain_sandboxed);
let labels: Vec<&str> = options.iter().map(|(label, _)| *label).collect();
let cursor = credential_storage_cursor(platform, managed, keychain_sandboxed);
let chosen = Select::new(prompt, labels)
.with_help_message(help_message)
.with_starting_cursor(cursor)
.prompt()?;
Ok(options
.iter()
.find(|(label, _)| *label == chosen)
.map(|(_, storage)| *storage)
.expect("inquire returns one of the labels we passed in"))
}
fn recorded_credential_storage(name: &str) -> Option<CredentialStorage> {
let path = profile_file(name).ok()?;
if !path.exists() {
return None;
}
load_profile(name)
.ok()
.map(|profile| profile.credential_storage)
}
fn delete_os_store_secrets_if_recorded(name: &str) {
if recorded_credential_storage(name) == Some(CredentialStorage::OsStore) {
keyring_store::delete_profile(name);
}
}
fn refuse_os_store_profile_in_keychain_sandbox(name: &str, action: &str) -> Result<()> {
if os_store_profile_action_is_blocked(
recorded_credential_storage(name),
crate::safety::is_macos_keychain_sandboxed(),
) {
anyhow::bail!(
"Profile '{name}' stores credentials in the macOS Keychain and cannot be {action} \
in this sandbox. Reconfigure or delete it outside the sandbox."
);
}
Ok(())
}
fn os_store_profile_action_is_blocked(
credential_storage: Option<CredentialStorage>,
keychain_sandboxed: bool,
) -> bool {
keychain_sandboxed && credential_storage == Some(CredentialStorage::OsStore)
}
fn os_store_or_file_fallback<T>(
profile: &str,
store_result: Result<()>,
file_payload: T,
os_desc: &'static str,
file_desc: &'static str,
managed: bool,
) -> Result<(CredentialStorage, Option<T>, &'static str)> {
match store_result {
Ok(()) => Ok((CredentialStorage::OsStore, None, os_desc)),
Err(err) => {
keyring_store::delete_profile(profile);
if managed {
anyhow::bail!(
"The OS credential store is unavailable ({err}). File credential storage \
is disabled by your organization's policy; contact your IT administrator."
);
}
eprintln!(
"Warning: OS credential store unavailable ({err}); falling back to file storage."
);
Ok((CredentialStorage::File, Some(file_payload), file_desc))
}
}
}
fn select_region_interactive() -> Result<RegionChoice> {
let last_input = std::cell::RefCell::new(String::new());
let scorer = |input: &str, option: &String, string_value: &str, idx: usize| -> Option<i64> {
*last_input.borrow_mut() = input.to_string();
match region_from_url(input) {
RegionMatch::Known(region) if is_picker_region(®ion) => {
(region_option_label(®ion) == string_value).then_some(i64::MAX)
}
_ => {
if (input.contains("://") || input.contains('.'))
&& string_value == CUSTOM_ENDPOINT_OPTION
{
return Some(0);
}
(Select::<String>::DEFAULT_SCORER)(input, option, string_value, idx)
}
}
};
let choice = Select::new("Region / Coralogix URL:", region_picker_options())
.with_starting_cursor(REGION_DEFAULT_CURSOR)
.with_help_message("Enter your Coralogix URL to auto-detect the region, or type to filter.")
.with_scorer(&scorer)
.prompt()?;
if choice == CUSTOM_ENDPOINT_OPTION {
let typed = last_input.into_inner().trim().to_string();
if typed.contains("://") || typed.contains('.') {
return resolve_url_choice(&typed);
}
prompt_custom_endpoint()
} else {
let region = PICKER_REGIONS
.iter()
.find(|r| region_option_label(r) == choice)
.cloned()
.expect("inquire returns one of the labels we passed in");
Ok(RegionChoice::Known(region))
}
}
fn resolve_url_choice(raw: &str) -> Result<RegionChoice> {
match region_from_url(raw) {
RegionMatch::Known(region) if is_picker_region(®ion) => {
println!("Detected region: {region}");
Ok(RegionChoice::Known(region))
}
_ => match custom_base_url_from(raw) {
Some(base_url) => {
println!(
"Couldn't map that URL to a known region - \
using it as a custom endpoint: {base_url}"
);
Ok(RegionChoice::Custom { base_url })
}
None => {
println!(
"Couldn't map that URL to a known region - \
enter your API endpoint manually."
);
prompt_custom_endpoint()
}
},
}
}
fn custom_base_url_from(raw: &str) -> Option<String> {
let cleaned = raw.trim().trim_end_matches('/');
if cleaned.is_empty() {
return None;
}
let with_scheme = if cleaned.contains("://") {
cleaned.to_string()
} else {
format!("https://{cleaned}")
};
crate::region::extract_host(&with_scheme).map(|_| with_scheme)
}
fn prompt_custom_endpoint() -> Result<RegionChoice> {
use inquire::validator::Validation;
let raw_url = Text::new("Base URL (e.g. https://api.myenv.coralogix.com):")
.with_validator(|input: &str| {
if crate::region::extract_host(input).is_some() {
Ok(Validation::Valid)
} else {
Ok(Validation::Invalid(
"Enter a URL with a host, e.g. https://api.myenv.coralogix.com".into(),
))
}
})
.prompt()?;
let base_url = custom_base_url_from(&raw_url).expect("validator guarantees a parseable host");
Ok(RegionChoice::Custom { base_url })
}
fn parse_region_flag(raw: &str) -> Result<Region> {
let region: Region = raw.parse().expect("Region::from_str is infallible");
if matches!(region, Region::Custom(_)) {
anyhow::bail!(
"unknown region '{raw}' — expected one of us1, us2, us3, eu1, eu2, ap1, ap2, ap3, \
or pass --url with your Coralogix URL"
);
}
Ok(region)
}
fn resolve_region_flags(url: Option<&str>, region: Option<&str>) -> Result<Option<RegionChoice>> {
if let Some(raw) = region {
return Ok(Some(RegionChoice::Known(parse_region_flag(raw)?)));
}
let Some(raw) = url else {
return Ok(None);
};
match region_from_url(raw) {
RegionMatch::Known(region) if is_picker_region(®ion) => {
println!("Detected region: {region}");
Ok(Some(RegionChoice::Known(region)))
}
_ => {
if crate::region::extract_host(raw).is_none() {
anyhow::bail!(
"'--url {raw}' is not a valid URL — pass your Coralogix URL \
(e.g. https://myteam.app.eu2.coralogix.com) or use --region"
);
}
println!("Couldn't map '{raw}' to a known region — using it as a custom API endpoint.");
let base_url = raw.trim().trim_end_matches('/').to_string();
Ok(Some(RegionChoice::Custom { base_url }))
}
}
}
fn hint_completions_refresh() {
if has_managed_completions() {
println!(
"Tip: profile list changed - run `cx completions refresh` \
to update static completion scripts."
);
}
}
fn display_labels(labels: &[String]) -> String {
if labels.is_empty() {
"-".to_string()
} else {
labels.join(",")
}
}
pub fn run_list(label_filter: Vec<String>) -> Result<()> {
let filter = crate::config::parse_given_label_args(&label_filter)?;
let global_config = load_config().unwrap_or_default();
let names = list_profile_names()?;
let mut entries: Vec<(String, Profile)> = names
.into_iter()
.filter_map(|name| {
let profile = load_profile(&name).ok()?;
Some((name, profile))
})
.collect();
if entries.is_empty() {
println!("No profiles configured. Run `cx profiles add` to create one.");
return Ok(());
}
if !filter.is_empty() {
entries.retain(|(_, profile)| crate::config::has_any_label(&profile.labels, &filter));
if entries.is_empty() {
println!("{}", crate::config::no_profiles_for_labels(&filter));
return Ok(());
}
}
render_text_table(&entries, &global_config);
Ok(())
}
fn render_text_table(entries: &[(String, Profile)], global_config: &crate::config::Config) {
let name_w = entries
.iter()
.map(|(n, _)| n.len())
.max()
.unwrap_or(4)
.max(4);
let label_w = entries
.iter()
.map(|(_, profile)| display_labels(&profile.labels).len())
.max()
.unwrap_or("LABEL".len())
.max("LABEL".len());
let region_w = entries
.iter()
.map(|(_, p)| p.region.to_string().len())
.max()
.unwrap_or(6)
.max(6);
let output_w = 6; let read_only_w = "READ ONLY".len();
println!(
"{:<name_w$} {:<label_w$} {:<region_w$} {:<8} {:<output_w$} {:<read_only_w$} DEFAULT",
"NAME",
"LABEL",
"REGION",
"AUTH",
"OUTPUT",
"READ ONLY",
name_w = name_w,
label_w = label_w,
region_w = region_w,
output_w = output_w,
read_only_w = read_only_w,
);
println!(
"{:<name_w$} {:<label_w$} {:<region_w$} {:<8} {:<output_w$} {:<read_only_w$} -------",
"-".repeat(name_w),
"-".repeat(label_w),
"-".repeat(region_w),
"--------",
"-".repeat(output_w),
"-".repeat(read_only_w),
name_w = name_w,
label_w = label_w,
region_w = region_w,
output_w = output_w,
read_only_w = read_only_w,
);
for (name, profile) in entries {
let label = display_labels(&profile.labels);
let region = profile.region.to_string();
let auth = match profile.auth {
AuthKind::OAuth => "oauth",
AuthKind::ApiKey => "api-key",
};
let output_fmt = profile
.default_output_format
.map(|f| f.as_str())
.unwrap_or("-");
let read_only = if profile.read_only { "yes" } else { "no" };
let is_default = if *name == global_config.default_profile {
"yes"
} else {
""
};
println!(
"{:<name_w$} {:<label_w$} {:<region_w$} {:<8} {:<output_w$} {:<read_only_w$} {}",
name,
label,
region,
auth,
output_fmt,
read_only,
is_default,
name_w = name_w,
label_w = label_w,
region_w = region_w,
output_w = output_w,
read_only_w = read_only_w,
);
}
}
pub struct AddArgs {
pub name: Option<String>,
pub url: Option<String>,
pub region: Option<String>,
pub api_key: Option<String>,
pub oauth: bool,
pub signup: bool,
pub force: bool,
pub set_default: bool,
pub disable_olly: bool,
pub quick: bool,
pub labels: Option<Vec<String>>,
}
fn resolve_profile_labels(
name: &str,
provided: Option<Vec<String>>,
interactive: bool,
quick: bool,
) -> Result<Vec<String>> {
if let Some(raw) = provided {
return crate::config::parse_given_label_args(&raw);
}
let existing = load_profile(name)
.ok()
.map(|profile| profile.labels)
.unwrap_or_default();
if !interactive || quick {
return Ok(existing);
}
let current = existing.join(",");
let mut prompt = Text::new("Labels (e.g. 'prod, eu'):")
.with_help_message("Comma-separated. Leave empty to keep the current labels.");
if !current.is_empty() {
prompt = prompt.with_default(¤t);
}
Ok(labels_from_prompt_answer(
&existing,
prompt.prompt_skippable()?.as_deref(),
))
}
fn labels_from_prompt_answer(existing: &[String], answer: Option<&str>) -> Vec<String> {
let current = existing.join(",");
match answer {
Some(text) if !text.trim().is_empty() && text.trim() != current => {
crate::config::parse_label_args([text])
}
_ => existing.to_vec(),
}
}
pub async fn run_add(args: AddArgs) -> Result<()> {
let AddArgs {
name,
url,
region,
api_key,
oauth,
signup,
force,
set_default,
disable_olly,
quick,
labels,
} = args;
let oauth = oauth || signup;
let managed = crate::managed_policy::requires_os_store()?;
let keychain_sandboxed = crate::safety::is_macos_keychain_sandboxed();
if managed && keychain_sandboxed {
anyhow::bail!(
"Your organization's policy requires the OS credential store, which is not \
accessed in this macOS sandbox. Configure this profile outside the sandbox."
);
}
reject_file_storage_override(
managed,
std::env::var("CX_CREDENTIAL_STORAGE").ok().as_deref(),
)?;
warn_invalid_credential_storage_override();
let api_key = api_key.filter(|k| !k.trim().is_empty()).filter(|_| !oauth);
let region_choice = resolve_region_flags(url.as_deref(), region.as_deref())?;
let fully_specified = api_key.is_some() && region_choice.is_some();
let interactive = std::io::stdin().is_terminal() && !fully_specified;
let is_first_profile = list_profile_names()?.is_empty();
let name = match name {
Some(n) => {
if n.is_empty() {
anyhow::bail!("Profile name cannot be empty.");
}
n
}
None if interactive => {
let mut prompt = Text::new("Profile name:")
.with_help_message("A short identifier for this profile, e.g. 'prod' or 'staging'.")
.with_validator(inquire::validator::MinLengthValidator::new(1));
if is_first_profile {
prompt = prompt.with_default("default");
}
prompt.prompt()?
}
None => "default".to_string(),
};
let existing_read_only = load_profile(&name).ok().map(|profile| profile.read_only);
refuse_os_store_profile_in_keychain_sandbox(&name, "reconfigured")?;
if profile_file(&name)?.exists() && !force {
if interactive {
let confirmed = Confirm::new(&format!("Reconfigure profile '{name}'?"))
.with_default(false)
.with_help_message("The profile already exists; reconfiguring replaces it.")
.prompt()?;
if !confirmed {
println!("Cancelled.");
return Ok(());
}
} else {
anyhow::bail!("profile '{name}' already exists — pass --force to overwrite");
}
}
println!("Configuring profile '{name}'\n");
let (mut profile, storage_desc) = if oauth {
configure_oauth(
&name,
region_choice,
interactive,
signup,
managed,
keychain_sandboxed,
)
.await?
} else if !interactive {
build_profile_non_interactive(&name, api_key, region_choice, managed, keychain_sandboxed)?
} else if api_key.is_some() {
configure_api_key(&name, api_key, region_choice, managed, keychain_sandboxed)?
} else {
let auth_choice = Select::new("Authentication method:", AUTH_METHODS.to_vec())
.with_starting_cursor(0) .with_help_message(
"OAuth opens your browser for secure login. \
API key lets you paste credentials directly \
(must be a Team Key or Personal Key - not a Send-Your-Data key).",
)
.prompt()?;
if auth_choice.starts_with("OAuth") {
configure_oauth(
&name,
region_choice,
interactive,
signup,
managed,
keychain_sandboxed,
)
.await?
} else {
configure_api_key(&name, None, region_choice, managed, keychain_sandboxed)?
}
};
profile.labels = resolve_profile_labels(&name, labels, interactive, quick)?;
profile.read_only = existing_read_only.unwrap_or(profile.read_only);
if quick {
profile.default_output_format = Some(OutputFormat::Json);
} else if interactive {
let global_config = load_config().unwrap_or_default();
let current_fmt = profile
.default_output_format
.unwrap_or(global_config.default_output_format);
let current_idx = OUTPUT_FORMATS
.iter()
.position(|&f| f == current_fmt.as_str())
.unwrap_or(0);
let format_str = Select::new("Default output format:", OUTPUT_FORMATS.to_vec())
.with_starting_cursor(current_idx)
.prompt()?;
profile.default_output_format = Some(match format_str {
"json" => OutputFormat::Json,
"toon" => OutputFormat::Toon,
_ => OutputFormat::Text,
});
}
save_profile(&name, &profile)?;
if is_first_profile {
let mut global_config = load_config().unwrap_or_default();
global_config.olly_enabled = !disable_olly;
global_config.default_profile = name.clone();
save_config(&global_config)?;
}
if !is_first_profile {
let mut global_config = load_config().unwrap_or_default();
let should_set_default = if set_default {
true
} else if interactive {
Confirm::new(&format!("Set '{name}' as the default profile?"))
.with_default(false)
.prompt()?
} else {
false
};
if should_set_default {
global_config.default_profile = name.clone();
save_config(&global_config)?;
}
}
report_onboarding(Some(&name)).await;
let cx_dir = crate::config::config_dir()?;
println!(
"\nProfile '{name}' saved to {}\nCredentials stored in {storage_desc}",
cx_dir.display()
);
hint_completions_refresh();
Ok(())
}
pub async fn report_onboarding(name: Option<&str>) {
let Ok(cfg) = crate::config::resolve(name, None, None).await else {
return;
};
let outcome = crate::onboarding::report(&cfg.profile_name, &cfg.endpoint, &cfg.api_key).await;
if outcome == Some(crate::onboarding::Outcome::Forbidden) {
let profile = match name {
Some(name) => name.to_string(),
None => load_config().unwrap_or_default().default_profile,
};
eprintln!(
"note: profile '{profile}' signs in with an API key, so this setup isn't linked \
to your Coralogix user. To link it, sign in as yourself with \
`cx profiles add {profile} --oauth --force`."
);
}
}
pub async fn run_refresh(profile_name: String) -> Result<()> {
if !profile_file(&profile_name)?.exists() {
anyhow::bail!(
"Profile '{profile_name}' not found. Run `cx profiles add {profile_name}` to set it up."
);
}
crate::config::refresh_oauth_profile(&profile_name).await
}
pub fn run_delete(profile_name: String, force: bool) -> Result<()> {
let path = profile_file(&profile_name)?;
if !path.exists() {
anyhow::bail!("Profile '{profile_name}' not found.");
}
refuse_os_store_profile_in_keychain_sandbox(&profile_name, "deleted")?;
let global_config = load_config().unwrap_or_default();
let is_default = profile_name == global_config.default_profile;
if !force {
let warning = if is_default {
format!(
"Delete profile '{profile_name}'? This is your default profile.\n\
All stored credentials will be removed."
)
} else {
format!(
"Delete profile '{profile_name}'?\n\
All stored credentials will be removed."
)
};
let confirmed = Confirm::new(&warning).with_default(false).prompt()?;
if !confirmed {
println!("Cancelled.");
return Ok(());
}
}
delete_os_store_secrets_if_recorded(&profile_name);
std::fs::remove_file(&path)?;
println!("Profile '{profile_name}' deleted.");
if is_default {
println!(
"Note: '{profile_name}' was your default profile. \
Run `cx profiles set-default <name>` to set a new default."
);
}
hint_completions_refresh();
Ok(())
}
#[cfg(target_os = "macos")]
pub fn run_migrate() -> Result<()> {
reject_keychain_migration_in_sandbox(crate::safety::is_macos_keychain_sandboxed())?;
let profiles = list_profile_names()?.into_iter().map(|name| {
let profile = load_profile(&name);
(name, profile)
});
let summary = run_migrate_with(profiles, recreate_os_store_secrets);
migration_result(summary)
}
#[cfg(any(target_os = "macos", test))]
fn reject_keychain_migration_in_sandbox(keychain_sandboxed: bool) -> Result<()> {
if keychain_sandboxed {
anyhow::bail!(
"`cx profiles migrate` cannot run in this macOS sandbox because it must access \
Keychain. Run it outside the sandbox."
);
}
Ok(())
}
#[cfg(any(target_os = "macos", test))]
#[derive(Debug, Default, PartialEq, Eq)]
struct MigrationSummary {
migrated: usize,
skipped: usize,
failed: usize,
}
#[cfg(any(target_os = "macos", test))]
fn run_migrate_with(
profiles: impl IntoIterator<Item = (String, Result<Profile>)>,
mut migrate: impl FnMut(&str, &Profile) -> Result<()>,
) -> MigrationSummary {
let mut summary = MigrationSummary::default();
for (name, profile) in profiles {
let profile = match profile {
Ok(profile) => profile,
Err(err) => {
eprintln!("Profile {name}: error: could not load: {err}");
summary.failed += 1;
continue;
}
};
if profile.credential_storage != CredentialStorage::OsStore {
eprintln!("Profile {name}: skipped (credentials are stored in the profile file).");
summary.skipped += 1;
continue;
}
match migrate(&name, &profile) {
Ok(()) => {
eprintln!("Profile {name}: migrated.");
summary.migrated += 1;
}
Err(err) => {
eprintln!("Profile {name}: error: could not migrate: {err}");
summary.failed += 1;
}
}
}
eprintln!(
"Migration complete: {} migrated, {} skipped, {} failed.",
summary.migrated, summary.skipped, summary.failed
);
summary
}
#[cfg(any(target_os = "macos", test))]
fn migration_result(summary: MigrationSummary) -> Result<()> {
if summary.failed > 0 {
anyhow::bail!("{} profile(s) failed to migrate", summary.failed);
}
Ok(())
}
#[cfg(target_os = "macos")]
fn recreate_os_store_secrets(name: &str, profile: &Profile) -> Result<()> {
let target = keyring_store::current_macos_backend();
migrate_profile_secrets(
name,
profile.auth,
&MacosProfileSecretMigrator {
profile_name: name,
target,
},
)
}
#[cfg(any(target_os = "macos", test))]
trait ProfileSecretMigrator {
fn read_source(&self, key_name: &str) -> Result<Option<String>>;
fn validate_target(&self, key_name: &str, value: &str) -> Result<()>;
fn delete_target(&self, key_name: &str) -> Result<()>;
fn store_target(&self, key_name: &str, value: &str) -> Result<()>;
fn read_target(&self, key_name: &str) -> Result<Option<String>>;
}
#[cfg(any(target_os = "macos", test))]
fn migrate_profile_secrets(
profile_name: &str,
auth: AuthKind,
migrator: &impl ProfileSecretMigrator,
) -> Result<()> {
let (required_secret, secret_names) = profile_secret_names(auth);
let mut secrets = Vec::new();
for key_name in secret_names {
let Some(value) = migrator.read_source(key_name)? else {
if *key_name == required_secret {
anyhow::bail!(
"required secret '{key_name}' was not found in either Keychain backend"
);
}
continue;
};
migrator.validate_target(key_name, &value)?;
secrets.push((*key_name, value));
}
for (key_name, value) in secrets {
migrator.delete_target(key_name)?;
store_and_verify_secret(profile_name, key_name, &value, migrator)?;
}
Ok(())
}
#[cfg(any(target_os = "macos", test))]
fn store_and_verify_secret(
profile_name: &str,
key_name: &str,
value: &str,
migrator: &impl ProfileSecretMigrator,
) -> Result<()> {
let first_failure = match migrator.store_target(key_name, value) {
Ok(()) => match verify_migrated_secret(key_name, value, migrator) {
Ok(()) => return Ok(()),
Err(err) => err,
},
Err(err) => err,
};
if let Err(retry_err) = migrator.store_target(key_name, value) {
anyhow::bail!(
"secret '{key_name}' was deleted but could not be restored \
(first attempt: {first_failure}; retry: {retry_err}). \
Reconfigure profile '{profile_name}' with `cx profiles add {profile_name} --force`."
);
}
verify_migrated_secret(key_name, value, migrator).with_context(|| {
format!(
"secret '{key_name}' was deleted and rewritten, but verification still failed; \
reconfigure profile '{profile_name}' with `cx profiles add {profile_name} --force`"
)
})
}
#[cfg(any(target_os = "macos", test))]
fn verify_migrated_secret(
key_name: &str,
expected: &str,
migrator: &impl ProfileSecretMigrator,
) -> Result<()> {
let actual = migrator.read_target(key_name)?.with_context(|| {
format!("secret '{key_name}' could not be read through the target backend")
})?;
if actual != expected {
anyhow::bail!("secret '{key_name}' did not match after rewriting it");
}
Ok(())
}
#[cfg(any(target_os = "macos", test))]
fn profile_secret_names(auth: AuthKind) -> (&'static str, &'static [&'static str]) {
match auth {
AuthKind::ApiKey => (API_KEY_SECRET, &[API_KEY_SECRET]),
AuthKind::OAuth => ("oauth_access_token", OAUTH_SECRETS),
}
}
#[cfg(target_os = "macos")]
struct MacosProfileSecretMigrator<'a> {
profile_name: &'a str,
target: keyring_store::MacosKeychainBackend,
}
#[cfg(target_os = "macos")]
impl ProfileSecretMigrator for MacosProfileSecretMigrator<'_> {
fn read_source(&self, key_name: &str) -> Result<Option<String>> {
read_macos_secret(self.profile_name, key_name, self.target)
}
fn validate_target(&self, key_name: &str, value: &str) -> Result<()> {
keyring_store::validate_secret_in_macos_backend(
self.profile_name,
key_name,
value,
self.target,
)
}
fn delete_target(&self, key_name: &str) -> Result<()> {
keyring_store::delete_secret_in_macos_backend(self.profile_name, key_name, self.target)
}
fn store_target(&self, key_name: &str, value: &str) -> Result<()> {
keyring_store::store_secret_in_macos_backend(
self.profile_name,
key_name,
value,
self.target,
)
}
fn read_target(&self, key_name: &str) -> Result<Option<String>> {
keyring_store::get_secret_from_macos_backend(self.profile_name, key_name, self.target)
}
}
#[cfg(target_os = "macos")]
fn read_macos_secret(
profile_name: &str,
key_name: &str,
target: keyring_store::MacosKeychainBackend,
) -> Result<Option<String>> {
let alternate = match target {
keyring_store::MacosKeychainBackend::NativeKeyring => {
keyring_store::MacosKeychainBackend::SecurityCli
}
keyring_store::MacosKeychainBackend::SecurityCli => {
keyring_store::MacosKeychainBackend::NativeKeyring
}
};
read_secret_with_fallback(
key_name,
keyring_store::get_secret_from_macos_backend(profile_name, key_name, target),
|| keyring_store::get_secret_from_macos_backend(profile_name, key_name, alternate),
)
}
#[cfg(any(target_os = "macos", test))]
fn read_secret_with_fallback(
key_name: &str,
target_read: Result<Option<String>>,
alternate_read: impl FnOnce() -> Result<Option<String>>,
) -> Result<Option<String>> {
match target_read {
Ok(Some(value)) => Ok(Some(value)),
Ok(None) => alternate_read(),
Err(target_err) => match alternate_read() {
Ok(Some(value)) => Ok(Some(value)),
Ok(None) => Err(target_err).with_context(|| {
format!("secret '{key_name}' could not be read from either Keychain backend")
}),
Err(alternate_err) => Err(anyhow::anyhow!(
"secret '{key_name}' could not be read from either Keychain backend \
(target: {target_err}; alternate: {alternate_err})"
)),
},
}
}
pub fn run_set_default(profile_name: String) -> Result<()> {
let path = profile_file(&profile_name)?;
if !path.exists() {
anyhow::bail!("Profile '{profile_name}' not found.");
}
let mut global_config = load_config().unwrap_or_default();
if global_config.default_profile == profile_name {
println!("Profile '{profile_name}' is already the default.");
return Ok(());
}
global_config.default_profile = profile_name.clone();
save_config(&global_config)?;
println!("Default profile set to '{profile_name}'.");
Ok(())
}
#[derive(Debug, Default)]
pub struct LabelEdit {
pub add: Vec<String>,
pub remove: Vec<String>,
pub set: Vec<String>,
pub clear: bool,
}
impl LabelEdit {
fn is_empty(&self) -> bool {
self.add.is_empty() && self.remove.is_empty() && self.set.is_empty() && !self.clear
}
fn apply(&self, current: &[String]) -> Vec<String> {
if self.clear {
return Vec::new();
}
if !self.set.is_empty() {
return crate::config::parse_label_args(&self.set);
}
let remove = crate::config::parse_label_args(&self.remove);
let kept = current.iter().filter(|label| !remove.contains(label));
let add = crate::config::parse_label_args(&self.add);
crate::config::normalize_labels(kept.cloned().chain(add))
}
}
pub fn run_label(profile_name: String, edit: LabelEdit) -> Result<()> {
if !profile_file(&profile_name)?.exists() {
anyhow::bail!(
"Profile '{profile_name}' not found. Run `cx profiles list` to see profiles."
);
}
let mut profile = load_profile(&profile_name)?;
for raw in [&edit.add, &edit.remove, &edit.set] {
crate::config::parse_given_label_args(raw)?;
}
if edit.is_empty() {
println!("{}", labels_line(&profile_name, &profile.labels));
return Ok(());
}
let new_labels = edit.apply(&profile.labels);
if new_labels == profile.labels {
println!(
"{} (unchanged)",
labels_line(&profile_name, &profile.labels)
);
return Ok(());
}
profile.labels = new_labels;
save_profile(&profile_name, &profile)?;
println!("{}", labels_line(&profile_name, &profile.labels));
Ok(())
}
fn labels_line(profile_name: &str, labels: &[String]) -> String {
if labels.is_empty() {
format!("Profile '{profile_name}' has no labels.")
} else {
format!(
"Profile '{profile_name}' labels: {}",
display_labels(labels)
)
}
}
fn build_profile_non_interactive(
name: &str,
api_key: Option<String>,
region_choice: Option<RegionChoice>,
managed: bool,
keychain_sandboxed: bool,
) -> Result<(Profile, &'static str)> {
let mut missing = Vec::new();
if region_choice.is_none() {
missing.push("no region — pass --url or --region");
}
if api_key.is_none() {
missing.push("no API key — pass --api-key or set CX_API_KEY");
}
if !missing.is_empty() {
anyhow::bail!("{}", missing.join("\n"));
}
let (api_key, region_choice) = (api_key.unwrap(), region_choice.unwrap());
let region = match region_choice {
RegionChoice::Known(region) => region,
RegionChoice::Custom { base_url } => Region::Custom(base_url),
};
delete_os_store_secrets_if_recorded(name);
let (credential_storage, api_key, storage_desc) = match default_credential_storage(
current_os_store_platform(),
managed,
keychain_sandboxed,
) {
CredentialStorage::OsStore => os_store_or_file_fallback(
name,
keyring_store::store_secret(name, "api_key", &api_key),
api_key,
"OS credential store",
"profile file",
managed,
)?,
CredentialStorage::File => (CredentialStorage::File, Some(api_key), "profile file"),
};
let profile = Profile {
auth: AuthKind::ApiKey,
credential_storage,
api_key,
region,
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,
};
Ok((profile, storage_desc))
}
async fn configure_oauth(
name: &str,
region_choice: Option<RegionChoice>,
interactive: bool,
signup: bool,
managed: bool,
keychain_sandboxed: bool,
) -> Result<(Profile, &'static str)> {
let region_choice = match region_choice {
Some(choice) => choice,
None if interactive => select_region_interactive()?,
None => anyhow::bail!("no region — pass --url or --region"),
};
let is_custom;
let (region, base_url, client_id, oauth_client_id_for_profile) = match region_choice {
RegionChoice::Custom { base_url } => {
is_custom = true;
if !interactive {
anyhow::bail!(
"a custom endpoint needs an OAuth client ID, which is prompted \
interactively — run on a terminal, or use --api-key/CX_API_KEY"
);
}
let client_id = Text::new("OAuth client ID:").prompt()?;
let region = Region::Custom(base_url.clone());
let client_id_for_profile = Some(client_id.clone());
(region, base_url, client_id, client_id_for_profile)
}
RegionChoice::Known(region) => {
is_custom = false;
let base_url = region.api_endpoint().to_string();
let region_name = region.to_string();
let client_id = oauth::client_id_for_region(®ion_name)
.map(|s| s.to_string())
.ok_or_else(|| {
anyhow::anyhow!(
"No OAuth client ID found for region '{region_name}'.\n\
Please choose \"{CUSTOM_ENDPOINT_OPTION}\" to provide your own \
base URL and client ID."
)
})?;
(region, base_url, client_id, None)
}
};
delete_os_store_secrets_if_recorded(name);
println!();
let login = oauth::LoginOptions {
signup,
..oauth::LoginOptions::default()
};
let tokens = oauth::browser_login(&base_url, &client_id, login).await?;
println!("Login successful!");
let credential_storage = if interactive {
let help_message =
credential_storage_help_message("stores tokens in the profile config (0600 perms).");
select_credential_storage(
"Where should OAuth tokens be stored?",
&help_message,
managed,
keychain_sandboxed,
)?
} else {
default_credential_storage(current_os_store_platform(), managed, keychain_sandboxed)
};
let oauth_base_url_for_profile = if is_custom { Some(base_url) } else { None };
let (credential_storage, oauth_tokens, storage_desc) = match credential_storage {
CredentialStorage::OsStore => os_store_or_file_fallback(
name,
oauth::store_tokens_keyring(name, &tokens),
oauth::tokens_to_stored(&tokens),
"OS credential store (OAuth tokens)",
"profile file (OAuth tokens)",
managed,
)?,
CredentialStorage::File => (
CredentialStorage::File,
Some(oauth::tokens_to_stored(&tokens)),
"profile file (OAuth tokens)",
),
};
let mut profile = Profile {
auth: AuthKind::OAuth,
credential_storage,
api_key: None,
region,
labels: Vec::new(),
oauth_client_id: oauth_client_id_for_profile,
oauth_base_url: oauth_base_url_for_profile,
oauth_tokens,
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,
};
if let Some(whoami) =
crate::identity::lookup_whoami_bounded(profile.region.api_endpoint(), &tokens.access_token)
.await
{
crate::config::remember_signed_in_team(&mut profile, &whoami);
}
Ok((profile, storage_desc))
}
fn configure_api_key(
name: &str,
api_key: Option<String>,
region_choice: Option<RegionChoice>,
managed: bool,
keychain_sandboxed: bool,
) -> Result<(Profile, &'static str)> {
let api_key = match api_key {
Some(key) => key,
None => {
println!(
"The API key must be a Team Key or a Personal Key.\n \
• Team Key: Data Flow → API Keys → Team Keys\n \
• Personal Key: User menu (top-right) → Personal Keys\n\
Send-Your-Data / ingress keys will NOT work for querying."
);
Password::new("Coralogix API key (Team Key or Personal Key):")
.with_display_mode(PasswordDisplayMode::Masked)
.without_confirmation()
.with_validator(|input: &str| {
use inquire::validator::Validation;
if input.trim().is_empty() {
Ok(Validation::Invalid("API key cannot be empty".into()))
} else {
Ok(Validation::Valid)
}
})
.prompt()?
}
};
let region_choice = match region_choice {
Some(choice) => choice,
None => select_region_interactive()?,
};
let region = match region_choice {
RegionChoice::Known(region) => region,
RegionChoice::Custom { base_url } => Region::Custom(base_url),
};
let help_message =
credential_storage_help_message("stores credentials in the profile config (0600 perms).");
let credential_storage = select_credential_storage(
"Where should API keys be stored?",
&help_message,
managed,
keychain_sandboxed,
)?;
let (credential_storage, api_key, storage_desc) = match credential_storage {
CredentialStorage::OsStore => os_store_or_file_fallback(
name,
keyring_store::store_secret(name, "api_key", &api_key),
api_key,
"OS credential store",
"profile file",
managed,
)?,
CredentialStorage::File => {
delete_os_store_secrets_if_recorded(name);
(CredentialStorage::File, Some(api_key), "profile file")
}
};
let profile = Profile {
auth: AuthKind::ApiKey,
credential_storage,
api_key,
region,
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,
};
Ok((profile, storage_desc))
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use std::collections::HashMap;
use super::*;
use clap::ValueEnum;
fn strings(values: &[&str]) -> Vec<String> {
values.iter().map(|v| v.to_string()).collect()
}
fn test_profile(credential_storage: CredentialStorage) -> Profile {
Profile {
auth: AuthKind::ApiKey,
credential_storage,
api_key: None,
region: Region::Eu2,
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,
}
}
#[derive(Default)]
struct MockSecretMigrator {
source: HashMap<String, String>,
target: RefCell<HashMap<String, String>>,
operations: RefCell<Vec<String>>,
source_error: Option<String>,
target_validation_error: Option<String>,
target_validation_errors: HashMap<String, String>,
verification_override: Option<String>,
verification_failures: RefCell<usize>,
store_failures: RefCell<usize>,
}
impl ProfileSecretMigrator for MockSecretMigrator {
fn read_source(&self, key_name: &str) -> Result<Option<String>> {
self.operations
.borrow_mut()
.push(format!("read:{key_name}"));
if let Some(error) = &self.source_error {
anyhow::bail!("{error}");
}
Ok(self.source.get(key_name).cloned())
}
fn validate_target(&self, key_name: &str, _value: &str) -> Result<()> {
self.operations
.borrow_mut()
.push(format!("validate:{key_name}"));
if let Some(error) = self.target_validation_errors.get(key_name) {
anyhow::bail!("{error}");
}
if let Some(error) = &self.target_validation_error {
anyhow::bail!("{error}");
}
Ok(())
}
fn delete_target(&self, key_name: &str) -> Result<()> {
self.operations
.borrow_mut()
.push(format!("delete:{key_name}"));
self.target.borrow_mut().remove(key_name);
Ok(())
}
fn store_target(&self, key_name: &str, value: &str) -> Result<()> {
self.operations
.borrow_mut()
.push(format!("store:{key_name}:{value}"));
let mut remaining_failures = self.store_failures.borrow_mut();
if *remaining_failures > 0 {
*remaining_failures -= 1;
anyhow::bail!("store denied");
}
self.target
.borrow_mut()
.insert(key_name.to_string(), value.to_string());
Ok(())
}
fn read_target(&self, key_name: &str) -> Result<Option<String>> {
self.operations
.borrow_mut()
.push(format!("verify:{key_name}"));
let mut remaining_failures = self.verification_failures.borrow_mut();
if *remaining_failures > 0 {
*remaining_failures -= 1;
return Ok(self.verification_override.clone());
}
Ok(self.target.borrow().get(key_name).cloned())
}
}
#[test]
fn migration_uses_the_expected_secret_set_for_each_auth_kind() {
assert_eq!(
profile_secret_names(AuthKind::ApiKey),
(API_KEY_SECRET, &[API_KEY_SECRET][..])
);
assert_eq!(
profile_secret_names(AuthKind::OAuth),
("oauth_access_token", OAUTH_SECRETS)
);
}
#[test]
fn migration_recreates_each_secret_in_read_delete_store_verify_order() {
let migrator = MockSecretMigrator {
source: HashMap::from([
("oauth_access_token".to_string(), "access".to_string()),
("oauth_refresh_token".to_string(), "refresh".to_string()),
]),
..Default::default()
};
migrate_profile_secrets("test", AuthKind::OAuth, &migrator).unwrap();
assert_eq!(
migrator.operations.into_inner(),
vec![
"read:oauth_access_token",
"validate:oauth_access_token",
"read:oauth_refresh_token",
"validate:oauth_refresh_token",
"read:oauth_id_token",
"read:oauth_token_expiry",
"delete:oauth_access_token",
"store:oauth_access_token:access",
"verify:oauth_access_token",
"delete:oauth_refresh_token",
"store:oauth_refresh_token:refresh",
"verify:oauth_refresh_token",
]
);
}
#[test]
fn migration_does_not_delete_a_required_secret_that_cannot_be_read() {
let migrator = MockSecretMigrator::default();
let error = migrate_profile_secrets("test", AuthKind::ApiKey, &migrator).unwrap_err();
assert!(error.to_string().contains("required secret 'api_key'"));
assert_eq!(migrator.operations.into_inner(), vec!["read:api_key"]);
}
#[test]
fn migration_stops_before_delete_when_source_read_fails() {
let migrator = MockSecretMigrator {
source_error: Some("access refused".to_string()),
..Default::default()
};
let error = migrate_profile_secrets("test", AuthKind::ApiKey, &migrator).unwrap_err();
assert!(error.to_string().contains("access refused"));
assert_eq!(migrator.operations.into_inner(), vec!["read:api_key"]);
}
#[test]
fn migration_does_not_delete_when_target_cannot_store_a_secret() {
let migrator = MockSecretMigrator {
source: HashMap::from([("api_key".to_string(), "too-long".to_string())]),
target_validation_error: Some("exceeds the interactive command buffer".to_string()),
..Default::default()
};
let error = migrate_profile_secrets("test", AuthKind::ApiKey, &migrator).unwrap_err();
assert!(error
.to_string()
.contains("exceeds the interactive command buffer"));
assert_eq!(
migrator.operations.into_inner(),
vec!["read:api_key", "validate:api_key"]
);
}
#[test]
fn migration_validates_every_oauth_secret_before_deleting_any_of_them() {
let migrator = MockSecretMigrator {
source: HashMap::from([
("oauth_access_token".to_string(), "access".to_string()),
("oauth_refresh_token".to_string(), "refresh".to_string()),
("oauth_id_token".to_string(), "too-long".to_string()),
]),
target_validation_errors: HashMap::from([(
"oauth_id_token".to_string(),
"exceeds the interactive command buffer".to_string(),
)]),
..Default::default()
};
let error = migrate_profile_secrets("test", AuthKind::OAuth, &migrator).unwrap_err();
assert!(error
.to_string()
.contains("exceeds the interactive command buffer"));
let operations = migrator.operations.into_inner();
assert!(operations
.iter()
.all(|operation| !operation.starts_with("delete:")));
assert_eq!(
operations,
vec![
"read:oauth_access_token",
"validate:oauth_access_token",
"read:oauth_refresh_token",
"validate:oauth_refresh_token",
"read:oauth_id_token",
"validate:oauth_id_token",
]
);
}
#[test]
fn migration_fails_when_target_readback_does_not_match() {
let migrator = MockSecretMigrator {
source: HashMap::from([("api_key".to_string(), "expected".to_string())]),
verification_override: Some("different".to_string()),
verification_failures: RefCell::new(2),
..Default::default()
};
let error = migrate_profile_secrets("test", AuthKind::ApiKey, &migrator).unwrap_err();
assert!(format!("{error:#}").contains("did not match after rewriting"));
assert_eq!(
migrator.operations.into_inner(),
vec![
"read:api_key",
"validate:api_key",
"delete:api_key",
"store:api_key:expected",
"verify:api_key",
"store:api_key:expected",
"verify:api_key",
]
);
}
#[test]
fn migration_retries_store_after_delete_before_reporting_a_lost_secret() {
let migrator = MockSecretMigrator {
source: HashMap::from([("api_key".to_string(), "value".to_string())]),
store_failures: RefCell::new(2),
..Default::default()
};
let error = migrate_profile_secrets("test", AuthKind::ApiKey, &migrator).unwrap_err();
assert!(error
.to_string()
.contains("was deleted but could not be restored"));
assert!(error.to_string().contains("cx profiles add test --force"));
assert_eq!(
migrator.operations.into_inner(),
vec![
"read:api_key",
"validate:api_key",
"delete:api_key",
"store:api_key:value",
"store:api_key:value",
]
);
}
#[test]
fn migration_retries_store_after_a_failed_readback() {
let migrator = MockSecretMigrator {
source: HashMap::from([("api_key".to_string(), "value".to_string())]),
verification_override: Some("different".to_string()),
verification_failures: RefCell::new(1),
..Default::default()
};
migrate_profile_secrets("test", AuthKind::ApiKey, &migrator).unwrap();
assert_eq!(
migrator.operations.into_inner(),
vec![
"read:api_key",
"validate:api_key",
"delete:api_key",
"store:api_key:value",
"verify:api_key",
"store:api_key:value",
"verify:api_key",
]
);
}
#[test]
fn migration_loop_skips_file_profiles_continues_after_failures_and_returns_an_error() {
let profiles = vec![
(
"file".to_string(),
Ok(test_profile(CredentialStorage::File)),
),
(
"success".to_string(),
Ok(test_profile(CredentialStorage::OsStore)),
),
(
"failure".to_string(),
Ok(test_profile(CredentialStorage::OsStore)),
),
(
"unreadable".to_string(),
Err(anyhow::anyhow!("permission denied")),
),
];
let migrated = RefCell::new(Vec::new());
let summary = run_migrate_with(profiles, |name, _profile| {
migrated.borrow_mut().push(name.to_string());
if name == "failure" {
anyhow::bail!("Keychain access denied");
}
Ok(())
});
assert_eq!(
summary,
MigrationSummary {
migrated: 1,
skipped: 1,
failed: 2,
}
);
assert_eq!(migrated.into_inner(), vec!["success", "failure"]);
assert_eq!(
migration_result(summary).unwrap_err().to_string(),
"2 profile(s) failed to migrate"
);
}
#[test]
fn migration_is_rejected_before_keychain_access_in_a_sandbox() {
assert!(reject_keychain_migration_in_sandbox(false).is_ok());
let err = reject_keychain_migration_in_sandbox(true).unwrap_err();
assert!(
err.to_string().contains("outside the sandbox"),
"unexpected error: {err}"
);
}
#[test]
fn secret_read_falls_back_when_target_does_not_find_the_item() {
let result = read_secret_with_fallback("api_key", Ok(None), || {
Ok(Some("from-alternate".to_string()))
})
.unwrap();
assert_eq!(result.as_deref(), Some("from-alternate"));
}
#[test]
fn secret_read_reports_both_backend_errors() {
let error = read_secret_with_fallback(
"api_key",
Err(anyhow::anyhow!("target denied access")),
|| Err(anyhow::anyhow!("alternate denied access")),
)
.unwrap_err();
assert!(error
.to_string()
.contains("target: target denied access; alternate: alternate denied access"));
}
#[test]
fn label_edit_add_keeps_existing_and_dedupes() {
let edit = LabelEdit {
add: strings(&["kuku, prod", "eu"]),
..Default::default()
};
assert_eq!(
edit.apply(&strings(&["prod", "staging"])),
strings(&["prod", "staging", "kuku", "eu"])
);
}
#[test]
fn label_edit_remove_ignores_missing_and_splits_commas() {
let edit = LabelEdit {
remove: strings(&["staging,missing"]),
..Default::default()
};
assert_eq!(
edit.apply(&strings(&["prod", "staging", "eu"])),
strings(&["prod", "eu"])
);
}
#[test]
fn label_edit_add_and_remove_in_one_call() {
let edit = LabelEdit {
add: strings(&["kuku"]),
remove: strings(&["prod"]),
..Default::default()
};
assert_eq!(
edit.apply(&strings(&["prod", "eu"])),
strings(&["eu", "kuku"])
);
}
#[test]
fn label_edit_set_replaces_and_clear_empties() {
let set = LabelEdit {
set: strings(&["a,b"]),
..Default::default()
};
assert_eq!(set.apply(&strings(&["prod"])), strings(&["a", "b"]));
let clear = LabelEdit {
clear: true,
..Default::default()
};
assert!(clear.apply(&strings(&["prod"])).is_empty());
assert!(LabelEdit::default().is_empty());
assert!(!set.is_empty());
}
#[test]
fn labels_line_names_profile_and_labels() {
assert_eq!(labels_line("a", &[]), "Profile 'a' has no labels.");
assert_eq!(
labels_line("a", &strings(&["prod", "eu"])),
"Profile 'a' labels: prod,eu"
);
}
#[test]
fn display_labels_joins_with_commas_or_dash() {
assert_eq!(display_labels(&[]), "-");
assert_eq!(
display_labels(&["prod".to_string(), "eu".to_string()]),
"prod,eu"
);
}
#[test]
fn accepted_label_default_keeps_legacy_comma_label() {
let existing = vec!["prod,eu".to_string()];
let accepted_default = existing.join(",");
assert_eq!(
labels_from_prompt_answer(&existing, Some(&accepted_default)),
existing
);
assert_eq!(labels_from_prompt_answer(&existing, Some("")), existing);
assert_eq!(labels_from_prompt_answer(&existing, Some(" ")), existing);
assert_eq!(labels_from_prompt_answer(&existing, None), existing);
assert_eq!(
labels_from_prompt_answer(&existing, Some("prod, eu")),
vec!["prod".to_string(), "eu".to_string()]
);
}
#[test]
fn every_output_format_is_selectable_in_picker() {
for variant in OutputFormat::value_variants() {
assert!(
OUTPUT_FORMATS.contains(&variant.as_str()),
"OUTPUT_FORMATS is missing canonical variant {:?}; picker cursor would \
not preselect it",
variant.as_str(),
);
}
}
#[test]
fn missing_profile_does_not_record_os_store() {
assert_eq!(
recorded_credential_storage("cx_profile_that_does_not_exist"),
None
);
}
#[test]
fn keychain_sandbox_blocks_destructive_actions_for_os_store_profiles() {
assert!(os_store_profile_action_is_blocked(
Some(CredentialStorage::OsStore),
true
));
assert!(!os_store_profile_action_is_blocked(
Some(CredentialStorage::File),
true
));
assert!(!os_store_profile_action_is_blocked(None, true));
assert!(!os_store_profile_action_is_blocked(
Some(CredentialStorage::OsStore),
false
));
}
#[test]
fn credential_storage_lists_file_first() {
let platform = current_os_store_platform();
let options = credential_storage_options_for(platform, false, false);
assert_eq!(options[0].1, CredentialStorage::File);
if os_store_offered_on(platform) {
assert_eq!(options.len(), 2);
assert_eq!(options[1].1, CredentialStorage::OsStore);
} else {
assert_eq!(options.len(), 1);
}
}
#[test]
fn keychain_sandbox_only_offers_and_defaults_to_file_storage() {
for platform in [
OsStorePlatform::Macos {
apple_signed: false,
},
OsStorePlatform::Macos { apple_signed: true },
OsStorePlatform::Windows,
OsStorePlatform::Other,
OsStorePlatform::LinuxMusl,
] {
assert_eq!(
credential_storage_options_for(platform, false, true),
vec![("file", CredentialStorage::File)]
);
assert_eq!(
default_credential_storage(platform, false, true),
CredentialStorage::File
);
assert_eq!(credential_storage_cursor(platform, false, true), 0);
}
assert_eq!(
select_credential_storage("ignored", "ignored", false, true)
.expect("Keychain-blocked sandbox should not prompt"),
CredentialStorage::File
);
}
#[test]
fn credential_storage_file_override_is_explicit() {
assert_eq!(
credential_storage_override_from(Some("file")),
Some(CredentialStorage::File)
);
assert_eq!(credential_storage_override_from(Some("os-store")), None);
assert_eq!(credential_storage_override_from(Some("FILE")), None);
assert_eq!(credential_storage_override_from(None), None);
}
#[test]
fn managed_policy_rejects_file_storage_override() {
let err = reject_file_storage_override(true, Some("file"))
.expect_err("policy forbids the file override");
assert!(
err.to_string()
.contains("disabled by your organization's policy"),
"got: {err}"
);
reject_file_storage_override(false, Some("file")).expect("no policy");
reject_file_storage_override(true, None).expect("no override");
reject_file_storage_override(true, Some("FILE")).expect("not the file override");
}
#[test]
fn managed_policy_offers_and_defaults_to_os_store_only() {
for platform in [
OsStorePlatform::Macos {
apple_signed: false,
},
OsStorePlatform::Macos { apple_signed: true },
OsStorePlatform::Windows,
OsStorePlatform::Other,
OsStorePlatform::LinuxMusl,
] {
let options = credential_storage_options_for(platform, true, false);
assert_eq!(options.len(), 1);
assert_eq!(options[0].1, CredentialStorage::OsStore);
assert_eq!(
default_credential_storage(platform, true, false),
CredentialStorage::OsStore
);
assert_eq!(credential_storage_cursor(platform, true, false), 0);
}
}
#[test]
fn managed_policy_skips_credential_storage_picker() {
assert_eq!(
select_credential_storage("ignored", "ignored", true, false)
.expect("managed policy should not prompt"),
CredentialStorage::OsStore
);
}
#[test]
fn invalid_credential_storage_override_warns() {
assert_eq!(invalid_credential_storage_override_warning(None), None);
assert_eq!(
invalid_credential_storage_override_warning(Some("file")),
None
);
assert_eq!(
invalid_credential_storage_override_warning(Some("FILE")).as_deref(),
Some("Warning: ignoring CX_CREDENTIAL_STORAGE=\"FILE\"; only \"file\" is supported.")
);
}
#[test]
fn macos_defaults_to_os_store_for_both_signatures() {
for apple_signed in [false, true] {
let platform = OsStorePlatform::Macos { apple_signed };
assert_eq!(
default_credential_storage(platform, false, false),
CredentialStorage::OsStore
);
let options = credential_storage_options_for(platform, false, false);
let cursor = credential_storage_cursor(platform, false, false);
assert_eq!(options[cursor].1, CredentialStorage::OsStore);
}
}
#[test]
fn windows_defaults_to_os_store() {
let platform = OsStorePlatform::Windows;
assert_eq!(
default_credential_storage(platform, false, false),
CredentialStorage::OsStore
);
let options = credential_storage_options_for(platform, false, false);
let cursor = credential_storage_cursor(platform, false, false);
assert_eq!(options[cursor].1, CredentialStorage::OsStore);
}
#[test]
fn unix_defaults_to_file() {
for platform in [OsStorePlatform::Other, OsStorePlatform::LinuxMusl] {
assert_eq!(
default_credential_storage(platform, false, false),
CredentialStorage::File
);
let options = credential_storage_options_for(platform, false, false);
let cursor = credential_storage_cursor(platform, false, false);
assert_eq!(options[cursor].1, CredentialStorage::File);
}
}
#[test]
fn unsigned_macos_offers_keychain_through_security() {
let platform = OsStorePlatform::Macos {
apple_signed: false,
};
assert!(os_store_offered_on(platform));
let help = credential_storage_help(
"stores credentials in the profile config (0600 perms).",
platform,
);
assert!(help.contains("/usr/bin/security"), "got: {help}");
assert!(help.contains("Homebrew"), "got: {help}");
assert!(help.contains("preselected"), "got: {help}");
assert!(
!help.contains("not offered"),
"unsigned builds must offer the Keychain, got: {help}"
);
}
#[test]
fn signed_macos_help_describes_the_signature_acl() {
let platform = OsStorePlatform::Macos { apple_signed: true };
assert!(os_store_offered_on(platform));
let help = credential_storage_help(
"stores credentials in the profile config (0600 perms).",
platform,
);
assert!(help.contains("Developer ID-signed"), "got: {help}");
assert!(help.contains("preselected"), "got: {help}");
assert!(
!help.contains("/usr/bin/security"),
"signed builds keep direct Keychain access, got: {help}"
);
}
#[test]
fn linux_musl_offers_only_file() {
assert!(!os_store_offered_on(OsStorePlatform::LinuxMusl));
}
#[test]
fn os_store_fallback_keeps_os_store_on_success() {
let (storage, payload, desc) = os_store_or_file_fallback(
"cx_test_os_store_ok",
Ok(()),
"secret",
"OS credential store",
"profile file",
false,
)
.expect("successful store");
assert_eq!(storage, CredentialStorage::OsStore);
assert_eq!(payload, None);
assert_eq!(desc, "OS credential store");
}
#[test]
fn os_store_fallback_uses_file_when_keyring_unavailable() {
let (storage, payload, desc) = os_store_or_file_fallback(
"cx_test_os_store_fallback",
Err(anyhow::anyhow!("no secret service")),
"secret",
"OS credential store",
"profile file",
false,
)
.expect("no policy should permit fallback");
assert_eq!(storage, CredentialStorage::File);
assert_eq!(payload, Some("secret"));
assert_eq!(desc, "profile file");
}
#[test]
fn managed_policy_refuses_file_fallback_when_os_store_fails() {
let err = os_store_or_file_fallback(
"cx_test_os_store_managed",
Err(anyhow::anyhow!("no secret service")),
"secret",
"OS credential store",
"profile file",
true,
)
.expect_err("policy forbids the file fallback");
let message = err.to_string();
assert!(message.contains("no secret service"), "got: {message}");
assert!(
message.contains("disabled by your organization's policy"),
"got: {message}"
);
}
#[test]
fn region_default_cursor_points_at_eu2() {
assert_eq!(
PICKER_REGIONS[REGION_DEFAULT_CURSOR],
Region::Eu2,
"REGION_DEFAULT_CURSOR must point at eu2 in PICKER_REGIONS"
);
}
#[test]
fn region_flag_parses_known_shortname() {
let region = parse_region_flag("eu2").expect("eu2 is a known region");
assert_eq!(region, Region::Eu2);
}
#[test]
fn region_flag_is_case_insensitive() {
let region = parse_region_flag("EU2").expect("region flag should be case-insensitive");
assert_eq!(region, Region::Eu2);
}
#[test]
fn region_flag_rejects_unknown_shortname() {
let err = parse_region_flag("eu22").expect_err("eu22 is not a region");
assert!(
err.to_string().contains("unknown region 'eu22'"),
"error should name the bad value, got: {err}"
);
}
#[test]
fn no_region_flags_resolve_to_none() {
assert!(resolve_region_flags(None, None)
.expect("no flags is valid")
.is_none());
}
#[test]
fn url_flag_derives_known_region() {
let choice = resolve_region_flags(Some("https://myteam.app.eu2.coralogix.com"), None)
.expect("recognizable URL")
.expect("URL flag should produce a choice");
assert!(
matches!(choice, RegionChoice::Known(Region::Eu2)),
"app URL should derive eu2"
);
}
#[test]
fn url_flag_unresolved_becomes_custom_endpoint() {
let choice = resolve_region_flags(Some("https://api.myenv.internal/"), None)
.expect("host-bearing URL")
.expect("URL flag should produce a choice");
match choice {
RegionChoice::Custom { base_url } => assert_eq!(base_url, "https://api.myenv.internal"),
RegionChoice::Known(_) => panic!("unknown host must not resolve to a known region"),
}
}
#[test]
fn url_flag_without_host_is_rejected() {
let err = resolve_region_flags(Some(""), None).expect_err("empty URL has no host");
assert!(
err.to_string().contains("not a valid URL"),
"error should say the URL is invalid, got: {err}"
);
}
#[test]
fn url_flag_schemeless_host_is_stored_verbatim() {
let choice = resolve_region_flags(Some("api.myenv.internal"), None)
.expect("host-bearing input")
.expect("URL flag should produce a choice");
match choice {
RegionChoice::Custom { base_url } => {
assert_eq!(base_url, "api.myenv.internal")
}
RegionChoice::Known(region) => {
panic!("unknown host must not resolve to a known region {region}")
}
}
}
#[test]
fn url_flag_unlisted_region_becomes_custom_endpoint() {
let choice = resolve_region_flags(Some("https://team.app.stg1.coralogix.net"), None)
.expect("host-bearing URL")
.expect("URL flag should produce a choice");
match choice {
RegionChoice::Custom { base_url } => {
assert_eq!(base_url, "https://team.app.stg1.coralogix.net")
}
RegionChoice::Known(region) => {
panic!("expected custom endpoint, got known region {region}")
}
}
}
#[test]
fn every_region_option_is_short_name_and_url_template() {
for region in PICKER_REGIONS {
let template = region
.app_url_template()
.expect("picker region must have an app URL template");
assert_eq!(
region_option_label(region),
format!("({region}) {template}")
);
assert!(
!matches!(region, Region::Custom(_)),
"PICKER_REGIONS entry {region} is not a known region"
);
}
}
#[test]
fn region_picker_ends_with_custom_endpoint() {
let options = region_picker_options();
assert_eq!(options[options.len() - 1], CUSTOM_ENDPOINT_OPTION);
assert_eq!(options.len(), PICKER_REGIONS.len() + 1);
}
#[test]
fn custom_base_url_adds_scheme_when_missing() {
assert_eq!(
custom_base_url_from("api.myenv.example.com").as_deref(),
Some("https://api.myenv.example.com")
);
}
#[test]
fn custom_base_url_preserves_scheme_and_strips_slash() {
assert_eq!(
custom_base_url_from("http://api.myenv.example.com/").as_deref(),
Some("http://api.myenv.example.com")
);
}
#[test]
fn custom_base_url_rejects_hostless_input() {
assert_eq!(custom_base_url_from(""), None);
assert_eq!(custom_base_url_from(" "), None);
}
#[test]
fn paste_url_for_listed_region_stays_known() {
match resolve_url_choice("https://team.app.eu2.coralogix.com").unwrap() {
RegionChoice::Known(region) => assert_eq!(region.to_string(), "eu2"),
RegionChoice::Custom { base_url } => {
panic!("expected known region eu2, got custom endpoint {base_url}")
}
}
}
#[test]
fn paste_url_for_unlisted_region_becomes_custom_endpoint() {
match resolve_url_choice("https://team.app.stg1.coralogix.net").unwrap() {
RegionChoice::Custom { base_url } => {
assert_eq!(base_url, "https://team.app.stg1.coralogix.net")
}
RegionChoice::Known(region) => {
panic!("expected custom endpoint, got known region {region}")
}
}
}
}