Base: codex-main originale (prima del fork aKode)
This commit is contained in:
262
codex-rs/secrets/src/lib.rs
Normal file
262
codex-rs/secrets/src/lib.rs
Normal file
@@ -0,0 +1,262 @@
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_git_utils::get_git_repo_root;
|
||||
use codex_keyring_store::DefaultKeyringStore;
|
||||
use codex_keyring_store::KeyringStore;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
|
||||
mod local;
|
||||
mod sanitizer;
|
||||
|
||||
pub use local::LocalSecretsBackend;
|
||||
pub use local::LocalSecretsNamespace;
|
||||
pub use sanitizer::redact_secrets;
|
||||
|
||||
const KEYRING_SERVICE: &str = "codex";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct SecretName(String);
|
||||
|
||||
impl SecretName {
|
||||
pub fn new(raw: &str) -> Result<Self> {
|
||||
let trimmed = raw.trim();
|
||||
anyhow::ensure!(!trimmed.is_empty(), "secret name must not be empty");
|
||||
anyhow::ensure!(
|
||||
trimmed
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_'),
|
||||
"secret name must contain only A-Z, 0-9, or _"
|
||||
);
|
||||
Ok(Self(trimmed.to_string()))
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
self.0.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for SecretName {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum SecretScope {
|
||||
Global,
|
||||
Environment(String),
|
||||
}
|
||||
|
||||
impl SecretScope {
|
||||
pub fn environment(environment_id: impl Into<String>) -> Result<Self> {
|
||||
let env_id = environment_id.into();
|
||||
let trimmed = env_id.trim();
|
||||
anyhow::ensure!(!trimmed.is_empty(), "environment id must not be empty");
|
||||
Ok(Self::Environment(trimmed.to_string()))
|
||||
}
|
||||
|
||||
pub fn canonical_key(&self, name: &SecretName) -> String {
|
||||
// Stable, env-safe identifier used as the on-disk map key.
|
||||
match self {
|
||||
Self::Global => format!("global/{}", name.as_str()),
|
||||
Self::Environment(environment_id) => {
|
||||
format!("env/{environment_id}/{}", name.as_str())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SecretListEntry {
|
||||
pub scope: SecretScope,
|
||||
pub name: SecretName,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum SecretsBackendKind {
|
||||
#[default]
|
||||
Local,
|
||||
}
|
||||
|
||||
pub trait SecretsBackend: Send + Sync {
|
||||
fn set(&self, scope: &SecretScope, name: &SecretName, value: &str) -> Result<()>;
|
||||
fn get(&self, scope: &SecretScope, name: &SecretName) -> Result<Option<String>>;
|
||||
fn delete(&self, scope: &SecretScope, name: &SecretName) -> Result<bool>;
|
||||
fn list(&self, scope_filter: Option<&SecretScope>) -> Result<Vec<SecretListEntry>>;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SecretsManager {
|
||||
backend: Arc<dyn SecretsBackend>,
|
||||
}
|
||||
|
||||
impl SecretsManager {
|
||||
pub fn new(codex_home: PathBuf, backend_kind: SecretsBackendKind) -> Self {
|
||||
let backend: Arc<dyn SecretsBackend> = match backend_kind {
|
||||
SecretsBackendKind::Local => {
|
||||
let keyring_store: Arc<dyn KeyringStore> = Arc::new(DefaultKeyringStore);
|
||||
Arc::new(LocalSecretsBackend::new(codex_home, keyring_store))
|
||||
}
|
||||
};
|
||||
Self { backend }
|
||||
}
|
||||
|
||||
pub fn new_with_keyring_store(
|
||||
codex_home: PathBuf,
|
||||
backend_kind: SecretsBackendKind,
|
||||
keyring_store: Arc<dyn KeyringStore>,
|
||||
) -> Self {
|
||||
let backend: Arc<dyn SecretsBackend> = match backend_kind {
|
||||
SecretsBackendKind::Local => {
|
||||
Arc::new(LocalSecretsBackend::new(codex_home, keyring_store))
|
||||
}
|
||||
};
|
||||
Self { backend }
|
||||
}
|
||||
|
||||
pub fn new_with_keyring_store_and_namespace(
|
||||
codex_home: PathBuf,
|
||||
backend_kind: SecretsBackendKind,
|
||||
keyring_store: Arc<dyn KeyringStore>,
|
||||
namespace: LocalSecretsNamespace,
|
||||
) -> Self {
|
||||
let backend: Arc<dyn SecretsBackend> = match backend_kind {
|
||||
SecretsBackendKind::Local => Arc::new(LocalSecretsBackend::new_with_namespace(
|
||||
codex_home,
|
||||
keyring_store,
|
||||
namespace,
|
||||
)),
|
||||
};
|
||||
Self { backend }
|
||||
}
|
||||
|
||||
pub fn set(&self, scope: &SecretScope, name: &SecretName, value: &str) -> Result<()> {
|
||||
self.backend.set(scope, name, value)
|
||||
}
|
||||
|
||||
pub fn get(&self, scope: &SecretScope, name: &SecretName) -> Result<Option<String>> {
|
||||
self.backend.get(scope, name)
|
||||
}
|
||||
|
||||
pub fn delete(&self, scope: &SecretScope, name: &SecretName) -> Result<bool> {
|
||||
self.backend.delete(scope, name)
|
||||
}
|
||||
|
||||
pub fn list(&self, scope_filter: Option<&SecretScope>) -> Result<Vec<SecretListEntry>> {
|
||||
self.backend.list(scope_filter)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn environment_id_from_cwd(cwd: &Path) -> String {
|
||||
if let Some(repo_root) = get_git_repo_root(cwd)
|
||||
&& let Some(name) = repo_root.file_name()
|
||||
{
|
||||
let name = name.to_string_lossy().trim().to_string();
|
||||
if !name.is_empty() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
let canonical = cwd
|
||||
.canonicalize()
|
||||
.unwrap_or_else(|_| cwd.to_path_buf())
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(canonical.as_bytes());
|
||||
let digest = hasher.finalize();
|
||||
let hex = format!("{digest:x}");
|
||||
let short = hex.get(..12).unwrap_or(hex.as_str());
|
||||
format!("cwd-{short}")
|
||||
}
|
||||
|
||||
/// Computes the OS keyring account name used to store a local namespace's passphrase.
|
||||
/// Existing namespaces retain their shared key; gateway credentials use an independent key.
|
||||
pub fn compute_keyring_account(codex_home: &Path, namespace: LocalSecretsNamespace) -> String {
|
||||
let canonical = codex_home
|
||||
.canonicalize()
|
||||
.unwrap_or_else(|_| codex_home.to_path_buf())
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(canonical.as_bytes());
|
||||
let digest = hasher.finalize();
|
||||
let hex = format!("{digest:x}");
|
||||
let short = hex.get(..16).unwrap_or(hex.as_str());
|
||||
let home_account = format!("secrets|{short}");
|
||||
// Separate keys also prevent concurrent first writes to the gateway and primary
|
||||
// stores from overwriting each other's newly generated encryption key.
|
||||
match namespace {
|
||||
LocalSecretsNamespace::GatewayOAuth => format!("{home_account}|gateway-oauth"),
|
||||
LocalSecretsNamespace::ManagedSecrets
|
||||
| LocalSecretsNamespace::CodexAuth
|
||||
| LocalSecretsNamespace::McpOAuth => home_account,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn keyring_service() -> &'static str {
|
||||
KEYRING_SERVICE
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::local::SECRETS_CACHE_TEST_LOCK;
|
||||
use codex_keyring_store::tests::MockKeyringStore;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
#[test]
|
||||
fn environment_id_fallback_has_cwd_prefix() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let env_id = environment_id_from_cwd(dir.path());
|
||||
let canonical = dir
|
||||
.path()
|
||||
.canonicalize()
|
||||
.expect("tempdir canonical path should exist")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(canonical.as_bytes());
|
||||
let digest = hasher.finalize();
|
||||
let hex = format!("{digest:x}");
|
||||
let short = hex.get(..12).expect("digest has at least 12 chars");
|
||||
assert_eq!(env_id, format!("cwd-{short}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manager_round_trips_local_backend() -> Result<()> {
|
||||
let _cache_lock = SECRETS_CACHE_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
let codex_home = tempfile::tempdir().expect("tempdir");
|
||||
let keyring = Arc::new(MockKeyringStore::default());
|
||||
let manager = SecretsManager::new_with_keyring_store(
|
||||
codex_home.path().to_path_buf(),
|
||||
SecretsBackendKind::Local,
|
||||
keyring,
|
||||
);
|
||||
let scope = SecretScope::Global;
|
||||
let name = SecretName::new("GITHUB_TOKEN")?;
|
||||
|
||||
manager.set(&scope, &name, "token-1")?;
|
||||
assert_eq!(manager.get(&scope, &name)?, Some("token-1".to_string()));
|
||||
|
||||
let listed = manager.list(/*scope_filter*/ None)?;
|
||||
assert_eq!(listed.len(), 1);
|
||||
assert_eq!(listed[0].name, name);
|
||||
|
||||
assert!(manager.delete(&scope, &name)?);
|
||||
assert_eq!(manager.get(&scope, &name)?, None);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
716
codex-rs/secrets/src/local.rs
Normal file
716
codex-rs/secrets/src/local.rs
Normal file
@@ -0,0 +1,716 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::atomic::compiler_fence;
|
||||
use std::time::SystemTime;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use age::decrypt;
|
||||
use age::encrypt;
|
||||
use age::scrypt::Identity as ScryptIdentity;
|
||||
use age::scrypt::Recipient as ScryptRecipient;
|
||||
use age::secrecy::ExposeSecret;
|
||||
use age::secrecy::SecretString;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
|
||||
use codex_keyring_store::KeyringStore;
|
||||
use rand::TryRngCore;
|
||||
use rand::rngs::OsRng;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use tracing::warn;
|
||||
|
||||
use super::SecretListEntry;
|
||||
use super::SecretName;
|
||||
use super::SecretScope;
|
||||
use super::SecretsBackend;
|
||||
use super::compute_keyring_account;
|
||||
use super::keyring_service;
|
||||
|
||||
const SECRETS_VERSION: u8 = 1;
|
||||
const LOCAL_SECRETS_FILENAME: &str = "local.age";
|
||||
const CODEX_AUTH_SECRETS_FILENAME: &str = "codex_auth.age";
|
||||
const MCP_OAUTH_SECRETS_FILENAME: &str = "mcp_oauth.age";
|
||||
const GATEWAY_OAUTH_SECRETS_FILENAME: &str = "gateway_oauth.age";
|
||||
static MCP_OAUTH_CACHE: Mutex<Option<CachedSecrets>> = Mutex::new(None);
|
||||
static CODEX_AUTH_CACHE: Mutex<Option<CachedSecrets>> = Mutex::new(None);
|
||||
static MANAGED_SECRETS_CACHE: Mutex<Option<CachedSecrets>> = Mutex::new(None);
|
||||
|
||||
// Tests that access the shared caches must hold this lock so another test's
|
||||
// temporary home cannot evict a snapshot while cache reuse is being asserted.
|
||||
#[cfg(test)]
|
||||
pub(super) static SECRETS_CACHE_TEST_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Selects the local encrypted file used by a `LocalSecretsBackend`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum LocalSecretsNamespace {
|
||||
/// General managed secrets stored in `local.age`.
|
||||
#[default]
|
||||
ManagedSecrets,
|
||||
/// Codex authentication credentials used by the CLI, TUI, app server, and other clients.
|
||||
CodexAuth,
|
||||
/// OAuth credentials for external MCP servers.
|
||||
McpOAuth,
|
||||
/// Gateway OAuth credentials, isolated from primary auth in file and encryption key.
|
||||
GatewayOAuth,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
struct SecretsFile {
|
||||
version: u8,
|
||||
secrets: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
struct CachedSecrets {
|
||||
path: PathBuf,
|
||||
ciphertext_hash: [u8; 32],
|
||||
passphrase_hash: [u8; 32],
|
||||
file: Arc<SecretsFile>,
|
||||
}
|
||||
|
||||
impl SecretsFile {
|
||||
fn new_empty() -> Self {
|
||||
Self {
|
||||
version: SECRETS_VERSION,
|
||||
secrets: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct LocalSecretsBackend {
|
||||
codex_home: PathBuf,
|
||||
keyring_store: Arc<dyn KeyringStore>,
|
||||
namespace: LocalSecretsNamespace,
|
||||
gateway_cache: Arc<Mutex<Option<CachedSecrets>>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for LocalSecretsBackend {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("LocalSecretsBackend")
|
||||
.field("codex_home", &self.codex_home)
|
||||
.field("keyring_store", &self.keyring_store)
|
||||
.field("namespace", &self.namespace)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalSecretsBackend {
|
||||
pub fn new(codex_home: PathBuf, keyring_store: Arc<dyn KeyringStore>) -> Self {
|
||||
Self::new_with_namespace(
|
||||
codex_home,
|
||||
keyring_store,
|
||||
LocalSecretsNamespace::ManagedSecrets,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn new_with_namespace(
|
||||
codex_home: PathBuf,
|
||||
keyring_store: Arc<dyn KeyringStore>,
|
||||
namespace: LocalSecretsNamespace,
|
||||
) -> Self {
|
||||
Self {
|
||||
codex_home,
|
||||
keyring_store,
|
||||
namespace,
|
||||
gateway_cache: Arc::new(Mutex::new(None)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set(&self, scope: &SecretScope, name: &SecretName, value: &str) -> Result<()> {
|
||||
anyhow::ensure!(!value.is_empty(), "secret value must not be empty");
|
||||
let canonical_key = scope.canonical_key(name);
|
||||
let mut file = self.load_file()?;
|
||||
file.secrets.insert(canonical_key, value.to_string());
|
||||
self.save_file(&file)
|
||||
}
|
||||
|
||||
pub fn get(&self, scope: &SecretScope, name: &SecretName) -> Result<Option<String>> {
|
||||
let canonical_key = scope.canonical_key(name);
|
||||
let file = self.load_file()?;
|
||||
Ok(file.secrets.get(&canonical_key).cloned())
|
||||
}
|
||||
|
||||
pub fn delete(&self, scope: &SecretScope, name: &SecretName) -> Result<bool> {
|
||||
let canonical_key = scope.canonical_key(name);
|
||||
let mut file = self.load_file()?;
|
||||
let removed = file.secrets.remove(&canonical_key).is_some();
|
||||
if removed {
|
||||
self.save_file(&file)?;
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
pub fn list(&self, scope_filter: Option<&SecretScope>) -> Result<Vec<SecretListEntry>> {
|
||||
let file = self.load_file()?;
|
||||
let mut entries = Vec::new();
|
||||
for canonical_key in file.secrets.keys() {
|
||||
let Some(entry) = parse_canonical_key(canonical_key) else {
|
||||
warn!("skipping invalid canonical secret key: {canonical_key}");
|
||||
continue;
|
||||
};
|
||||
if let Some(scope) = scope_filter
|
||||
&& entry.scope != *scope
|
||||
{
|
||||
continue;
|
||||
}
|
||||
entries.push(entry);
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn secrets_dir(&self) -> PathBuf {
|
||||
self.codex_home.join("secrets")
|
||||
}
|
||||
|
||||
fn secrets_path(&self) -> PathBuf {
|
||||
let filename = match self.namespace {
|
||||
LocalSecretsNamespace::ManagedSecrets => LOCAL_SECRETS_FILENAME,
|
||||
LocalSecretsNamespace::CodexAuth => CODEX_AUTH_SECRETS_FILENAME,
|
||||
LocalSecretsNamespace::McpOAuth => MCP_OAUTH_SECRETS_FILENAME,
|
||||
LocalSecretsNamespace::GatewayOAuth => GATEWAY_OAUTH_SECRETS_FILENAME,
|
||||
};
|
||||
self.secrets_dir().join(filename)
|
||||
}
|
||||
|
||||
/// Each namespace keeps at most one snapshot; gateway snapshots are scoped to
|
||||
/// a backend and its clones. Every read still checks the file and keyring.
|
||||
fn decrypted_cache(&self) -> &Mutex<Option<CachedSecrets>> {
|
||||
match self.namespace {
|
||||
LocalSecretsNamespace::ManagedSecrets => &MANAGED_SECRETS_CACHE,
|
||||
LocalSecretsNamespace::CodexAuth => &CODEX_AUTH_CACHE,
|
||||
LocalSecretsNamespace::McpOAuth => &MCP_OAUTH_CACHE,
|
||||
LocalSecretsNamespace::GatewayOAuth => &self.gateway_cache,
|
||||
}
|
||||
}
|
||||
|
||||
fn load_file(&self) -> Result<SecretsFile> {
|
||||
let path = self.secrets_path();
|
||||
if !path.exists() {
|
||||
return Ok(SecretsFile::new_empty());
|
||||
}
|
||||
|
||||
let ciphertext = fs::read(&path)
|
||||
.with_context(|| format!("failed to read secrets file at {}", path.display()))?;
|
||||
let passphrase = self.load_or_create_passphrase()?;
|
||||
let ciphertext_hash: [u8; 32] = Sha256::digest(&ciphertext).into();
|
||||
let passphrase_hash: [u8; 32] =
|
||||
Sha256::digest(passphrase.expose_secret().as_bytes()).into();
|
||||
// Hold the namespace lock through decryption so concurrent misses share
|
||||
// one decrypted snapshot instead of repeating the expensive scrypt work.
|
||||
let mut cache = self
|
||||
.decrypted_cache()
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(cached) = cache.as_ref()
|
||||
&& cached.path == path
|
||||
&& cached.ciphertext_hash == ciphertext_hash
|
||||
&& cached.passphrase_hash == passphrase_hash
|
||||
{
|
||||
return Ok(cached.file.as_ref().clone());
|
||||
}
|
||||
let plaintext = decrypt_with_passphrase(&ciphertext, &passphrase)?;
|
||||
let mut parsed: SecretsFile = serde_json::from_slice(&plaintext).with_context(|| {
|
||||
format!(
|
||||
"failed to deserialize decrypted secrets file at {}",
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
if parsed.version == 0 {
|
||||
parsed.version = SECRETS_VERSION;
|
||||
}
|
||||
anyhow::ensure!(
|
||||
parsed.version <= SECRETS_VERSION,
|
||||
"secrets file version {} is newer than supported version {}",
|
||||
parsed.version,
|
||||
SECRETS_VERSION
|
||||
);
|
||||
*cache = Some(CachedSecrets {
|
||||
path,
|
||||
ciphertext_hash,
|
||||
passphrase_hash,
|
||||
file: Arc::new(parsed.clone()),
|
||||
});
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
fn save_file(&self, file: &SecretsFile) -> Result<()> {
|
||||
let dir = self.secrets_dir();
|
||||
fs::create_dir_all(&dir)
|
||||
.with_context(|| format!("failed to create secrets dir {}", dir.display()))?;
|
||||
|
||||
let passphrase = self.load_or_create_passphrase()?;
|
||||
let plaintext = serde_json::to_vec(file).context("failed to serialize secrets file")?;
|
||||
let ciphertext = encrypt_with_passphrase(&plaintext, &passphrase)?;
|
||||
let path = self.secrets_path();
|
||||
write_file_atomically(&path, &ciphertext)?;
|
||||
let mut cache = self
|
||||
.decrypted_cache()
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
// Publish only committed contents. Reads still verify the ciphertext and
|
||||
// keyring, so a racing replacement cannot make this snapshot authoritative.
|
||||
if file.version == SECRETS_VERSION {
|
||||
*cache = Some(CachedSecrets {
|
||||
path,
|
||||
ciphertext_hash: Sha256::digest(&ciphertext).into(),
|
||||
passphrase_hash: Sha256::digest(passphrase.expose_secret().as_bytes()).into(),
|
||||
file: Arc::new(file.clone()),
|
||||
});
|
||||
} else if cache.as_ref().is_some_and(|cached| cached.path == path) {
|
||||
// Leave schema normalization and rejection to the normal read path.
|
||||
*cache = None;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_or_create_passphrase(&self) -> Result<SecretString> {
|
||||
let account = compute_keyring_account(&self.codex_home, self.namespace);
|
||||
let loaded = self
|
||||
.keyring_store
|
||||
.load(keyring_service(), &account)
|
||||
.map_err(std::io::Error::from)
|
||||
.with_context(|| format!("failed to load secrets key from keyring for {account}"))?;
|
||||
match loaded {
|
||||
Some(existing) => Ok(SecretString::from(existing)),
|
||||
None => {
|
||||
// Generate a high-entropy key and persist it in the OS keyring.
|
||||
// This keeps secrets out of plaintext config while remaining
|
||||
// fully local/offline for the MVP.
|
||||
let generated = generate_passphrase()?;
|
||||
self.keyring_store
|
||||
.save(keyring_service(), &account, generated.expose_secret())
|
||||
.map_err(std::io::Error::from)
|
||||
.context("failed to persist secrets key in keyring")?;
|
||||
Ok(generated)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SecretsBackend for LocalSecretsBackend {
|
||||
fn set(&self, scope: &SecretScope, name: &SecretName, value: &str) -> Result<()> {
|
||||
LocalSecretsBackend::set(self, scope, name, value)
|
||||
}
|
||||
|
||||
fn get(&self, scope: &SecretScope, name: &SecretName) -> Result<Option<String>> {
|
||||
LocalSecretsBackend::get(self, scope, name)
|
||||
}
|
||||
|
||||
fn delete(&self, scope: &SecretScope, name: &SecretName) -> Result<bool> {
|
||||
LocalSecretsBackend::delete(self, scope, name)
|
||||
}
|
||||
|
||||
fn list(&self, scope_filter: Option<&SecretScope>) -> Result<Vec<SecretListEntry>> {
|
||||
LocalSecretsBackend::list(self, scope_filter)
|
||||
}
|
||||
}
|
||||
|
||||
fn write_file_atomically(path: &Path, contents: &[u8]) -> Result<()> {
|
||||
let dir = path.parent().with_context(|| {
|
||||
format!(
|
||||
"failed to compute parent directory for secrets file at {}",
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
let nonce = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |duration| duration.as_nanos());
|
||||
let filename = path.file_name().with_context(|| {
|
||||
format!(
|
||||
"failed to compute filename for secrets file at {}",
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
let tmp_path = dir.join(format!(
|
||||
".{}.tmp-{}-{nonce}",
|
||||
filename.to_string_lossy(),
|
||||
std::process::id()
|
||||
));
|
||||
|
||||
{
|
||||
let mut tmp_file = fs::OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.open(&tmp_path)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"failed to create temp secrets file at {}",
|
||||
tmp_path.display()
|
||||
)
|
||||
})?;
|
||||
tmp_file.write_all(contents).with_context(|| {
|
||||
format!(
|
||||
"failed to write temp secrets file at {}",
|
||||
tmp_path.display()
|
||||
)
|
||||
})?;
|
||||
tmp_file.sync_all().with_context(|| {
|
||||
format!("failed to sync temp secrets file at {}", tmp_path.display())
|
||||
})?;
|
||||
}
|
||||
|
||||
match fs::rename(&tmp_path, path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(initial_error) => {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
if path.exists() {
|
||||
fs::remove_file(path).with_context(|| {
|
||||
format!(
|
||||
"failed to remove existing secrets file at {} before replace",
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
fs::rename(&tmp_path, path).with_context(|| {
|
||||
format!(
|
||||
"failed to replace secrets file at {} with {}",
|
||||
path.display(),
|
||||
tmp_path.display()
|
||||
)
|
||||
})?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
let _ = fs::remove_file(&tmp_path);
|
||||
Err(initial_error).with_context(|| {
|
||||
format!(
|
||||
"failed to atomically replace secrets file at {} with {}",
|
||||
path.display(),
|
||||
tmp_path.display()
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_passphrase() -> Result<SecretString> {
|
||||
let mut bytes = [0_u8; 32];
|
||||
let mut rng = OsRng;
|
||||
rng.try_fill_bytes(&mut bytes)
|
||||
.context("failed to generate random secrets key")?;
|
||||
// Base64 keeps the keyring payload ASCII-safe without reducing entropy.
|
||||
let encoded = BASE64_STANDARD.encode(bytes);
|
||||
wipe_bytes(&mut bytes);
|
||||
Ok(SecretString::from(encoded))
|
||||
}
|
||||
|
||||
fn wipe_bytes(bytes: &mut [u8]) {
|
||||
for byte in bytes {
|
||||
// Volatile writes make it much harder for the compiler to elide the wipe.
|
||||
// SAFETY: `byte` is a valid mutable reference into `bytes`.
|
||||
unsafe { std::ptr::write_volatile(byte, 0) };
|
||||
}
|
||||
compiler_fence(Ordering::SeqCst);
|
||||
}
|
||||
|
||||
fn encrypt_with_passphrase(plaintext: &[u8], passphrase: &SecretString) -> Result<Vec<u8>> {
|
||||
let recipient = ScryptRecipient::new(passphrase.clone());
|
||||
encrypt(&recipient, plaintext).context("failed to encrypt secrets file")
|
||||
}
|
||||
|
||||
fn decrypt_with_passphrase(ciphertext: &[u8], passphrase: &SecretString) -> Result<Vec<u8>> {
|
||||
let identity = ScryptIdentity::new(passphrase.clone());
|
||||
decrypt(&identity, ciphertext).context("failed to decrypt secrets file")
|
||||
}
|
||||
|
||||
fn parse_canonical_key(canonical_key: &str) -> Option<SecretListEntry> {
|
||||
let mut parts = canonical_key.split('/');
|
||||
let scope_kind = parts.next()?;
|
||||
match scope_kind {
|
||||
"global" => {
|
||||
let name = parts.next()?;
|
||||
if parts.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
let name = SecretName::new(name).ok()?;
|
||||
Some(SecretListEntry {
|
||||
scope: SecretScope::Global,
|
||||
name,
|
||||
})
|
||||
}
|
||||
"env" => {
|
||||
let environment_id = parts.next()?;
|
||||
let name = parts.next()?;
|
||||
if parts.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
let name = SecretName::new(name).ok()?;
|
||||
let scope = SecretScope::environment(environment_id.to_string()).ok()?;
|
||||
Some(SecretListEntry { scope, name })
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use codex_keyring_store::tests::MockKeyringStore;
|
||||
use keyring::Error as KeyringError;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn load_file_rejects_newer_schema_versions() -> Result<()> {
|
||||
let _cache_lock = SECRETS_CACHE_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
let codex_home = tempfile::tempdir().expect("tempdir");
|
||||
let keyring = Arc::new(MockKeyringStore::default());
|
||||
let backend = LocalSecretsBackend::new(codex_home.path().to_path_buf(), keyring);
|
||||
|
||||
let file = SecretsFile {
|
||||
version: SECRETS_VERSION + 1,
|
||||
secrets: BTreeMap::new(),
|
||||
};
|
||||
backend.save_file(&file)?;
|
||||
|
||||
let error = backend
|
||||
.load_file()
|
||||
.expect_err("must reject newer schema version");
|
||||
assert!(
|
||||
error.to_string().contains("newer than supported version"),
|
||||
"unexpected error: {error:#}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_fails_when_keyring_is_unavailable() -> Result<()> {
|
||||
let _cache_lock = SECRETS_CACHE_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
let codex_home = tempfile::tempdir().expect("tempdir");
|
||||
let keyring = Arc::new(MockKeyringStore::default());
|
||||
let account =
|
||||
compute_keyring_account(codex_home.path(), LocalSecretsNamespace::ManagedSecrets);
|
||||
keyring.set_error(
|
||||
&account,
|
||||
KeyringError::Invalid("error".into(), "load".into()),
|
||||
);
|
||||
|
||||
let backend = LocalSecretsBackend::new(codex_home.path().to_path_buf(), keyring);
|
||||
let scope = SecretScope::Global;
|
||||
let name = SecretName::new("TEST_SECRET")?;
|
||||
let error = backend
|
||||
.set(&scope, &name, "secret-value")
|
||||
.expect_err("must fail when keyring load fails");
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("failed to load secrets key from keyring"),
|
||||
"unexpected error: {error:#}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_file_does_not_leave_temp_files() -> Result<()> {
|
||||
let _cache_lock = SECRETS_CACHE_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
let codex_home = tempfile::tempdir().expect("tempdir");
|
||||
let keyring = Arc::new(MockKeyringStore::default());
|
||||
let backend = LocalSecretsBackend::new(codex_home.path().to_path_buf(), keyring);
|
||||
|
||||
let scope = SecretScope::Global;
|
||||
let name = SecretName::new("TEST_SECRET")?;
|
||||
backend.set(&scope, &name, "one")?;
|
||||
backend.set(&scope, &name, "two")?;
|
||||
|
||||
let secrets_dir = backend.secrets_dir();
|
||||
let entries = fs::read_dir(&secrets_dir)
|
||||
.with_context(|| format!("failed to read {}", secrets_dir.display()))?
|
||||
.collect::<std::io::Result<Vec<_>>>()
|
||||
.with_context(|| format!("failed to enumerate {}", secrets_dir.display()))?;
|
||||
|
||||
let filenames: Vec<String> = entries
|
||||
.into_iter()
|
||||
.filter_map(|entry| entry.file_name().to_str().map(ToString::to_string))
|
||||
.collect();
|
||||
assert_eq!(filenames, vec![LOCAL_SECRETS_FILENAME.to_string()]);
|
||||
assert_eq!(backend.get(&scope, &name)?, Some("two".to_string()));
|
||||
assert!(
|
||||
MCP_OAUTH_CACHE
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.as_ref()
|
||||
.is_none_or(|cached| cached.path != backend.secrets_path())
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_namespaces_write_separate_files() -> Result<()> {
|
||||
let _cache_lock = SECRETS_CACHE_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
let codex_home = tempfile::tempdir().expect("tempdir");
|
||||
let keyring = Arc::new(MockKeyringStore::default());
|
||||
let codex_auth_backend = LocalSecretsBackend::new_with_namespace(
|
||||
codex_home.path().to_path_buf(),
|
||||
keyring.clone(),
|
||||
LocalSecretsNamespace::CodexAuth,
|
||||
);
|
||||
let mcp_backend = LocalSecretsBackend::new_with_namespace(
|
||||
codex_home.path().to_path_buf(),
|
||||
keyring.clone(),
|
||||
LocalSecretsNamespace::McpOAuth,
|
||||
);
|
||||
let gateway_backend = LocalSecretsBackend::new_with_namespace(
|
||||
codex_home.path().to_path_buf(),
|
||||
keyring.clone(),
|
||||
LocalSecretsNamespace::GatewayOAuth,
|
||||
);
|
||||
let scope = SecretScope::Global;
|
||||
let name = SecretName::new("TEST_SECRET")?;
|
||||
|
||||
codex_auth_backend.set(&scope, &name, "codex-auth-value")?;
|
||||
mcp_backend.set(&scope, &name, "mcp-value")?;
|
||||
gateway_backend.set(&scope, &name, "gateway-value")?;
|
||||
|
||||
assert_eq!(
|
||||
codex_auth_backend.get(&scope, &name)?,
|
||||
Some("codex-auth-value".to_string())
|
||||
);
|
||||
assert!(
|
||||
MCP_OAUTH_CACHE
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.as_ref()
|
||||
.is_none_or(|cached| cached.path != codex_auth_backend.secrets_path())
|
||||
);
|
||||
assert_eq!(
|
||||
mcp_backend.get(&scope, &name)?,
|
||||
Some("mcp-value".to_string())
|
||||
);
|
||||
assert!(
|
||||
codex_home
|
||||
.path()
|
||||
.join("secrets")
|
||||
.join("codex_auth.age")
|
||||
.exists()
|
||||
);
|
||||
assert!(
|
||||
codex_home
|
||||
.path()
|
||||
.join("secrets")
|
||||
.join("mcp_oauth.age")
|
||||
.exists()
|
||||
);
|
||||
assert!(!codex_home.path().join("secrets").join("local.age").exists());
|
||||
assert!(
|
||||
codex_home
|
||||
.path()
|
||||
.join("secrets/gateway_oauth.age")
|
||||
.is_file()
|
||||
);
|
||||
// Primary-auth key removal must not make the independent gateway file unreadable.
|
||||
keyring
|
||||
.delete(
|
||||
keyring_service(),
|
||||
&compute_keyring_account(codex_home.path(), LocalSecretsNamespace::CodexAuth),
|
||||
)
|
||||
.expect("remove primary secrets key");
|
||||
assert_eq!(
|
||||
gateway_backend.get(&scope, &name)?,
|
||||
Some("gateway-value".to_string())
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_namespace_caches_reuse_plaintext_and_detect_ciphertext_changes() -> Result<()> {
|
||||
let _cache_lock = SECRETS_CACHE_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
for namespace in [
|
||||
LocalSecretsNamespace::ManagedSecrets,
|
||||
LocalSecretsNamespace::CodexAuth,
|
||||
LocalSecretsNamespace::McpOAuth,
|
||||
] {
|
||||
let codex_home = tempfile::tempdir().expect("tempdir");
|
||||
let keyring = Arc::new(MockKeyringStore::default());
|
||||
let first = LocalSecretsBackend::new_with_namespace(
|
||||
codex_home.path().to_path_buf(),
|
||||
keyring.clone(),
|
||||
namespace,
|
||||
);
|
||||
let second = LocalSecretsBackend::new_with_namespace(
|
||||
codex_home.path().to_path_buf(),
|
||||
keyring,
|
||||
namespace,
|
||||
);
|
||||
let scope = SecretScope::Global;
|
||||
let name = SecretName::new("TEST_SECRET")?;
|
||||
let cached_file = || {
|
||||
Arc::clone(
|
||||
&first
|
||||
.decrypted_cache()
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.as_ref()
|
||||
.expect("credentials should be cached")
|
||||
.file,
|
||||
)
|
||||
};
|
||||
|
||||
first.set(&scope, &name, "one")?;
|
||||
let original_ciphertext = fs::read(first.secrets_path())?;
|
||||
// Exercise concurrent cold reads even though saves populate the cache.
|
||||
*first
|
||||
.decrypted_cache()
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner) = None;
|
||||
let (first_cached, second_cached) = std::thread::scope(|threads| {
|
||||
let first_reader = threads.spawn(|| {
|
||||
assert_eq!(first.get(&scope, &name)?, Some("one".to_string()));
|
||||
Ok::<_, anyhow::Error>(cached_file())
|
||||
});
|
||||
let second_reader = threads.spawn(|| {
|
||||
assert_eq!(second.get(&scope, &name)?, Some("one".to_string()));
|
||||
Ok::<_, anyhow::Error>(cached_file())
|
||||
});
|
||||
Ok::<_, anyhow::Error>((
|
||||
first_reader.join().expect("first credential reader")?,
|
||||
second_reader.join().expect("second credential reader")?,
|
||||
))
|
||||
})?;
|
||||
assert!(Arc::ptr_eq(&first_cached, &second_cached));
|
||||
|
||||
assert_eq!(second.get(&scope, &name)?, Some("one".to_string()));
|
||||
assert!(Arc::ptr_eq(&first_cached, &cached_file()));
|
||||
|
||||
first.set(&scope, &name, "two")?;
|
||||
let updated_cached = cached_file();
|
||||
assert!(!Arc::ptr_eq(&first_cached, &updated_cached));
|
||||
assert_eq!(second.get(&scope, &name)?, Some("two".to_string()));
|
||||
assert!(Arc::ptr_eq(&updated_cached, &cached_file()));
|
||||
|
||||
// Another process can replace the file without invalidating this cache.
|
||||
fs::write(first.secrets_path(), &original_ciphertext)?;
|
||||
assert_eq!(second.get(&scope, &name)?, Some("one".to_string()));
|
||||
|
||||
assert!(first.delete(&scope, &name)?);
|
||||
let deleted_cached = cached_file();
|
||||
assert_eq!(second.get(&scope, &name)?, None);
|
||||
assert!(Arc::ptr_eq(&deleted_cached, &cached_file()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "local_cache_tests.rs"]
|
||||
mod cache_tests;
|
||||
171
codex-rs/secrets/src/local_cache_tests.rs
Normal file
171
codex-rs/secrets/src/local_cache_tests.rs
Normal file
@@ -0,0 +1,171 @@
|
||||
//! Cached reads must observe current filesystem and keyring authority, and writes
|
||||
//! must publish only committed snapshots.
|
||||
|
||||
use super::*;
|
||||
use codex_keyring_store::tests::MockKeyringStore;
|
||||
use keyring::Error as KeyringError;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn cached_reads_check_file_presence_key_rotation_and_keyring_errors() -> Result<()> {
|
||||
let _cache_lock = SECRETS_CACHE_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
for namespace in [
|
||||
LocalSecretsNamespace::ManagedSecrets,
|
||||
LocalSecretsNamespace::CodexAuth,
|
||||
] {
|
||||
let home = tempfile::tempdir()?;
|
||||
let keyring = Arc::new(MockKeyringStore::default());
|
||||
let backend = LocalSecretsBackend::new_with_namespace(
|
||||
home.path().to_path_buf(),
|
||||
keyring.clone(),
|
||||
namespace,
|
||||
);
|
||||
let scope = SecretScope::Global;
|
||||
let name = SecretName::new("TEST_SECRET")?;
|
||||
backend.set(&scope, &name, "original")?;
|
||||
assert_eq!(backend.get(&scope, &name)?, Some("original".to_string()));
|
||||
let ciphertext = fs::read(backend.secrets_path())?;
|
||||
let account = compute_keyring_account(home.path(), namespace);
|
||||
let original_key = keyring
|
||||
.load(keyring_service(), &account)?
|
||||
.expect("persisted encryption key");
|
||||
|
||||
// A cached snapshot cannot make a removed file appear to exist.
|
||||
fs::remove_file(backend.secrets_path())?;
|
||||
assert_eq!(backend.get(&scope, &name)?, None);
|
||||
assert_eq!(backend.list(/*scope_filter*/ None)?, Vec::new());
|
||||
fs::write(backend.secrets_path(), &ciphertext)?;
|
||||
assert_eq!(backend.get(&scope, &name)?, Some("original".to_string()));
|
||||
|
||||
// Neither a changed encryption key nor a keyring error may reuse plaintext.
|
||||
let replacement_key = generate_passphrase()?;
|
||||
keyring.save(keyring_service(), &account, replacement_key.expose_secret())?;
|
||||
assert!(backend.get(&scope, &name).is_err());
|
||||
keyring.save(keyring_service(), &account, &original_key)?;
|
||||
assert_eq!(backend.get(&scope, &name)?, Some("original".to_string()));
|
||||
keyring.set_error(
|
||||
&account,
|
||||
KeyringError::PlatformFailure(Box::new(std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
"keyring is locked",
|
||||
))),
|
||||
);
|
||||
assert!(backend.get(&scope, &name).is_err());
|
||||
|
||||
fs::write(backend.secrets_path(), b"invalid ciphertext")?;
|
||||
assert!(backend.get(&scope, &name).is_err());
|
||||
fs::write(backend.secrets_path(), &ciphertext)?;
|
||||
assert_eq!(backend.get(&scope, &name)?, Some("original".to_string()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_caches_keep_homes_and_namespaces_isolated() -> Result<()> {
|
||||
let _cache_lock = SECRETS_CACHE_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
let homes = [tempfile::tempdir()?, tempfile::tempdir()?];
|
||||
let keyring = Arc::new(MockKeyringStore::default());
|
||||
let scope = SecretScope::Global;
|
||||
let name = SecretName::new("TEST_SECRET")?;
|
||||
let mut backends = Vec::new();
|
||||
for (index, home) in homes.iter().enumerate() {
|
||||
for namespace in [
|
||||
LocalSecretsNamespace::ManagedSecrets,
|
||||
LocalSecretsNamespace::CodexAuth,
|
||||
LocalSecretsNamespace::McpOAuth,
|
||||
] {
|
||||
let backend = LocalSecretsBackend::new_with_namespace(
|
||||
home.path().to_path_buf(),
|
||||
keyring.clone(),
|
||||
namespace,
|
||||
);
|
||||
let value = format!("{index}-{namespace:?}");
|
||||
backend.set(&scope, &name, &value)?;
|
||||
backends.push((backend, value));
|
||||
}
|
||||
}
|
||||
for (backend, value) in backends.iter().rev().chain(backends.iter()) {
|
||||
assert_eq!(backend.get(&scope, &name)?, Some(value.clone()));
|
||||
assert_eq!(
|
||||
backend.list(Some(&scope))?,
|
||||
vec![SecretListEntry {
|
||||
scope: scope.clone(),
|
||||
name: name.clone(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saves_cache_committed_contents_and_preserve_them_after_a_failed_commit() -> Result<()> {
|
||||
let _cache_lock = SECRETS_CACHE_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
for namespace in [
|
||||
LocalSecretsNamespace::ManagedSecrets,
|
||||
LocalSecretsNamespace::CodexAuth,
|
||||
LocalSecretsNamespace::McpOAuth,
|
||||
LocalSecretsNamespace::GatewayOAuth,
|
||||
] {
|
||||
let home = tempfile::tempdir()?;
|
||||
let keyring = Arc::new(MockKeyringStore::default());
|
||||
let backend =
|
||||
LocalSecretsBackend::new_with_namespace(home.path().to_path_buf(), keyring, namespace);
|
||||
let scope = SecretScope::Global;
|
||||
let name = SecretName::new("TEST_SECRET")?;
|
||||
backend.set(&scope, &name, "committed")?;
|
||||
let committed = Arc::clone(
|
||||
&backend
|
||||
.decrypted_cache()
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.as_ref()
|
||||
.expect("successful save should populate the cache")
|
||||
.file,
|
||||
);
|
||||
|
||||
// The first read after a save, including through a clone, needs no decryption.
|
||||
assert_eq!(
|
||||
backend.clone().get(&scope, &name)?,
|
||||
Some("committed".to_string())
|
||||
);
|
||||
assert!(Arc::ptr_eq(
|
||||
&committed,
|
||||
&backend
|
||||
.decrypted_cache()
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.as_ref()
|
||||
.expect("read should retain the committed snapshot")
|
||||
.file,
|
||||
));
|
||||
|
||||
// A directory at the destination makes the atomic replacement fail on
|
||||
// every platform without relying on permissions or timing.
|
||||
let path = backend.secrets_path();
|
||||
let backup = home.path().join("committed.age");
|
||||
fs::rename(&path, &backup)?;
|
||||
fs::create_dir(&path)?;
|
||||
let attempted = SecretsFile::new_empty();
|
||||
assert!(backend.save_file(&attempted).is_err());
|
||||
assert!(Arc::ptr_eq(
|
||||
&committed,
|
||||
&backend
|
||||
.decrypted_cache()
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.as_ref()
|
||||
.expect("failed save should retain the committed snapshot")
|
||||
.file,
|
||||
));
|
||||
fs::remove_dir(&path)?;
|
||||
fs::rename(&backup, &path)?;
|
||||
assert_eq!(backend.get(&scope, &name)?, Some("committed".to_string()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
87
codex-rs/secrets/src/sanitizer.rs
Normal file
87
codex-rs/secrets/src/sanitizer.rs
Normal file
@@ -0,0 +1,87 @@
|
||||
use regex::Regex;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
static OPENAI_KEY_REGEX: LazyLock<Regex> = LazyLock::new(|| compile_regex(r"sk-[A-Za-z0-9]{20,}"));
|
||||
static AWS_ACCESS_KEY_ID_REGEX: LazyLock<Regex> =
|
||||
LazyLock::new(|| compile_regex(r"\bAKIA[0-9A-Z]{16}\b"));
|
||||
static BEARER_TOKEN_REGEX: LazyLock<Regex> =
|
||||
LazyLock::new(|| compile_regex(r"(?i:\bBearer)[ \t]+[A-Za-z0-9._~+/-]{16,}=*"));
|
||||
static SECRET_ASSIGNMENT_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
||||
compile_regex(r#"(?i)\b(api[_-]?key|token|secret|password)\b(\s*[:=]\s*)(["']?)[^\s"']{8,}"#)
|
||||
});
|
||||
|
||||
/// Remove secret and keys from a String. This is done on best effort basis following some
|
||||
/// well-known REGEX.
|
||||
pub fn redact_secrets(input: String) -> String {
|
||||
let redacted = BEARER_TOKEN_REGEX.replace_all(&input, "Bearer [REDACTED_SECRET]");
|
||||
let redacted = OPENAI_KEY_REGEX.replace_all(&redacted, "[REDACTED_SECRET]");
|
||||
let redacted = AWS_ACCESS_KEY_ID_REGEX.replace_all(&redacted, "[REDACTED_SECRET]");
|
||||
let redacted = SECRET_ASSIGNMENT_REGEX.replace_all(&redacted, "$1$2$3[REDACTED_SECRET]");
|
||||
|
||||
redacted.to_string()
|
||||
}
|
||||
|
||||
fn compile_regex(pattern: &str) -> Regex {
|
||||
match Regex::new(pattern) {
|
||||
Ok(regex) => regex,
|
||||
Err(err) => panic!("invalid regex pattern `{pattern}`: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn redacts_supported_bearer_tokens() {
|
||||
let cases = [
|
||||
(
|
||||
"Bearer abcde+fghijklmnopqrstuvwxyz012345",
|
||||
"Bearer [REDACTED_SECRET]",
|
||||
),
|
||||
(
|
||||
"Bearer abcdefghijklmnop+secret_suffix",
|
||||
"Bearer [REDACTED_SECRET]",
|
||||
),
|
||||
(
|
||||
"Bearer sk-abcdefghijklmnopqrst+secret_suffix",
|
||||
"Bearer [REDACTED_SECRET]",
|
||||
),
|
||||
(
|
||||
"Bearer AKIAABCDEFGHIJKLMNOP/~secret_suffix",
|
||||
"Bearer [REDACTED_SECRET]",
|
||||
),
|
||||
(
|
||||
"Bearer AbcdefghijklMN09._~+/-==; echo done",
|
||||
"Bearer [REDACTED_SECRET]; echo done",
|
||||
),
|
||||
(
|
||||
"authorization: bEaReR\tabcdefghijklmnop",
|
||||
"authorization: Bearer [REDACTED_SECRET]",
|
||||
),
|
||||
("Bearer abcdefghijklmnop", "Bearer [REDACTED_SECRET]"),
|
||||
];
|
||||
|
||||
for (input, expected) in cases {
|
||||
assert_eq!(redact_secrets(input.to_string()), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn avoids_bearer_false_positives() {
|
||||
let cases = [
|
||||
"Bearer of good news",
|
||||
"Bearer abcdefghijklmno",
|
||||
"NotABearer abcdefghijklmnop",
|
||||
"Bearerabcdefghijklmnop",
|
||||
"Bearer\nabcdefghijklmnop",
|
||||
"Bearer\u{a0}abcdefghijklmnop",
|
||||
"Bearer abcdefghijklmno\u{212a}",
|
||||
];
|
||||
|
||||
for input in cases {
|
||||
assert_eq!(redact_secrets(input.to_string()), input);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user