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));
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: crate::agents::API_PROVIDERS
369 .iter()
370 .map(|api| api.provider)
371 .collect(),
372 keys: available
373 .into_iter()
374 .map(|(provider, variable, key, in_environment)| {
375 let stored = saved.keys.contains_key(&key);
376 let availability = if in_environment {
377 KeyAvailability::Environment { saved: stored }
378 } else if stored {
379 KeyAvailability::Saved
380 } else {
381 KeyAvailability::Absent
382 };
383 KeyStatus {
384 provider,
385 variable,
386 availability,
387 }
388 })
389 .collect(),
390 custom: saved
391 .custom
392 .iter()
393 .filter(|(name, _)| !inventory.contains(name.as_str()))
394 .map(|(name, custom)| (name.clone(), CustomView::visible(custom, &inventory)))
395 .collect(),
396 refused: refused.map(|reason| inventory.scrub(&reason)),
397 })
398}
399
400pub fn key(
403 provider: HttpProvider,
404 location: Result<&Location, &str>,
405) -> Result<Option<ApiKey>, String> {
406 let Some(key_provider) = KeyProvider::of(provider) else {
407 return Ok(None);
408 };
409 if let Some(key) = environment_key(provider) {
410 return key.map(Some);
411 }
412 Ok(read(location?)?.available().keys.remove(&key_provider))
413}
414
415pub(crate) fn custom(
417 name: &CustomBackendName,
418 location: &Location,
419) -> Result<Option<Custom>, String> {
420 Ok(read(location)?.available().custom.remove(name))
421}
422
423async fn update(
424 location: &Location,
425 change: impl FnOnce(&mut Saved) -> Result<(), String>,
426) -> Result<(), String> {
427 let storage = Storage::new(location)?;
428 let _lock = storage.lock(LOCK).await?;
429 let mut saved: Saved = storage.read(FILE)?.unwrap_or_default();
430 let previous = saved.secrets().map(str::to_owned).collect::<Vec<_>>();
431 change(&mut saved)?;
432 history::publish(
433 &storage,
434 previous.iter().map(String::as_str).chain(saved.secrets()),
435 )?;
436 storage.save(FILE, &saved)
437}
438
439pub async fn save_key(
441 location: &Location,
442 provider: HttpProvider,
443 key: ApiKey,
444) -> Result<(), String> {
445 let Some(key_provider) = KeyProvider::of(provider) else {
446 return Err(format!(
447 "{provider} signs in through its own CLI instead of using a key: codex login."
448 ));
449 };
450 update(location, |saved| {
451 saved.keys.insert(key_provider, key);
452 Ok(())
453 })
454 .await
455}
456
457pub async fn remove_key(location: &Location, provider: HttpProvider) -> Result<(), String> {
459 let Some(provider) = KeyProvider::of(provider) else {
460 return Ok(());
461 };
462 update(location, |saved| {
463 saved.keys.remove(&provider);
464 Ok(())
465 })
466 .await
467}
468
469pub enum KeyChange {
472 Set(ApiKey),
473 Keep,
474 None,
475}
476
477pub async fn save_custom(
479 location: &Location,
480 name: CustomBackendName,
481 mut custom: Custom,
482 key: KeyChange,
483) -> Result<(), String> {
484 if let Custom::Alias { provider } = custom
485 && !crate::agents::API_PROVIDERS
486 .iter()
487 .any(|api| api.provider == provider)
488 {
489 return Err(format!(
490 "{provider} is an agent, not an API provider, and cannot be aliased."
491 ));
492 }
493 update(location, |saved| {
494 if let Custom::Endpoint { url, key: slot, .. } = &mut custom {
495 if url.0.is_none() {
496 return Err("Enter a valid endpoint URL.".into());
497 }
498 *slot = match key {
499 KeyChange::Set(key) => Some(key),
500 KeyChange::Keep => match saved.custom.get(&name) {
501 Some(Custom::Endpoint { key, .. }) => key.clone(),
502 _ => None,
503 },
504 KeyChange::None => None,
505 };
506 }
507 saved.custom.insert(name, custom);
508 Ok(())
509 })
510 .await
511}
512
513pub async fn remove_custom(location: &Location, name: &CustomBackendName) -> Result<(), String> {
515 update(location, |saved| {
516 saved
517 .custom
518 .remove(name)
519 .map(drop)
520 .ok_or_else(|| "No custom provider has that name.".into())
521 })
522 .await
523}
524
525#[cfg(test)]
526mod tests;
527
528pub(crate) fn secret_values(
530 location: Option<&Location>,
531) -> Result<impl Iterator<Item = String>, String> {
532 use crate::json::{Object, Optional};
535
536 #[derive(Deserialize)]
537 struct CredentialFields {
538 #[serde(default)]
539 keys: Optional<Object<BTreeMap<String, Optional<String>>>>,
540 #[serde(default)]
541 custom: Optional<Object<BTreeMap<String, Optional<Object<CustomField>>>>>,
542 }
543 #[derive(Deserialize)]
544 struct CustomField {
545 #[serde(default)]
546 key: Optional<String>,
547 }
548 let stored = location
549 .filter(|location| !location.is_refused())
550 .map(|location| Storage::inspect(location)?.read::<Object<CredentialFields>>(FILE))
551 .transpose()?
552 .flatten()
553 .into_iter()
554 .flat_map(|Object(fields)| {
555 let keys = fields
556 .keys
557 .0
558 .into_iter()
559 .flat_map(|Object(keys)| keys.into_values().filter_map(|value| value.0));
560 let custom = fields.custom.0.into_iter().flat_map(|Object(custom)| {
561 custom
562 .into_values()
563 .filter_map(|value| value.0.and_then(|Object(custom)| custom.key.0))
564 });
565 keys.chain(custom)
566 .flat_map(|value| [value.trim().to_owned(), value])
567 });
568 let environment = HttpProvider::ALL
569 .into_iter()
570 .filter_map(key_variable)
571 .filter_map(crate::platform::var_text)
572 .flat_map(|value| [value.trim().to_owned(), value]);
573 Ok(stored.chain(environment))
574}