use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use url::Url;
use super::storage::{Location, Storage};
use crate::{
llm::EndpointApi,
names::{CustomBackendName, HttpProvider},
secret::{Inventory, history},
};
pub(crate) const FILE: &str = "providers.json";
const LOCK: &str = "providers";
const MAX_KEY_BYTES: usize = 4096;
#[derive(Clone, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct ApiKey(String);
impl<'de> Deserialize<'de> for ApiKey {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
String::deserialize(deserializer)?
.parse()
.map_err(serde::de::Error::custom)
}
}
impl ApiKey {
pub(crate) fn expose(&self) -> &str {
&self.0
}
}
impl std::fmt::Debug for ApiKey {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("ApiKey(…)")
}
}
impl std::str::FromStr for ApiKey {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let key = value.trim();
if (1..=MAX_KEY_BYTES).contains(&key.len())
&& key.bytes().all(|byte| byte.is_ascii_graphic())
{
Ok(Self(key.to_owned()))
} else {
Err("An API key is 1–4096 printable ASCII characters without spaces.".into())
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EndpointUrl(Option<Url>);
impl EndpointUrl {
pub fn as_str(&self) -> &str {
self.0
.as_ref()
.map_or("", |url| url.as_str().trim_end_matches('/'))
}
pub(crate) fn into_url(self) -> Url {
self.0.expect("only stored endpoint URLs may be routed")
}
fn visible(&self, inventory: &Inventory) -> Self {
if inventory.contains(self.as_str()) {
Self(None)
} else {
self.clone()
}
}
}
impl Serialize for EndpointUrl {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl std::str::FromStr for EndpointUrl {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let mut url = Url::parse(value.trim()).map_err(|_| "Enter a valid endpoint URL.")?;
if !matches!(url.scheme(), "http" | "https") || url.host().is_none() {
return Err("An endpoint URL uses http:// or https:// and names a host.".into());
}
if !url.username().is_empty()
|| url.password().is_some()
|| url.query().is_some()
|| url.fragment().is_some()
{
return Err(
"An endpoint URL has no credentials, query or fragment; the key goes in its own field."
.into(),
);
}
if url.path().len() > 1 && url.path().ends_with('/') {
let path = url.path().trim_end_matches('/').to_owned();
url.set_path(&path);
}
Ok(Self(Some(url)))
}
}
impl<'de> Deserialize<'de> for EndpointUrl {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
String::deserialize(deserializer)?
.parse()
.map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
pub enum Custom {
Alias { provider: HttpProvider },
Endpoint {
api: EndpointApi,
url: EndpointUrl,
#[serde(default, skip_serializing_if = "Option::is_none")]
key: Option<ApiKey>,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum CustomView {
Alias {
provider: HttpProvider,
},
Endpoint {
api: EndpointApi,
url: EndpointUrl,
key: bool,
},
}
impl From<&Custom> for CustomView {
fn from(custom: &Custom) -> Self {
let inventory = Inventory::new(match custom {
Custom::Endpoint { key, .. } => key.as_ref().map(|key| key.expose().to_owned()),
Custom::Alias { .. } => None,
});
Self::visible(custom, &inventory)
}
}
impl CustomView {
fn visible(custom: &Custom, inventory: &Inventory) -> Self {
match custom {
Custom::Alias { provider } => Self::Alias {
provider: *provider,
},
Custom::Endpoint { api, url, key } => Self::Endpoint {
api: *api,
url: url.visible(inventory),
key: key.is_some(),
},
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum KeySource {
Environment,
Saved,
Absent,
}
#[derive(Debug, Clone, Copy)]
enum KeyAvailability {
Absent,
Saved,
Environment { saved: bool },
}
#[derive(Debug, Clone)]
pub struct KeyStatus {
provider: HttpProvider,
variable: &'static str,
availability: KeyAvailability,
}
impl KeyStatus {
pub fn provider(&self) -> HttpProvider {
self.provider
}
pub fn variable(&self) -> &'static str {
self.variable
}
pub fn source(&self) -> KeySource {
match self.availability {
KeyAvailability::Absent => KeySource::Absent,
KeyAvailability::Saved => KeySource::Saved,
KeyAvailability::Environment { .. } => KeySource::Environment,
}
}
pub fn saved(&self) -> bool {
match self.availability {
KeyAvailability::Absent => false,
KeyAvailability::Saved => true,
KeyAvailability::Environment { saved } => saved,
}
}
}
impl Serialize for KeyStatus {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
#[derive(Serialize)]
struct Wire {
provider: HttpProvider,
variable: &'static str,
source: KeySource,
saved: bool,
}
Wire {
provider: self.provider(),
variable: self.variable(),
source: self.source(),
saved: self.saved(),
}
.serialize(serializer)
}
}
#[derive(Debug, Clone, Serialize)]
pub struct Providers {
#[serde(skip)]
pub alias_targets: Vec<HttpProvider>,
pub keys: Vec<KeyStatus>,
pub custom: BTreeMap<CustomBackendName, CustomView>,
#[serde(skip_serializing_if = "Option::is_none")]
pub refused: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum KeyProvider {
Openai,
Anthropic,
Gemini,
}
impl KeyProvider {
fn of(provider: HttpProvider) -> Option<Self> {
match provider {
HttpProvider::Openai => Some(Self::Openai),
HttpProvider::Anthropic => Some(Self::Anthropic),
HttpProvider::Gemini => Some(Self::Gemini),
HttpProvider::Codex => None,
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Saved {
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
keys: BTreeMap<KeyProvider, ApiKey>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
custom: BTreeMap<CustomBackendName, Custom>,
}
impl Saved {
fn secrets(&self) -> impl Iterator<Item = &str> {
self.keys
.values()
.chain(self.custom.values().filter_map(|custom| match custom {
Custom::Endpoint { key, .. } => key.as_ref(),
Custom::Alias { .. } => None,
}))
.map(ApiKey::expose)
}
}
pub fn key_variable(provider: HttpProvider) -> Option<&'static str> {
match provider {
HttpProvider::Openai => Some("OPENAI_API_KEY"),
HttpProvider::Anthropic => Some("ANTHROPIC_API_KEY"),
HttpProvider::Gemini => Some("GEMINI_API_KEY"),
HttpProvider::Codex => None,
}
}
fn environment_key(provider: HttpProvider) -> Option<Result<ApiKey, String>> {
let variable = key_variable(provider)?;
let value = crate::platform::var(variable)?;
Some(
crate::platform::as_text(&value)
.map_err(str::to_owned)
.and_then(str::parse)
.map_err(|error| format!("{variable} is set but invalid: {error}")),
)
}
enum Configuration {
Saved(Saved),
Refused(String),
}
impl Configuration {
fn available(self) -> Saved {
match self {
Self::Saved(saved) => saved,
Self::Refused(_) => Saved::default(),
}
}
}
fn read(location: &Location) -> Result<Configuration, String> {
if let Some(refusal) = location.refusal(FILE)? {
return Ok(Configuration::Refused(refusal));
}
let saved = Storage::inspect(location)?.read(FILE)?.unwrap_or_default();
Ok(Configuration::Saved(saved))
}
pub fn list(location: &Location) -> Result<Providers, String> {
let mut inventory = Inventory::read(Some(location), Some(location));
let configured = read(location).map_err(|error| inventory.scrub(&error))?;
let (saved, refused) = match configured {
Configuration::Saved(saved) => (saved, None),
Configuration::Refused(refusal) => (Saved::default(), Some(refusal)),
};
inventory.merge(Inventory::new(saved.secrets().map(str::to_owned)));
let available = HttpProvider::ALL
.into_iter()
.filter_map(|provider| {
let variable = key_variable(provider)?;
let key = KeyProvider::of(provider)?;
Some((provider, variable, key, environment_key(provider).is_some()))
})
.collect::<Vec<_>>();
Ok(Providers {
alias_targets: HttpProvider::ALL.to_vec(),
keys: available
.into_iter()
.map(|(provider, variable, key, in_environment)| {
let stored = saved.keys.contains_key(&key);
let availability = if in_environment {
KeyAvailability::Environment { saved: stored }
} else if stored {
KeyAvailability::Saved
} else {
KeyAvailability::Absent
};
KeyStatus {
provider,
variable,
availability,
}
})
.collect(),
custom: saved
.custom
.iter()
.filter(|(name, _)| !inventory.contains(name.as_str()))
.map(|(name, custom)| (name.clone(), CustomView::visible(custom, &inventory)))
.collect(),
refused: refused.map(|reason| inventory.scrub(&reason)),
})
}
pub fn key(
provider: HttpProvider,
location: Result<&Location, &str>,
) -> Result<Option<ApiKey>, String> {
let Some(key_provider) = KeyProvider::of(provider) else {
return Ok(None);
};
if let Some(key) = environment_key(provider) {
return key.map(Some);
}
Ok(read(location?)?.available().keys.remove(&key_provider))
}
pub(crate) fn custom(
name: &CustomBackendName,
location: &Location,
) -> Result<Option<Custom>, String> {
Ok(read(location)?.available().custom.remove(name))
}
async fn update(
location: &Location,
change: impl FnOnce(&mut Saved) -> Result<(), String>,
) -> Result<(), String> {
let storage = Storage::new(location)?;
let _lock = storage.lock(LOCK).await?;
let mut saved: Saved = storage.read(FILE)?.unwrap_or_default();
let previous = saved.secrets().map(str::to_owned).collect::<Vec<_>>();
change(&mut saved)?;
history::publish(
&storage,
previous.iter().map(String::as_str).chain(saved.secrets()),
)?;
storage.save(FILE, &saved)
}
pub async fn save_key(
location: &Location,
provider: HttpProvider,
key: ApiKey,
) -> Result<(), String> {
let Some(key_provider) = KeyProvider::of(provider) else {
return Err(format!(
"{provider} signs in instead of using a key: artifactize login {provider}."
));
};
update(location, |saved| {
saved.keys.insert(key_provider, key);
Ok(())
})
.await
}
pub async fn remove_key(location: &Location, provider: HttpProvider) -> Result<(), String> {
let Some(provider) = KeyProvider::of(provider) else {
return Ok(());
};
update(location, |saved| {
saved.keys.remove(&provider);
Ok(())
})
.await
}
pub enum KeyChange {
Set(ApiKey),
Keep,
None,
}
pub async fn save_custom(
location: &Location,
name: CustomBackendName,
mut custom: Custom,
key: KeyChange,
) -> Result<(), String> {
update(location, |saved| {
if let Custom::Endpoint { url, key: slot, .. } = &mut custom {
if url.0.is_none() {
return Err("Enter a valid endpoint URL.".into());
}
*slot = match key {
KeyChange::Set(key) => Some(key),
KeyChange::Keep => match saved.custom.get(&name) {
Some(Custom::Endpoint { key, .. }) => key.clone(),
_ => None,
},
KeyChange::None => None,
};
}
saved.custom.insert(name, custom);
Ok(())
})
.await
}
pub async fn remove_custom(location: &Location, name: &CustomBackendName) -> Result<(), String> {
update(location, |saved| {
saved
.custom
.remove(name)
.map(drop)
.ok_or_else(|| "No custom provider has that name.".into())
})
.await
}
#[cfg(test)]
mod tests;
pub(crate) fn secret_values(
location: Option<&Location>,
) -> Result<impl Iterator<Item = String>, String> {
use crate::json::{Object, Optional};
#[derive(Deserialize)]
struct CredentialFields {
#[serde(default)]
keys: Optional<Object<BTreeMap<String, Optional<String>>>>,
#[serde(default)]
custom: Optional<Object<BTreeMap<String, Optional<Object<CustomField>>>>>,
}
#[derive(Deserialize)]
struct CustomField {
#[serde(default)]
key: Optional<String>,
}
let stored = location
.filter(|location| !location.is_refused())
.map(|location| Storage::inspect(location)?.read::<Object<CredentialFields>>(FILE))
.transpose()?
.flatten()
.into_iter()
.flat_map(|Object(fields)| {
let keys = fields
.keys
.0
.into_iter()
.flat_map(|Object(keys)| keys.into_values().filter_map(|value| value.0));
let custom = fields.custom.0.into_iter().flat_map(|Object(custom)| {
custom
.into_values()
.filter_map(|value| value.0.and_then(|Object(custom)| custom.key.0))
});
keys.chain(custom)
.flat_map(|value| [value.trim().to_owned(), value])
});
let environment = HttpProvider::ALL
.into_iter()
.filter_map(key_variable)
.filter_map(crate::platform::var_text)
.flat_map(|value| [value.trim().to_owned(), value]);
Ok(stored.chain(environment))
}