Skip to main content

base/interface/
credentials.rs

1//! `CredentialSource` — where the engine's API keys come from.
2//!
3//! The default source is the environment: the variable a provider's
4//! `api_key_env` names, and `ANTHROPIC_AUTH_TOKEN` / `ANTHROPIC_API_KEY` for
5//! the provider the engine supplies when the settings define none. That is fine on a laptop and disqualifying for a host that
6//! is not allowed to have a credential on disk at all — a service pulling
7//! from a vault, an operator injecting per-request identity, anything with
8//! rotation. This trait is the seam such a host replaces.
9//!
10//! # The value never comes back as a `String`
11//!
12//! Credentials leak through the boring paths — a `{:?}` on a config struct, a
13//! telemetry payload built by serializing something that happened to hold one.
14//! [`Secret`] exists so that cannot happen by accident: it does not implement
15//! `Display`, it does not implement `Serialize`, and its `Debug` prints
16//! nothing. Reading the value takes [`Secret::expose`], which is verbose on
17//! purpose — a call to it is a place to look during review.
18
19use std::collections::HashMap;
20
21use crate::provider::ProviderConfig;
22
23/// A credential.
24///
25/// Deliberately awkward to print, serialize or otherwise let out: the only
26/// way to the value is [`expose`](Self::expose).
27#[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    /// The credential itself. Every call is a place a secret can escape;
36    /// there should be few, and each should be handing it to the thing that
37    /// authenticates with it.
38    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
53/// Where a provider's credential comes from.
54///
55/// Synchronous, and that is a real constraint: a source that has to reach a
56/// network vault must resolve eagerly and cache, because this is called while
57/// provider configuration is being turned into live clients, at startup. The
58/// dynamic case — a token that expires mid-session and must be refreshed
59/// per-request — is not this trait's job; that is what a bearer-token provider
60/// is for, and one can be handed out here inside whatever the factory builds.
61pub trait CredentialSource: Send + Sync {
62    /// The API key for `provider_id`, or a reason there is none.
63    ///
64    /// The reason is phrased without naming the provider — the caller knows
65    /// which provider it asked about and prefixes it, so the message reads the
66    /// same wherever it surfaces.
67    fn api_key(&self, provider_id: &str, config: &ProviderConfig) -> Result<Secret, String>;
68}
69
70/// What the provider entry in `settings.json` says: the environment variable
71/// its `api_key_env` names — `ANTHROPIC_AUTH_TOKEN` / `ANTHROPIC_API_KEY`
72/// for the built-in provider. The default source.
73pub 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
85/// The provider entry's own answer ([`ConfigCredentials`]) first, then a
86/// host-supplied source for whatever the entry leaves unset.
87pub 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
101/// Reads the key from the environment, trying each name in turn.
102///
103/// The other half of what the engine already did — the daemon's own client is
104/// built this way — and the smallest example of a source that keeps nothing on
105/// disk.
106pub struct EnvCredentials {
107    names: Vec<String>,
108}
109
110impl EnvCredentials {
111    /// Also holds every name back from the environment child processes
112    /// inherit ([`hold_back_credential`](crate::interface::exec::env::hold_back_credential)).
113    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    /// The names the engine has always looked at, in the order it looked.
122    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
147/// Answers from a map given up front.
148///
149/// For tests, and for a host that resolved its credentials somewhere else
150/// entirely — a vault client, a secrets mount, an operator's own prompt — and
151/// just needs to hand the answers over.
152pub 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    /// `PATH` stands in for a key variable: always set, so the test needs no
212    /// `set_var` racing other threads.
213    #[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}