1use std::collections::BTreeMap;
4
5use serde::{Deserialize, Serialize};
6use url::Url;
7
8use super::storage::{Location, Storage};
9use crate::{
10 llm::EndpointApi,
11 names::{CustomBackendName, HttpProvider},
12 secret::{Inventory, history},
13};
14
15pub(crate) const FILE: &str = "providers.json";
16const LOCK: &str = "providers";
18const MAX_KEY_BYTES: usize = 4096;
20
21#[derive(Clone, PartialEq, Eq, Serialize)]
23#[serde(transparent)]
24pub struct ApiKey(String);
25
26impl<'de> Deserialize<'de> for ApiKey {
28 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
29 String::deserialize(deserializer)?
30 .parse()
31 .map_err(serde::de::Error::custom)
32 }
33}
34
35impl ApiKey {
36 pub(crate) fn expose(&self) -> &str {
37 &self.0
38 }
39}
40
41impl std::fmt::Debug for ApiKey {
42 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 formatter.write_str("ApiKey(…)")
44 }
45}
46
47impl std::str::FromStr for ApiKey {
48 type Err = String;
49 fn from_str(value: &str) -> Result<Self, Self::Err> {
50 let key = value.trim();
51 if (1..=MAX_KEY_BYTES).contains(&key.len())
52 && key.bytes().all(|byte| byte.is_ascii_graphic())
53 {
54 Ok(Self(key.to_owned()))
55 } else {
56 Err("An API key is 1–4096 printable ASCII characters without spaces.".into())
57 }
58 }
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct EndpointUrl(Option<Url>);
65
66impl EndpointUrl {
67 pub fn as_str(&self) -> &str {
69 self.0
70 .as_ref()
71 .map_or("", |url| url.as_str().trim_end_matches('/'))
72 }
73
74 pub(crate) fn into_url(self) -> Url {
75 self.0.expect("only stored endpoint URLs may be routed")
76 }
77
78 fn visible(&self, inventory: &Inventory) -> Self {
79 if inventory.contains(self.as_str()) {
80 Self(None)
81 } else {
82 self.clone()
83 }
84 }
85}
86
87impl Serialize for EndpointUrl {
88 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
89 serializer.serialize_str(self.as_str())
90 }
91}
92
93impl std::str::FromStr for EndpointUrl {
94 type Err = String;
95 fn from_str(value: &str) -> Result<Self, Self::Err> {
96 let mut url = Url::parse(value.trim()).map_err(|_| "Enter a valid endpoint URL.")?;
97 if !matches!(url.scheme(), "http" | "https") || url.host().is_none() {
98 return Err("An endpoint URL uses http:// or https:// and names a host.".into());
99 }
100 if !url.username().is_empty()
101 || url.password().is_some()
102 || url.query().is_some()
103 || url.fragment().is_some()
104 {
105 return Err(
106 "An endpoint URL has no credentials, query or fragment; the key goes in its own field."
107 .into(),
108 );
109 }
110 if url.path().len() > 1 && url.path().ends_with('/') {
111 let path = url.path().trim_end_matches('/').to_owned();
112 url.set_path(&path);
113 }
114 Ok(Self(Some(url)))
115 }
116}
117
118impl<'de> Deserialize<'de> for EndpointUrl {
119 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
120 String::deserialize(deserializer)?
121 .parse()
122 .map_err(serde::de::Error::custom)
123 }
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
129pub enum Custom {
130 Alias { provider: HttpProvider },
132 Endpoint {
134 api: EndpointApi,
135 url: EndpointUrl,
136 #[serde(default, skip_serializing_if = "Option::is_none")]
137 key: Option<ApiKey>,
138 },
139}
140
141#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
143#[serde(tag = "kind", rename_all = "lowercase")]
144pub enum CustomView {
145 Alias {
146 provider: HttpProvider,
147 },
148 Endpoint {
149 api: EndpointApi,
150 url: EndpointUrl,
151 key: bool,
152 },
153}
154
155impl From<&Custom> for CustomView {
156 fn from(custom: &Custom) -> Self {
157 let inventory = Inventory::new(match custom {
158 Custom::Endpoint { key, .. } => key.as_ref().map(|key| key.expose().to_owned()),
159 Custom::Alias { .. } => None,
160 });
161 Self::visible(custom, &inventory)
162 }
163}
164
165impl CustomView {
166 fn visible(custom: &Custom, inventory: &Inventory) -> Self {
167 match custom {
168 Custom::Alias { provider } => Self::Alias {
169 provider: *provider,
170 },
171 Custom::Endpoint { api, url, key } => Self::Endpoint {
172 api: *api,
173 url: url.visible(inventory),
174 key: key.is_some(),
175 },
176 }
177 }
178}
179
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
182#[serde(rename_all = "lowercase")]
183pub enum KeySource {
184 Environment,
185 Saved,
186 Absent,
187}
188
189#[derive(Debug, Clone, Copy)]
190enum KeyAvailability {
191 Absent,
192 Saved,
193 Environment { saved: bool },
194}
195
196#[derive(Debug, Clone)]
198pub struct KeyStatus {
199 provider: HttpProvider,
200 variable: &'static str,
201 availability: KeyAvailability,
202}
203
204impl KeyStatus {
205 pub fn provider(&self) -> HttpProvider {
206 self.provider
207 }
208
209 pub fn variable(&self) -> &'static str {
211 self.variable
212 }
213
214 pub fn source(&self) -> KeySource {
215 match self.availability {
216 KeyAvailability::Absent => KeySource::Absent,
217 KeyAvailability::Saved => KeySource::Saved,
218 KeyAvailability::Environment { .. } => KeySource::Environment,
219 }
220 }
221
222 pub fn saved(&self) -> bool {
224 match self.availability {
225 KeyAvailability::Absent => false,
226 KeyAvailability::Saved => true,
227 KeyAvailability::Environment { saved } => saved,
228 }
229 }
230}
231
232impl Serialize for KeyStatus {
233 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
234 #[derive(Serialize)]
235 struct Wire {
236 provider: HttpProvider,
237 variable: &'static str,
238 source: KeySource,
239 saved: bool,
240 }
241 Wire {
242 provider: self.provider(),
243 variable: self.variable(),
244 source: self.source(),
245 saved: self.saved(),
246 }
247 .serialize(serializer)
248 }
249}
250
251#[derive(Debug, Clone, Serialize)]
253pub struct Providers {
254 #[serde(skip)]
255 pub alias_targets: Vec<HttpProvider>,
256 pub keys: Vec<KeyStatus>,
257 pub custom: BTreeMap<CustomBackendName, CustomView>,
258 #[serde(skip_serializing_if = "Option::is_none")]
260 pub refused: Option<String>,
261}
262
263#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd, Serialize, Deserialize)]
264#[serde(rename_all = "lowercase")]
265enum KeyProvider {
266 Openai,
267 Anthropic,
268 Gemini,
269}
270
271impl KeyProvider {
272 fn of(provider: HttpProvider) -> Option<Self> {
273 match provider {
274 HttpProvider::Openai => Some(Self::Openai),
275 HttpProvider::Anthropic => Some(Self::Anthropic),
276 HttpProvider::Gemini => Some(Self::Gemini),
277 HttpProvider::Codex => None,
278 }
279 }
280}
281
282#[derive(Debug, Default, Serialize, Deserialize)]
283#[serde(deny_unknown_fields)]
284struct Saved {
285 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
286 keys: BTreeMap<KeyProvider, ApiKey>,
287 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
288 custom: BTreeMap<CustomBackendName, Custom>,
289}
290
291impl Saved {
292 fn secrets(&self) -> impl Iterator<Item = &str> {
293 self.keys
294 .values()
295 .chain(self.custom.values().filter_map(|custom| match custom {
296 Custom::Endpoint { key, .. } => key.as_ref(),
297 Custom::Alias { .. } => None,
298 }))
299 .map(ApiKey::expose)
300 }
301}
302
303pub fn key_variable(provider: HttpProvider) -> Option<&'static str> {
306 match provider {
307 HttpProvider::Openai => Some("OPENAI_API_KEY"),
308 HttpProvider::Anthropic => Some("ANTHROPIC_API_KEY"),
309 HttpProvider::Gemini => Some("GEMINI_API_KEY"),
310 HttpProvider::Codex => None,
311 }
312}
313
314fn environment_key(provider: HttpProvider) -> Option<Result<ApiKey, String>> {
317 let variable = key_variable(provider)?;
318 let value = crate::platform::var(variable)?;
319 Some(
320 crate::platform::as_text(&value)
321 .map_err(str::to_owned)
322 .and_then(str::parse)
323 .map_err(|error| format!("{variable} is set but invalid: {error}")),
324 )
325}
326
327enum Configuration {
328 Saved(Saved),
329 Refused(String),
330}
331
332impl Configuration {
333 fn available(self) -> Saved {
334 match self {
335 Self::Saved(saved) => saved,
336 Self::Refused(_) => Saved::default(),
337 }
338 }
339}
340
341fn read(location: &Location) -> Result<Configuration, String> {
343 if let Some(refusal) = location.refusal(FILE)? {
344 return Ok(Configuration::Refused(refusal));
345 }
346 let saved = Storage::inspect(location)?.read(FILE)?.unwrap_or_default();
347 Ok(Configuration::Saved(saved))
348}
349
350pub fn list(location: &Location) -> Result<Providers, String> {
352 let mut inventory = Inventory::read(Some(location), Some(location));
353 let configured = read(location).map_err(|error| inventory.scrub(&error))?;
354 let (saved, refused) = match configured {
355 Configuration::Saved(saved) => (saved, None),
356 Configuration::Refused(refusal) => (Saved::default(), Some(refusal)),
357 };
358 inventory.merge(Inventory::new(saved.secrets().map(str::to_owned)));
359 let available = HttpProvider::ALL
360 .into_iter()
361 .filter_map(|provider| {
362 let variable = key_variable(provider)?;
363 let key = KeyProvider::of(provider)?;
364 Some((provider, variable, key, environment_key(provider).is_some()))
365 })
366 .collect::<Vec<_>>();
367 Ok(Providers {
368 alias_targets: HttpProvider::ALL.to_vec(),
369 keys: available
370 .into_iter()
371 .map(|(provider, variable, key, in_environment)| {
372 let stored = saved.keys.contains_key(&key);
373 let availability = if in_environment {
374 KeyAvailability::Environment { saved: stored }
375 } else if stored {
376 KeyAvailability::Saved
377 } else {
378 KeyAvailability::Absent
379 };
380 KeyStatus {
381 provider,
382 variable,
383 availability,
384 }
385 })
386 .collect(),
387 custom: saved
388 .custom
389 .iter()
390 .filter(|(name, _)| !inventory.contains(name.as_str()))
391 .map(|(name, custom)| (name.clone(), CustomView::visible(custom, &inventory)))
392 .collect(),
393 refused: refused.map(|reason| inventory.scrub(&reason)),
394 })
395}
396
397pub fn key(
400 provider: HttpProvider,
401 location: Result<&Location, &str>,
402) -> Result<Option<ApiKey>, String> {
403 let Some(key_provider) = KeyProvider::of(provider) else {
404 return Ok(None);
405 };
406 if let Some(key) = environment_key(provider) {
407 return key.map(Some);
408 }
409 Ok(read(location?)?.available().keys.remove(&key_provider))
410}
411
412pub(crate) fn custom(
414 name: &CustomBackendName,
415 location: &Location,
416) -> Result<Option<Custom>, String> {
417 Ok(read(location)?.available().custom.remove(name))
418}
419
420async fn update(
421 location: &Location,
422 change: impl FnOnce(&mut Saved) -> Result<(), String>,
423) -> Result<(), String> {
424 let storage = Storage::new(location)?;
425 let _lock = storage.lock(LOCK).await?;
426 let mut saved: Saved = storage.read(FILE)?.unwrap_or_default();
427 let previous = saved.secrets().map(str::to_owned).collect::<Vec<_>>();
428 change(&mut saved)?;
429 history::publish(
430 &storage,
431 previous.iter().map(String::as_str).chain(saved.secrets()),
432 )?;
433 storage.save(FILE, &saved)
434}
435
436pub async fn save_key(
438 location: &Location,
439 provider: HttpProvider,
440 key: ApiKey,
441) -> Result<(), String> {
442 let Some(key_provider) = KeyProvider::of(provider) else {
443 return Err(format!(
444 "{provider} signs in instead of using a key: artifactize login {provider}."
445 ));
446 };
447 update(location, |saved| {
448 saved.keys.insert(key_provider, key);
449 Ok(())
450 })
451 .await
452}
453
454pub async fn remove_key(location: &Location, provider: HttpProvider) -> Result<(), String> {
456 let Some(provider) = KeyProvider::of(provider) else {
457 return Ok(());
458 };
459 update(location, |saved| {
460 saved.keys.remove(&provider);
461 Ok(())
462 })
463 .await
464}
465
466pub enum KeyChange {
469 Set(ApiKey),
470 Keep,
471 None,
472}
473
474pub async fn save_custom(
476 location: &Location,
477 name: CustomBackendName,
478 mut custom: Custom,
479 key: KeyChange,
480) -> Result<(), String> {
481 update(location, |saved| {
482 if let Custom::Endpoint { url, key: slot, .. } = &mut custom {
483 if url.0.is_none() {
484 return Err("Enter a valid endpoint URL.".into());
485 }
486 *slot = match key {
487 KeyChange::Set(key) => Some(key),
488 KeyChange::Keep => match saved.custom.get(&name) {
489 Some(Custom::Endpoint { key, .. }) => key.clone(),
490 _ => None,
491 },
492 KeyChange::None => None,
493 };
494 }
495 saved.custom.insert(name, custom);
496 Ok(())
497 })
498 .await
499}
500
501pub async fn remove_custom(location: &Location, name: &CustomBackendName) -> Result<(), String> {
503 update(location, |saved| {
504 saved
505 .custom
506 .remove(name)
507 .map(drop)
508 .ok_or_else(|| "No custom provider has that name.".into())
509 })
510 .await
511}
512
513#[cfg(test)]
514mod tests;
515
516pub(crate) fn secret_values(
518 location: Option<&Location>,
519) -> Result<impl Iterator<Item = String>, String> {
520 use crate::json::{Object, Optional};
523
524 #[derive(Deserialize)]
525 struct CredentialFields {
526 #[serde(default)]
527 keys: Optional<Object<BTreeMap<String, Optional<String>>>>,
528 #[serde(default)]
529 custom: Optional<Object<BTreeMap<String, Optional<Object<CustomField>>>>>,
530 }
531 #[derive(Deserialize)]
532 struct CustomField {
533 #[serde(default)]
534 key: Optional<String>,
535 }
536 let stored = location
537 .filter(|location| !location.is_refused())
538 .map(|location| Storage::inspect(location)?.read::<Object<CredentialFields>>(FILE))
539 .transpose()?
540 .flatten()
541 .into_iter()
542 .flat_map(|Object(fields)| {
543 let keys = fields
544 .keys
545 .0
546 .into_iter()
547 .flat_map(|Object(keys)| keys.into_values().filter_map(|value| value.0));
548 let custom = fields.custom.0.into_iter().flat_map(|Object(custom)| {
549 custom
550 .into_values()
551 .filter_map(|value| value.0.and_then(|Object(custom)| custom.key.0))
552 });
553 keys.chain(custom)
554 .flat_map(|value| [value.trim().to_owned(), value])
555 });
556 let environment = HttpProvider::ALL
557 .into_iter()
558 .filter_map(key_variable)
559 .filter_map(crate::platform::var_text)
560 .flat_map(|value| [value.trim().to_owned(), value]);
561 Ok(stored.chain(environment))
562}