Skip to main content

artifactize_core/auth/
providers.rs

1//! API keys saved for the built-in providers and the custom providers of this machine, in
2//! `$STATE/auth/providers.json` beside the other credentials. A project only names a
3//! provider in `backend`; what the name reaches is set up here, by the person who runs it.
4
5use std::{collections::BTreeMap, path::Path};
6
7use serde::{Deserialize, Serialize};
8use url::Url;
9
10use super::storage::{Location, Storage, Tokens};
11use crate::{
12    config::{Backend, Provider},
13    llm::EndpointApi,
14};
15
16const FILE: &str = "providers.json";
17/// Serialize read-modify-write updates across processes, as Codex refreshes are.
18const LOCK: &str = "providers";
19/// Bound a pasted key: provider keys are a few hundred bytes at most.
20const MAX_KEY_BYTES: usize = 4096;
21
22/// An API key; never printed, logged or returned to a caller outside this crate.
23#[derive(Clone, PartialEq, Eq, Serialize)]
24#[serde(transparent)]
25pub struct ApiKey(String);
26
27/// A saved key passes the same checks as a typed one.
28impl<'de> Deserialize<'de> for ApiKey {
29    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
30        String::deserialize(deserializer)?
31            .parse()
32            .map_err(serde::de::Error::custom)
33    }
34}
35
36impl ApiKey {
37    pub(crate) fn expose(&self) -> &str {
38        &self.0
39    }
40}
41
42impl std::fmt::Debug for ApiKey {
43    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        formatter.write_str("ApiKey(…)")
45    }
46}
47
48impl std::str::FromStr for ApiKey {
49    type Err = String;
50    fn from_str(value: &str) -> Result<Self, Self::Err> {
51        let key = value.trim();
52        if (1..=MAX_KEY_BYTES).contains(&key.len())
53            && key.bytes().all(|byte| byte.is_ascii_graphic())
54        {
55            Ok(Self(key.to_owned()))
56        } else {
57            Err("An API key is 1–4096 printable ASCII characters without spaces.".into())
58        }
59    }
60}
61
62/// A custom endpoint's API root: http(s), without credentials, a query or a fragment, which
63/// belong in its key.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct EndpointUrl(Url);
66
67impl EndpointUrl {
68    pub fn as_str(&self) -> &str {
69        self.0.as_str().trim_end_matches('/')
70    }
71
72    pub(crate) fn into_url(self) -> Url {
73        self.0
74    }
75}
76
77impl Serialize for EndpointUrl {
78    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
79        serializer.serialize_str(self.as_str())
80    }
81}
82
83impl std::str::FromStr for EndpointUrl {
84    type Err = String;
85    fn from_str(value: &str) -> Result<Self, Self::Err> {
86        let mut url = Url::parse(value.trim()).map_err(|_| format!("{value:?} is not a URL."))?;
87        if !matches!(url.scheme(), "http" | "https") || url.host().is_none() {
88            return Err("An endpoint URL uses http:// or https:// and names a host.".into());
89        }
90        if !url.username().is_empty()
91            || url.password().is_some()
92            || url.query().is_some()
93            || url.fragment().is_some()
94        {
95            return Err(
96                "An endpoint URL has no credentials, query or fragment; the key goes in its own field."
97                    .into(),
98            );
99        }
100        if url.path().len() > 1 && url.path().ends_with('/') {
101            let path = url.path().trim_end_matches('/').to_owned();
102            url.set_path(&path);
103        }
104        Ok(Self(url))
105    }
106}
107
108impl<'de> Deserialize<'de> for EndpointUrl {
109    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
110        String::deserialize(deserializer)?
111            .parse()
112            .map_err(serde::de::Error::custom)
113    }
114}
115
116/// What a custom provider reaches.
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
119pub enum Custom {
120    /// A built-in provider under another name, with its sign-in or key.
121    Alias { provider: Provider },
122    /// An API at a URL, with an optional key.
123    Endpoint {
124        api: EndpointApi,
125        url: EndpointUrl,
126        #[serde(default, skip_serializing_if = "Option::is_none")]
127        key: Option<ApiKey>,
128    },
129}
130
131/// A custom provider as Settings and `provider list` show it: never its key.
132#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
133#[serde(tag = "kind", rename_all = "lowercase")]
134pub enum CustomView {
135    Alias {
136        provider: Provider,
137    },
138    Endpoint {
139        api: EndpointApi,
140        url: EndpointUrl,
141        key: bool,
142    },
143}
144
145impl From<&Custom> for CustomView {
146    fn from(custom: &Custom) -> Self {
147        match custom {
148            Custom::Alias { provider } => Self::Alias {
149                provider: *provider,
150            },
151            Custom::Endpoint { api, url, key } => Self::Endpoint {
152                api: *api,
153                url: url.clone(),
154                key: key.is_some(),
155            },
156        }
157    }
158}
159
160/// Where a built-in provider's key comes from.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
162#[serde(rename_all = "lowercase")]
163pub enum KeySource {
164    Environment,
165    Saved,
166    Absent,
167}
168
169#[derive(Debug, Clone, Copy)]
170enum KeyAvailability {
171    Absent,
172    Saved,
173    Environment { saved: bool },
174}
175
176/// A built-in API-key provider's key, as Settings and `doctor` show it.
177#[derive(Debug, Clone)]
178pub struct KeyStatus {
179    provider: Provider,
180    variable: &'static str,
181    availability: KeyAvailability,
182}
183
184impl KeyStatus {
185    pub fn provider(&self) -> Provider {
186        self.provider
187    }
188
189    /// The environment variable read first.
190    pub fn variable(&self) -> &'static str {
191        self.variable
192    }
193
194    pub fn source(&self) -> KeySource {
195        match self.availability {
196            KeyAvailability::Absent => KeySource::Absent,
197            KeyAvailability::Saved => KeySource::Saved,
198            KeyAvailability::Environment { .. } => KeySource::Environment,
199        }
200    }
201
202    /// Whether a key is saved here, also while the variable comes first.
203    pub fn saved(&self) -> bool {
204        match self.availability {
205            KeyAvailability::Absent => false,
206            KeyAvailability::Saved => true,
207            KeyAvailability::Environment { saved } => saved,
208        }
209    }
210}
211
212impl Serialize for KeyStatus {
213    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
214        #[derive(Serialize)]
215        struct Wire {
216            provider: Provider,
217            variable: &'static str,
218            source: KeySource,
219            saved: bool,
220        }
221        Wire {
222            provider: self.provider(),
223            variable: self.variable(),
224            source: self.source(),
225            saved: self.saved(),
226        }
227        .serialize(serializer)
228    }
229}
230
231/// The providers this machine has set up.
232#[derive(Debug, Clone, Serialize)]
233pub struct Providers {
234    #[serde(skip)]
235    pub alias_targets: Vec<Provider>,
236    pub keys: Vec<KeyStatus>,
237    pub custom: BTreeMap<Backend, CustomView>,
238    /// Why nothing can be saved in this state, which holds nothing yet.
239    #[serde(skip_serializing_if = "Option::is_none")]
240    pub refused: Option<String>,
241}
242
243#[derive(Debug, Default, Serialize, Deserialize)]
244#[serde(deny_unknown_fields)]
245struct Saved {
246    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
247    keys: BTreeMap<Provider, ApiKey>,
248    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
249    custom: BTreeMap<Backend, Custom>,
250}
251
252/// The environment variable that holds an API-key provider's key; `None` for Codex and Claude
253/// Code, which sign in instead.
254pub fn key_variable(provider: Provider) -> Option<&'static str> {
255    match provider {
256        Provider::Openai => Some("OPENAI_API_KEY"),
257        Provider::Anthropic => Some("ANTHROPIC_API_KEY"),
258        Provider::Gemini => Some("GEMINI_API_KEY"),
259        Provider::Codex | Provider::ClaudeAgent => None,
260    }
261}
262
263/// The key in `provider`'s variable. A set variable is the key in use: an invalid value is
264/// an error, never a reason to fall back to a saved key from another account.
265fn environment_key(provider: Provider) -> Option<Result<ApiKey, String>> {
266    let variable = key_variable(provider)?;
267    let value = crate::platform::environment::var_text(variable)?;
268    Some(
269        value
270            .parse()
271            .map_err(|error| format!("{variable} is set but invalid: {error}")),
272    )
273}
274
275/// The saved keys and custom providers, and why none can be saved here. Environment keys
276/// work in any state, so refused storage is an error only once it holds something.
277fn read(state: Option<&Path>, repo: Option<&Path>) -> Result<(Saved, Option<String>), String> {
278    let location = Location::find(state, repo)?;
279    if let Some(refusal) = location.refusal(Tokens::Providers) {
280        return match crate::platform::entry_exists(&location.directory.join(FILE)) {
281            Ok(false) => Ok((Saved::default(), Some(refusal))),
282            _ => Err(refusal),
283        };
284    }
285    let saved = Storage::inspect(state, repo, Tokens::Providers)?
286        .read(FILE)?
287        .unwrap_or_default();
288    Ok((saved, None))
289}
290
291fn can_alias(provider: Provider) -> bool {
292    !matches!(provider, Provider::ClaudeAgent)
293}
294
295/// What `state` has set up, without any key.
296pub fn list(state: Option<&Path>, repo: Option<&Path>) -> Result<Providers, String> {
297    let (saved, refused) = read(state, repo)?;
298    Ok(Providers {
299        alias_targets: Provider::ALL
300            .into_iter()
301            .filter(|provider| can_alias(*provider))
302            .collect(),
303        keys: Provider::ALL
304            .into_iter()
305            .filter_map(|provider| {
306                let variable = key_variable(provider)?;
307                let stored = saved.keys.contains_key(&provider);
308                let availability = if environment_key(provider).is_some() {
309                    KeyAvailability::Environment { saved: stored }
310                } else if stored {
311                    KeyAvailability::Saved
312                } else {
313                    KeyAvailability::Absent
314                };
315                Some(KeyStatus {
316                    provider,
317                    variable,
318                    availability,
319                })
320            })
321            .collect(),
322        custom: saved
323            .custom
324            .iter()
325            .map(|(name, custom)| (name.clone(), custom.into()))
326            .collect(),
327        refused,
328    })
329}
330
331/// A built-in provider's key: its environment variable first, then the saved key.
332pub(crate) fn key(
333    provider: Provider,
334    state: Option<&Path>,
335    repo: Option<&Path>,
336) -> Result<Option<ApiKey>, String> {
337    if let Some(key) = environment_key(provider) {
338        return key.map(Some);
339    }
340    Ok(read(state, repo)?.0.keys.remove(&provider))
341}
342
343/// The custom provider `name`, if this machine has one.
344pub(crate) fn custom(
345    name: &Backend,
346    state: Option<&Path>,
347    repo: Option<&Path>,
348) -> Result<Option<Custom>, String> {
349    Ok(read(state, repo)?.0.custom.remove(name))
350}
351
352async fn update(
353    state: Option<&Path>,
354    repo: Option<&Path>,
355    change: impl FnOnce(&mut Saved) -> Result<(), String>,
356) -> Result<(), String> {
357    let storage = Storage::new(state, repo, Tokens::Providers)?;
358    let _lock = storage.lock(LOCK).await?;
359    let mut saved: Saved = storage.read(FILE)?.unwrap_or_default();
360    change(&mut saved)?;
361    storage.save(FILE, &saved)
362}
363
364/// Save `key` for an API-key provider.
365pub async fn save_key(
366    state: Option<&Path>,
367    repo: Option<&Path>,
368    provider: Provider,
369    key: ApiKey,
370) -> Result<(), String> {
371    if key_variable(provider).is_none() {
372        return Err(format!(
373            "{provider} signs in instead of using a key: artifactize login {provider}."
374        ));
375    }
376    update(state, repo, |saved| {
377        saved.keys.insert(provider, key);
378        Ok(())
379    })
380    .await
381}
382
383/// Forget the saved key of `provider`; its environment variable is untouched.
384pub async fn remove_key(
385    state: Option<&Path>,
386    repo: Option<&Path>,
387    provider: Provider,
388) -> Result<(), String> {
389    update(state, repo, |saved| {
390        saved.keys.remove(&provider);
391        Ok(())
392    })
393    .await
394}
395
396/// How a custom provider is saved: its key is replaced, kept from the provider it replaces,
397/// or left out.
398pub enum KeyChange {
399    Set(ApiKey),
400    Keep,
401    None,
402}
403
404/// Add the custom provider `name`, or replace it.
405pub async fn save_custom(
406    state: Option<&Path>,
407    repo: Option<&Path>,
408    name: Backend,
409    mut custom: Custom,
410    key: KeyChange,
411) -> Result<(), String> {
412    if name.is_reserved_custom() {
413        return Err(format!(
414            "{name} is a built-in provider; give the custom provider another name."
415        ));
416    }
417    if let Custom::Alias { provider } = &custom
418        && !can_alias(*provider)
419    {
420        return Err(format!(
421            "{provider} uses a native CLI and cannot be aliased by a custom provider."
422        ));
423    }
424    update(state, repo, |saved| {
425        if let Custom::Endpoint { key: slot, .. } = &mut custom {
426            *slot = match key {
427                KeyChange::Set(key) => Some(key),
428                KeyChange::Keep => match saved.custom.get(&name) {
429                    Some(Custom::Endpoint { key, .. }) => key.clone(),
430                    _ => None,
431                },
432                KeyChange::None => None,
433            };
434        }
435        saved.custom.insert(name, custom);
436        Ok(())
437    })
438    .await
439}
440
441/// Remove the custom provider `name`.
442pub async fn remove_custom(
443    state: Option<&Path>,
444    repo: Option<&Path>,
445    name: &Backend,
446) -> Result<(), String> {
447    update(state, repo, |saved| {
448        saved
449            .custom
450            .remove(name)
451            .map(drop)
452            .ok_or_else(|| format!("No custom provider is named {name}."))
453    })
454    .await
455}
456
457#[cfg(test)]
458mod tests {
459    use super::*;
460
461    #[test]
462    fn key_availability_keeps_the_wire_fields_for_each_state() {
463        for (availability, source, saved) in [
464            (KeyAvailability::Absent, "absent", false),
465            (KeyAvailability::Saved, "saved", true),
466            (
467                KeyAvailability::Environment { saved: false },
468                "environment",
469                false,
470            ),
471            (
472                KeyAvailability::Environment { saved: true },
473                "environment",
474                true,
475            ),
476        ] {
477            let provider = Provider::Openai;
478            let variable = key_variable(provider).unwrap();
479            let key = KeyStatus {
480                provider,
481                variable,
482                availability,
483            };
484            assert_eq!(
485                serde_json::to_value(key).unwrap(),
486                serde_json::json!({"provider":"openai", "variable":variable, "source":source, "saved":saved}),
487            );
488        }
489    }
490}