- Provider: rimossi openai, Bedrock e GCP integrati e ogni fallback a OpenAI;
restano ollama, lmstudio e i provider personalizzati. Senza provider, exec e
TUI mostrano come configurarlo.
- Chiave per provider: api_key = "keyring", provider_api_key_store =
auto|keyring|file (fallback su file 0600 / ACL Windows); `codex login
--provider <id> --with-api-key`, `logout --provider`; login status e doctor
mostrano dove sta la chiave senza rivelarla.
- Modelli letti da GET {base_url}/models; contesto da config, poi dal server
(/props, meta.n_ctx), poi 32768; apply_patch come tool function; niente tool
ospitati; niente piu' avviso "metadata not found".
- Unione dei soli messaggi system/developer iniziali in un unico system;
quelli successivi restano al loro posto come user (cache del server
preservata: turno N prefisso esatto del turno N+1).
- Modelli ausiliari (memorie, guardian-v2) = modello di sessione se il
preferito gpt-* non e' nel catalogo.
- Ricerca web: crate web-tools, backend SearXNG con web_search e web_fetch
(protezione SSRF); senza backend nessuno strumento web.
- Skill: rimossa openai-docs; skill-installer punta a git.difonzo.net.
- apply_patch accetta gli header @@ -a,b +c,d @@ dei diff unificati.
- Rimossi resti: request_plugin_install, AppsInstructions, --cyber-access-program,
URL updater/realtime predefiniti.
- Fix: importazione sessioni con provider vuoto.
- Istruzioni di sistema invariate. Test: cancellati solo quelli del codice
rimosso, test di sicurezza adattati; restano solo fallimenti d'ambiente.
- Prova reale su imeAI + SearXNG: risposta, modifica file, web_search,
cache riusata, connessioni solo verso .25 e .57.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
244 lines
8.7 KiB
Rust
244 lines
8.7 KiB
Rust
//! Per-provider API keys stored outside config.toml (`api_key = "keyring"`).
|
|
//!
|
|
//! The process-wide [`ProviderApiKeyStore`] decides where keys live. By default it is the
|
|
//! system keyring (service [`PROVIDER_API_KEY_KEYRING_SERVICE`], account
|
|
//! `model-provider:<id>`; Keychain on macOS, Credential Manager on Windows, Secret Service
|
|
//! or keyutils on Linux). `codex-login` installs a store that follows
|
|
//! `provider_api_key_store = "auto" | "keyring" | "file"` and can fall back to a private
|
|
//! file in CODEX_HOME. Loaded keys are cached for the life of the process. Keys are never
|
|
//! logged or included in errors.
|
|
|
|
use std::collections::HashMap;
|
|
use std::fmt;
|
|
use std::sync::Arc;
|
|
use std::sync::Mutex;
|
|
use std::sync::OnceLock;
|
|
use std::sync::PoisonError;
|
|
use std::sync::RwLock;
|
|
|
|
use codex_keyring_store::DefaultKeyringStore;
|
|
use codex_keyring_store::KeyringStore;
|
|
use codex_protocol::error::CodexErr;
|
|
use codex_protocol::error::Result as CodexResult;
|
|
|
|
use crate::PROVIDER_API_KEY_KEYRING_SERVICE;
|
|
use crate::provider_api_key_keyring_account;
|
|
|
|
/// Where a provider key was found or stored. Never contains the key.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum ProviderApiKeyLocation {
|
|
/// System keyring entry (service, account).
|
|
Keyring { service: String, account: String },
|
|
/// Private file (path shown to the user).
|
|
File { path: String },
|
|
/// Process memory only.
|
|
Memory,
|
|
}
|
|
|
|
impl fmt::Display for ProviderApiKeyLocation {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::Keyring { service, account } => {
|
|
write!(
|
|
f,
|
|
"system keyring (service `{service}`, account `{account}`)"
|
|
)
|
|
}
|
|
Self::File { path } => write!(f, "file {path}"),
|
|
Self::Memory => f.write_str("memory (this process only)"),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Backend that stores provider API keys by provider id.
|
|
///
|
|
/// Implementations must never include key material in errors, `Debug` output or logs.
|
|
pub trait ProviderApiKeyStore: fmt::Debug + Send + Sync {
|
|
/// Loads the key for `provider_id`; `Ok(None)` when none is stored.
|
|
fn load(&self, provider_id: &str) -> Result<Option<String>, String>;
|
|
/// Stores `api_key` for `provider_id` and reports where it went.
|
|
fn save(&self, provider_id: &str, api_key: &str) -> Result<ProviderApiKeyLocation, String>;
|
|
/// Deletes the key for `provider_id`; returns whether one existed.
|
|
fn delete(&self, provider_id: &str) -> Result<bool, String>;
|
|
/// Where the key for `provider_id` currently is, if stored.
|
|
fn locate(&self, provider_id: &str) -> Result<Option<ProviderApiKeyLocation>, String>;
|
|
}
|
|
|
|
/// Keyring-only store backed by a [`KeyringStore`].
|
|
#[derive(Debug, Clone)]
|
|
pub struct KeyringProviderApiKeyStore {
|
|
keyring: Arc<dyn KeyringStore>,
|
|
}
|
|
|
|
impl KeyringProviderApiKeyStore {
|
|
pub fn new(keyring: Arc<dyn KeyringStore>) -> Self {
|
|
Self { keyring }
|
|
}
|
|
|
|
fn location(provider_id: &str) -> ProviderApiKeyLocation {
|
|
ProviderApiKeyLocation::Keyring {
|
|
service: PROVIDER_API_KEY_KEYRING_SERVICE.to_string(),
|
|
account: provider_api_key_keyring_account(provider_id),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Default for KeyringProviderApiKeyStore {
|
|
fn default() -> Self {
|
|
Self::new(Arc::new(DefaultKeyringStore))
|
|
}
|
|
}
|
|
|
|
impl ProviderApiKeyStore for KeyringProviderApiKeyStore {
|
|
fn load(&self, provider_id: &str) -> Result<Option<String>, String> {
|
|
self.keyring
|
|
.load(
|
|
PROVIDER_API_KEY_KEYRING_SERVICE,
|
|
&provider_api_key_keyring_account(provider_id),
|
|
)
|
|
.map(|key| key.filter(|key| !key.trim().is_empty()))
|
|
// The keyring error describes the backend failure, never the secret.
|
|
.map_err(|error| format!("system keyring unavailable: {}", error.message()))
|
|
}
|
|
|
|
fn save(&self, provider_id: &str, api_key: &str) -> Result<ProviderApiKeyLocation, String> {
|
|
self.keyring
|
|
.save(
|
|
PROVIDER_API_KEY_KEYRING_SERVICE,
|
|
&provider_api_key_keyring_account(provider_id),
|
|
api_key,
|
|
)
|
|
.map_err(|error| format!("system keyring unavailable: {}", error.message()))?;
|
|
Ok(Self::location(provider_id))
|
|
}
|
|
|
|
fn delete(&self, provider_id: &str) -> Result<bool, String> {
|
|
self.keyring
|
|
.delete(
|
|
PROVIDER_API_KEY_KEYRING_SERVICE,
|
|
&provider_api_key_keyring_account(provider_id),
|
|
)
|
|
.map_err(|error| format!("system keyring unavailable: {}", error.message()))
|
|
}
|
|
|
|
fn locate(&self, provider_id: &str) -> Result<Option<ProviderApiKeyLocation>, String> {
|
|
Ok(self.load(provider_id)?.map(|_| Self::location(provider_id)))
|
|
}
|
|
}
|
|
|
|
fn store_slot() -> &'static RwLock<Arc<dyn ProviderApiKeyStore>> {
|
|
static STORE: OnceLock<RwLock<Arc<dyn ProviderApiKeyStore>>> = OnceLock::new();
|
|
STORE.get_or_init(|| RwLock::new(Arc::new(KeyringProviderApiKeyStore::default())))
|
|
}
|
|
|
|
fn cache() -> &'static Mutex<HashMap<String, String>> {
|
|
static CACHE: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
|
|
CACHE.get_or_init(|| Mutex::new(HashMap::new()))
|
|
}
|
|
|
|
fn clear_cache() {
|
|
cache()
|
|
.lock()
|
|
.unwrap_or_else(PoisonError::into_inner)
|
|
.clear();
|
|
}
|
|
|
|
/// The process-wide provider key store.
|
|
pub fn provider_api_key_store() -> Arc<dyn ProviderApiKeyStore> {
|
|
Arc::clone(&store_slot().read().unwrap_or_else(PoisonError::into_inner))
|
|
}
|
|
|
|
/// Installs the process-wide provider key store (done by config loading).
|
|
pub fn set_provider_api_key_store(store: Arc<dyn ProviderApiKeyStore>) {
|
|
*store_slot().write().unwrap_or_else(PoisonError::into_inner) = store;
|
|
clear_cache();
|
|
}
|
|
|
|
/// Replaces the keyring backend with a keyring-only store. Intended for tests.
|
|
#[doc(hidden)]
|
|
pub fn set_provider_keyring_store_for_testing(keyring: Arc<dyn KeyringStore>) {
|
|
set_provider_api_key_store(Arc::new(KeyringProviderApiKeyStore::new(keyring)));
|
|
}
|
|
|
|
fn provider_id_from_account(account: &str) -> &str {
|
|
account.strip_prefix("model-provider:").unwrap_or(account)
|
|
}
|
|
|
|
/// Loads the key for a keyring account, failing when no non-empty key is stored.
|
|
pub(crate) fn load(account: &str) -> CodexResult<String> {
|
|
if let Some(key) = cache()
|
|
.lock()
|
|
.unwrap_or_else(PoisonError::into_inner)
|
|
.get(account)
|
|
{
|
|
return Ok(key.clone());
|
|
}
|
|
let key = load_with(provider_api_key_store().as_ref(), account)?;
|
|
cache()
|
|
.lock()
|
|
.unwrap_or_else(PoisonError::into_inner)
|
|
.insert(account.to_string(), key.clone());
|
|
Ok(key)
|
|
}
|
|
|
|
pub(crate) fn load_with(store: &dyn ProviderApiKeyStore, account: &str) -> CodexResult<String> {
|
|
let provider_id = provider_id_from_account(account);
|
|
match store.load(provider_id) {
|
|
Ok(Some(key)) if !key.trim().is_empty() => Ok(key),
|
|
Ok(_) => Err(CodexErr::UnsupportedOperation(format!(
|
|
"No API key is stored for model provider `{provider_id}`. \
|
|
Store one with: codex login --provider {provider_id} --with-api-key"
|
|
))),
|
|
Err(error) => Err(CodexErr::UnsupportedOperation(format!(
|
|
"Failed to read the API key for model provider `{provider_id}`: {error}"
|
|
))),
|
|
}
|
|
}
|
|
|
|
/// Stores `api_key` for `provider_id` in the process-wide store.
|
|
pub fn save_provider_api_key(
|
|
provider_id: &str,
|
|
api_key: &str,
|
|
) -> Result<ProviderApiKeyLocation, String> {
|
|
if api_key.trim().is_empty() {
|
|
return Err("API key must not be empty".to_string());
|
|
}
|
|
let location = provider_api_key_store()
|
|
.save(provider_id, api_key)
|
|
.map_err(|error| {
|
|
format!("Failed to store the API key for model provider `{provider_id}`: {error}")
|
|
})?;
|
|
cache()
|
|
.lock()
|
|
.unwrap_or_else(PoisonError::into_inner)
|
|
.insert(
|
|
provider_api_key_keyring_account(provider_id),
|
|
api_key.to_string(),
|
|
);
|
|
Ok(location)
|
|
}
|
|
|
|
/// Removes the stored key for `provider_id`. Returns whether a key was present.
|
|
pub fn delete_provider_api_key(provider_id: &str) -> Result<bool, String> {
|
|
cache()
|
|
.lock()
|
|
.unwrap_or_else(PoisonError::into_inner)
|
|
.remove(&provider_api_key_keyring_account(provider_id));
|
|
provider_api_key_store()
|
|
.delete(provider_id)
|
|
.map_err(|error| {
|
|
format!("Failed to delete the API key for model provider `{provider_id}`: {error}")
|
|
})
|
|
}
|
|
|
|
/// Where the key for `provider_id` is stored, without reading it into any output.
|
|
pub fn locate_provider_api_key(
|
|
provider_id: &str,
|
|
) -> Result<Option<ProviderApiKeyLocation>, String> {
|
|
provider_api_key_store().locate(provider_id)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "keyring_api_key_tests.rs"]
|
|
mod tests;
|