base/interface/
credentials.rs1use std::collections::HashMap;
20
21use crate::provider::ProviderConfig;
22
23#[derive(Clone, PartialEq, Eq)]
28pub struct Secret(String);
29
30impl Secret {
31 pub fn new(value: impl Into<String>) -> Self {
32 Self(value.into())
33 }
34
35 pub fn expose(&self) -> &str {
39 &self.0
40 }
41
42 pub fn is_empty(&self) -> bool {
43 self.0.is_empty()
44 }
45}
46
47impl std::fmt::Debug for Secret {
48 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 f.write_str("<redacted>")
50 }
51}
52
53pub trait CredentialSource: Send + Sync {
62 fn api_key(&self, provider_id: &str, config: &ProviderConfig) -> Result<Secret, String>;
68}
69
70pub struct ConfigCredentials;
74
75impl CredentialSource for ConfigCredentials {
76 fn api_key(&self, provider_id: &str, config: &ProviderConfig) -> Result<Secret, String> {
77 match config.api_key_env.as_deref().filter(|n| !n.is_empty()) {
78 Some(name) => EnvCredentials::new([name]).api_key(provider_id, config),
79 None if config.builtin => EnvCredentials::anthropic().api_key(provider_id, config),
80 None => Err("missing api_key: no `api_key_env`".to_string()),
81 }
82 }
83}
84
85pub struct ConfigThen(pub std::sync::Arc<dyn CredentialSource>);
88
89impl CredentialSource for ConfigThen {
90 fn api_key(&self, provider_id: &str, config: &ProviderConfig) -> Result<Secret, String> {
91 ConfigCredentials
92 .api_key(provider_id, config)
93 .or_else(|own| {
94 self.0
95 .api_key(provider_id, config)
96 .map_err(|host| format!("{own}; host: {host}"))
97 })
98 }
99}
100
101pub struct EnvCredentials {
107 names: Vec<String>,
108}
109
110impl EnvCredentials {
111 pub fn new(names: impl IntoIterator<Item = impl Into<String>>) -> Self {
114 let names: Vec<String> = names.into_iter().map(Into::into).collect();
115 for name in &names {
116 crate::interface::exec::env::hold_back_credential(name);
117 }
118 Self { names }
119 }
120
121 pub fn anthropic() -> Self {
123 Self::new(["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"])
124 }
125}
126
127impl CredentialSource for EnvCredentials {
128 #[expect(
129 clippy::disallowed_methods,
130 reason = "reading the key from the process environment is what this credential source is"
131 )]
132 fn api_key(&self, _provider_id: &str, _config: &ProviderConfig) -> Result<Secret, String> {
133 for name in &self.names {
134 if let Ok(v) = std::env::var(name) {
135 if !v.is_empty() {
136 return Ok(Secret::new(v));
137 }
138 }
139 }
140 Err(format!(
141 "missing api_key: none of {} is set",
142 self.names.join(", ")
143 ))
144 }
145}
146
147pub struct StaticCredentials {
153 by_provider: HashMap<String, Secret>,
154}
155
156impl StaticCredentials {
157 pub fn new(entries: impl IntoIterator<Item = (String, Secret)>) -> Self {
158 Self {
159 by_provider: entries.into_iter().collect(),
160 }
161 }
162}
163
164impl CredentialSource for StaticCredentials {
165 fn api_key(&self, provider_id: &str, _config: &ProviderConfig) -> Result<Secret, String> {
166 self.by_provider
167 .get(provider_id)
168 .cloned()
169 .ok_or_else(|| "missing api_key".to_string())
170 }
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176
177 const CANARY: &str = "sk-do-not-print-me";
178
179 #[test]
180 fn a_secret_prints_as_nothing() {
181 let s = Secret::new(CANARY);
182 assert!(!format!("{s:?}").contains(CANARY));
183 assert!(!format!("{:?}", Some(s.clone())).contains(CANARY));
184 assert!(!format!("{:?}", vec![s.clone()]).contains(CANARY));
185 assert_eq!(s.expose(), CANARY);
186 }
187
188 #[test]
189 fn the_config_source_reports_a_missing_key() {
190 let err = ConfigCredentials
191 .api_key("main", &ProviderConfig::default())
192 .unwrap_err();
193 assert!(err.starts_with("missing api_key"), "{err}");
194 }
195
196 #[test]
197 fn a_source_that_keeps_nothing_on_disk_can_answer_instead() {
198 let source = StaticCredentials::new([("vault-backed".to_string(), Secret::new(CANARY))]);
199 let got = source
200 .api_key("vault-backed", &ProviderConfig::default())
201 .expect("the map has this provider");
202 assert_eq!(got.expose(), CANARY);
203 assert_eq!(
204 source
205 .api_key("someone-else", &ProviderConfig::default())
206 .unwrap_err(),
207 "missing api_key"
208 );
209 }
210
211 #[test]
214 #[expect(
215 clippy::disallowed_methods,
216 reason = "the expected key is whatever the environment holds"
217 )]
218 fn a_provider_can_name_the_variable_its_key_is_in() {
219 let cfg = ProviderConfig {
220 api_key_env: Some("PATH".into()),
221 ..Default::default()
222 };
223 let got = ConfigCredentials.api_key("p", &cfg).unwrap();
224 assert_eq!(got.expose(), std::env::var("PATH").unwrap());
225
226 let unset = ProviderConfig {
227 api_key_env: Some("AGIX_TEST_CREDENTIAL_THAT_IS_NOT_SET".into()),
228 ..Default::default()
229 };
230 let err = ConfigCredentials.api_key("p", &unset).unwrap_err();
231 assert!(
232 err.contains("AGIX_TEST_CREDENTIAL_THAT_IS_NOT_SET"),
233 "{err}"
234 );
235 }
236
237 #[test]
238 fn the_host_answers_only_what_the_entry_leaves_unset() {
239 let host = std::sync::Arc::new(StaticCredentials::new([(
240 "vault-backed".to_string(),
241 Secret::new(CANARY),
242 )]));
243 let chain = ConfigThen(host);
244 assert_eq!(
245 chain
246 .api_key("vault-backed", &ProviderConfig::default())
247 .unwrap()
248 .expose(),
249 CANARY
250 );
251 let named = ProviderConfig {
252 api_key_env: Some("PATH".into()),
253 ..Default::default()
254 };
255 assert_ne!(
256 chain.api_key("vault-backed", &named).unwrap().expose(),
257 CANARY,
258 "the variable the entry names wins over the host"
259 );
260 let err = chain
261 .api_key("unknown", &ProviderConfig::default())
262 .unwrap_err();
263 assert!(err.starts_with("missing api_key"), "{err}");
264 }
265
266 #[test]
267 fn the_env_source_names_what_it_looked_for() {
268 let source = EnvCredentials::new(["AGIX_TEST_CREDENTIAL_THAT_IS_NOT_SET"]);
269 let err = source
270 .api_key("main", &ProviderConfig::default())
271 .unwrap_err();
272 assert!(
273 err.contains("AGIX_TEST_CREDENTIAL_THAT_IS_NOT_SET"),
274 "{err}"
275 );
276 }
277}