use std::collections::HashMap;
use crate::provider::ProviderConfig;
#[derive(Clone, PartialEq, Eq)]
pub struct Secret(String);
impl Secret {
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
pub fn expose(&self) -> &str {
&self.0
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl std::fmt::Debug for Secret {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("<redacted>")
}
}
pub trait CredentialSource: Send + Sync {
fn api_key(&self, provider_id: &str, config: &ProviderConfig) -> Result<Secret, String>;
}
pub struct ConfigCredentials;
impl CredentialSource for ConfigCredentials {
fn api_key(&self, provider_id: &str, config: &ProviderConfig) -> Result<Secret, String> {
match config.api_key_env.as_deref().filter(|n| !n.is_empty()) {
Some(name) => EnvCredentials::new([name]).api_key(provider_id, config),
None if config.builtin => EnvCredentials::anthropic().api_key(provider_id, config),
None => Err("missing api_key: no `api_key_env`".to_string()),
}
}
}
pub struct ConfigThen(pub std::sync::Arc<dyn CredentialSource>);
impl CredentialSource for ConfigThen {
fn api_key(&self, provider_id: &str, config: &ProviderConfig) -> Result<Secret, String> {
ConfigCredentials
.api_key(provider_id, config)
.or_else(|own| {
self.0
.api_key(provider_id, config)
.map_err(|host| format!("{own}; host: {host}"))
})
}
}
pub struct EnvCredentials {
names: Vec<String>,
}
impl EnvCredentials {
pub fn new(names: impl IntoIterator<Item = impl Into<String>>) -> Self {
let names: Vec<String> = names.into_iter().map(Into::into).collect();
for name in &names {
crate::interface::exec::env::hold_back_credential(name);
}
Self { names }
}
pub fn anthropic() -> Self {
Self::new(["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"])
}
}
impl CredentialSource for EnvCredentials {
#[expect(
clippy::disallowed_methods,
reason = "reading the key from the process environment is what this credential source is"
)]
fn api_key(&self, _provider_id: &str, _config: &ProviderConfig) -> Result<Secret, String> {
for name in &self.names {
if let Ok(v) = std::env::var(name) {
if !v.is_empty() {
return Ok(Secret::new(v));
}
}
}
Err(format!(
"missing api_key: none of {} is set",
self.names.join(", ")
))
}
}
pub struct StaticCredentials {
by_provider: HashMap<String, Secret>,
}
impl StaticCredentials {
pub fn new(entries: impl IntoIterator<Item = (String, Secret)>) -> Self {
Self {
by_provider: entries.into_iter().collect(),
}
}
}
impl CredentialSource for StaticCredentials {
fn api_key(&self, provider_id: &str, _config: &ProviderConfig) -> Result<Secret, String> {
self.by_provider
.get(provider_id)
.cloned()
.ok_or_else(|| "missing api_key".to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
const CANARY: &str = "sk-do-not-print-me";
#[test]
fn a_secret_prints_as_nothing() {
let s = Secret::new(CANARY);
assert!(!format!("{s:?}").contains(CANARY));
assert!(!format!("{:?}", Some(s.clone())).contains(CANARY));
assert!(!format!("{:?}", vec![s.clone()]).contains(CANARY));
assert_eq!(s.expose(), CANARY);
}
#[test]
fn the_config_source_reports_a_missing_key() {
let err = ConfigCredentials
.api_key("main", &ProviderConfig::default())
.unwrap_err();
assert!(err.starts_with("missing api_key"), "{err}");
}
#[test]
fn a_source_that_keeps_nothing_on_disk_can_answer_instead() {
let source = StaticCredentials::new([("vault-backed".to_string(), Secret::new(CANARY))]);
let got = source
.api_key("vault-backed", &ProviderConfig::default())
.expect("the map has this provider");
assert_eq!(got.expose(), CANARY);
assert_eq!(
source
.api_key("someone-else", &ProviderConfig::default())
.unwrap_err(),
"missing api_key"
);
}
#[test]
#[expect(
clippy::disallowed_methods,
reason = "the expected key is whatever the environment holds"
)]
fn a_provider_can_name_the_variable_its_key_is_in() {
let cfg = ProviderConfig {
api_key_env: Some("PATH".into()),
..Default::default()
};
let got = ConfigCredentials.api_key("p", &cfg).unwrap();
assert_eq!(got.expose(), std::env::var("PATH").unwrap());
let unset = ProviderConfig {
api_key_env: Some("AGIX_TEST_CREDENTIAL_THAT_IS_NOT_SET".into()),
..Default::default()
};
let err = ConfigCredentials.api_key("p", &unset).unwrap_err();
assert!(
err.contains("AGIX_TEST_CREDENTIAL_THAT_IS_NOT_SET"),
"{err}"
);
}
#[test]
fn the_host_answers_only_what_the_entry_leaves_unset() {
let host = std::sync::Arc::new(StaticCredentials::new([(
"vault-backed".to_string(),
Secret::new(CANARY),
)]));
let chain = ConfigThen(host);
assert_eq!(
chain
.api_key("vault-backed", &ProviderConfig::default())
.unwrap()
.expose(),
CANARY
);
let named = ProviderConfig {
api_key_env: Some("PATH".into()),
..Default::default()
};
assert_ne!(
chain.api_key("vault-backed", &named).unwrap().expose(),
CANARY,
"the variable the entry names wins over the host"
);
let err = chain
.api_key("unknown", &ProviderConfig::default())
.unwrap_err();
assert!(err.starts_with("missing api_key"), "{err}");
}
#[test]
fn the_env_source_names_what_it_looked_for() {
let source = EnvCredentials::new(["AGIX_TEST_CREDENTIAL_THAT_IS_NOT_SET"]);
let err = source
.api_key("main", &ProviderConfig::default())
.unwrap_err();
assert!(
err.contains("AGIX_TEST_CREDENTIAL_THAT_IS_NOT_SET"),
"{err}"
);
}
}