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    pub keys: Vec<KeyStatus>,
235    pub custom: BTreeMap<Backend, CustomView>,
236    /// Why nothing can be saved in this state, which holds nothing yet.
237    #[serde(skip_serializing_if = "Option::is_none")]
238    pub refused: Option<String>,
239}
240
241#[derive(Debug, Default, Serialize, Deserialize)]
242#[serde(deny_unknown_fields)]
243struct Saved {
244    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
245    keys: BTreeMap<Provider, ApiKey>,
246    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
247    custom: BTreeMap<Backend, Custom>,
248}
249
250/// The environment variable that holds an API-key provider's key; `None` for Codex and Claude
251/// Code, which sign in instead.
252pub fn key_variable(provider: Provider) -> Option<&'static str> {
253    match provider {
254        Provider::Openai => Some("OPENAI_API_KEY"),
255        Provider::Anthropic => Some("ANTHROPIC_API_KEY"),
256        Provider::Gemini => Some("GEMINI_API_KEY"),
257        Provider::Codex | Provider::ClaudeAgent => None,
258    }
259}
260
261/// The key in `provider`'s variable. A set variable is the key in use: an invalid value is
262/// an error, never a reason to fall back to a saved key from another account.
263fn environment_key(provider: Provider) -> Option<Result<ApiKey, String>> {
264    let variable = key_variable(provider)?;
265    let value = crate::platform::environment::var_text(variable)?;
266    Some(
267        value
268            .parse()
269            .map_err(|error| format!("{variable} is set but invalid: {error}")),
270    )
271}
272
273/// The saved keys and custom providers, and why none can be saved here. Environment keys
274/// work in any state, so refused storage is an error only once it holds something.
275fn read(state: Option<&Path>, repo: Option<&Path>) -> Result<(Saved, Option<String>), String> {
276    let location = Location::find(state, repo)?;
277    if let Some(refusal) = location.refusal(Tokens::Providers) {
278        return match crate::platform::entry_exists(&location.directory.join(FILE)) {
279            Ok(false) => Ok((Saved::default(), Some(refusal))),
280            _ => Err(refusal),
281        };
282    }
283    let saved = Storage::inspect(state, repo, Tokens::Providers)?
284        .read(FILE)?
285        .unwrap_or_default();
286    Ok((saved, None))
287}
288
289/// What `state` has set up, without any key.
290pub fn list(state: Option<&Path>, repo: Option<&Path>) -> Result<Providers, String> {
291    let (saved, refused) = read(state, repo)?;
292    Ok(Providers {
293        keys: Provider::ALL
294            .into_iter()
295            .filter_map(|provider| {
296                let variable = key_variable(provider)?;
297                let stored = saved.keys.contains_key(&provider);
298                let availability = if environment_key(provider).is_some() {
299                    KeyAvailability::Environment { saved: stored }
300                } else if stored {
301                    KeyAvailability::Saved
302                } else {
303                    KeyAvailability::Absent
304                };
305                Some(KeyStatus {
306                    provider,
307                    variable,
308                    availability,
309                })
310            })
311            .collect(),
312        custom: saved
313            .custom
314            .iter()
315            .map(|(name, custom)| (name.clone(), custom.into()))
316            .collect(),
317        refused,
318    })
319}
320
321/// A built-in provider's key: its environment variable first, then the saved key.
322pub(crate) fn key(
323    provider: Provider,
324    state: Option<&Path>,
325    repo: Option<&Path>,
326) -> Result<Option<ApiKey>, String> {
327    if let Some(key) = environment_key(provider) {
328        return key.map(Some);
329    }
330    Ok(read(state, repo)?.0.keys.remove(&provider))
331}
332
333/// The custom provider `name`, if this machine has one.
334pub(crate) fn custom(
335    name: &Backend,
336    state: Option<&Path>,
337    repo: Option<&Path>,
338) -> Result<Option<Custom>, String> {
339    Ok(read(state, repo)?.0.custom.remove(name))
340}
341
342async fn update(
343    state: Option<&Path>,
344    repo: Option<&Path>,
345    change: impl FnOnce(&mut Saved) -> Result<(), String>,
346) -> Result<(), String> {
347    let storage = Storage::new(state, repo, Tokens::Providers)?;
348    let _lock = storage.lock(LOCK).await?;
349    let mut saved: Saved = storage.read(FILE)?.unwrap_or_default();
350    change(&mut saved)?;
351    storage.save(FILE, &saved)
352}
353
354/// Save `key` for an API-key provider.
355pub async fn save_key(
356    state: Option<&Path>,
357    repo: Option<&Path>,
358    provider: Provider,
359    key: ApiKey,
360) -> Result<(), String> {
361    if key_variable(provider).is_none() {
362        return Err(format!(
363            "{provider} signs in instead of using a key: artifactize login {provider}."
364        ));
365    }
366    update(state, repo, |saved| {
367        saved.keys.insert(provider, key);
368        Ok(())
369    })
370    .await
371}
372
373/// Forget the saved key of `provider`; its environment variable is untouched.
374pub async fn remove_key(
375    state: Option<&Path>,
376    repo: Option<&Path>,
377    provider: Provider,
378) -> Result<(), String> {
379    update(state, repo, |saved| {
380        saved.keys.remove(&provider);
381        Ok(())
382    })
383    .await
384}
385
386/// How a custom provider is saved: its key is replaced, kept from the provider it replaces,
387/// or left out.
388pub enum KeyChange {
389    Set(ApiKey),
390    Keep,
391    None,
392}
393
394/// Add the custom provider `name`, or replace it.
395pub async fn save_custom(
396    state: Option<&Path>,
397    repo: Option<&Path>,
398    name: Backend,
399    mut custom: Custom,
400    key: KeyChange,
401) -> Result<(), String> {
402    if let Some(provider) = name.builtin() {
403        return Err(format!(
404            "{provider} is a built-in provider; give the custom provider another name."
405        ));
406    }
407    update(state, repo, |saved| {
408        if let Custom::Endpoint { key: slot, .. } = &mut custom {
409            *slot = match key {
410                KeyChange::Set(key) => Some(key),
411                KeyChange::Keep => match saved.custom.get(&name) {
412                    Some(Custom::Endpoint { key, .. }) => key.clone(),
413                    _ => None,
414                },
415                KeyChange::None => None,
416            };
417        }
418        saved.custom.insert(name, custom);
419        Ok(())
420    })
421    .await
422}
423
424/// Remove the custom provider `name`.
425pub async fn remove_custom(
426    state: Option<&Path>,
427    repo: Option<&Path>,
428    name: &Backend,
429) -> Result<(), String> {
430    update(state, repo, |saved| {
431        saved
432            .custom
433            .remove(name)
434            .map(drop)
435            .ok_or_else(|| format!("No custom provider is named {name}."))
436    })
437    .await
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443
444    #[test]
445    fn key_availability_keeps_the_wire_fields_for_each_state() {
446        for (availability, source, saved) in [
447            (KeyAvailability::Absent, "absent", false),
448            (KeyAvailability::Saved, "saved", true),
449            (
450                KeyAvailability::Environment { saved: false },
451                "environment",
452                false,
453            ),
454            (
455                KeyAvailability::Environment { saved: true },
456                "environment",
457                true,
458            ),
459        ] {
460            let provider = Provider::Openai;
461            let variable = key_variable(provider).unwrap();
462            let key = KeyStatus {
463                provider,
464                variable,
465                availability,
466            };
467            assert_eq!(
468                serde_json::to_value(key).unwrap(),
469                serde_json::json!({"provider":"openai", "variable":variable, "source":source, "saved":saved}),
470            );
471        }
472    }
473}