aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
9
akode-rs/login/src/auth/api_key.rs
Normal file
9
akode-rs/login/src/auth/api_key.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
//! API-key routing hints. Prefixes do not validate credentials or grant access.
|
||||
|
||||
/// Whether the key carries a FedRAMP issuance marker.
|
||||
///
|
||||
/// Unmarked keys may predate the marker, so `false` does not establish that a key
|
||||
/// is commercial. Authentication must still use the complete, unchanged key.
|
||||
pub fn is_fedramp_api_key(api_key: &str) -> bool {
|
||||
api_key.starts_with("sk-proj-fedramp-") || api_key.starts_with("sk-svcacct-fedramp-")
|
||||
}
|
||||
32
akode-rs/login/src/auth/auth_headers.rs
Normal file
32
akode-rs/login/src/auth/auth_headers.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
use std::fmt;
|
||||
|
||||
use http::HeaderMap;
|
||||
|
||||
/// Request headers returned by an external auth provider.
|
||||
///
|
||||
/// The provider owns credential validation, rotation, and persistence. Codex
|
||||
/// keeps the resolved headers in memory and attaches them to backend requests.
|
||||
/// Identity headers must be derived from and bound to the validated credentials;
|
||||
/// Codex may use them to enforce managed authentication policy.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct AuthHeaders {
|
||||
headers: HeaderMap,
|
||||
}
|
||||
|
||||
impl AuthHeaders {
|
||||
pub fn new(headers: HeaderMap) -> Self {
|
||||
Self { headers }
|
||||
}
|
||||
|
||||
pub fn headers(&self) -> &HeaderMap {
|
||||
&self.headers
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for AuthHeaders {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("AuthHeaders")
|
||||
.field("headers", &"<redacted>")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
1065
akode-rs/login/src/auth/auth_tests.rs
Normal file
1065
akode-rs/login/src/auth/auth_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
93
akode-rs/login/src/auth/change_state.rs
Normal file
93
akode-rs/login/src/auth/change_state.rs
Normal file
@@ -0,0 +1,93 @@
|
||||
//! Tracks credential changes separately from ownership changes, before notifications coalesce.
|
||||
|
||||
use super::AuthManager;
|
||||
use super::CodexAuth;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// An account owner within a particular credential source, retained by in-flight work.
|
||||
#[derive(Clone)]
|
||||
pub struct AuthOwner {
|
||||
manager: Arc<AuthManager>,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
impl AuthOwner {
|
||||
pub(super) fn new(manager: Arc<AuthManager>, generation: u64) -> Self {
|
||||
Self {
|
||||
manager,
|
||||
generation,
|
||||
}
|
||||
}
|
||||
|
||||
/// Watch credential changes from the source that owns this work.
|
||||
pub fn changes(&self) -> tokio::sync::watch::Receiver<AuthChangeState> {
|
||||
self.manager.auth_change_state_receiver()
|
||||
}
|
||||
|
||||
pub fn is_current(&self) -> bool {
|
||||
self.changes().borrow().owner_generation == self.generation
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for AuthOwner {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
Arc::ptr_eq(&self.manager, &other.manager) && self.generation == other.generation
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for AuthOwner {}
|
||||
|
||||
impl std::fmt::Debug for AuthOwner {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AuthOwner")
|
||||
.field("generation", &self.generation)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Opaque revisions local to one auth manager. Consumers must reset on reconnect.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AuthChangeState {
|
||||
/// Advances on cached credential changes and explicit invalidation of pending reads.
|
||||
pub generation: u64,
|
||||
/// Advances on login, logout, or changes of user, workspace, service account, or auth mode.
|
||||
/// Credential changes with incomplete owner identity also advance this revision.
|
||||
/// Losing login metadata alone preserves the account owner.
|
||||
pub owner_generation: u64,
|
||||
/// Advances on an underlying actor credential/source change, including a new OAuth login.
|
||||
/// Renewal within an identifiable OAuth session or WIF subject preserves this revision.
|
||||
pub source_generation: u64,
|
||||
/// Preserves strict login ownership for EMA, including loss of login metadata.
|
||||
pub login_generation: u64,
|
||||
}
|
||||
|
||||
/// Whether request preparation can use the credentials it selected.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RequestAuthChange {
|
||||
Unchanged,
|
||||
CredentialsChanged,
|
||||
OwnerChanged,
|
||||
}
|
||||
|
||||
impl AuthChangeState {
|
||||
/// Compare a completed attempt with its original owner and starting credential revision.
|
||||
pub fn compare_for_request(&self, expected_owner: u64, prepared: Self) -> RequestAuthChange {
|
||||
if self.owner_generation != expected_owner {
|
||||
RequestAuthChange::OwnerChanged
|
||||
} else if self.generation != prepared.generation {
|
||||
RequestAuthChange::CredentialsChanged
|
||||
} else {
|
||||
RequestAuthChange::Unchanged
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stored and host-supplied credentials carry no verifiable account identity, so any
|
||||
/// credential change is treated as a new owner.
|
||||
pub(super) fn same_owner(_previous: Option<&CodexAuth>, _current: Option<&CodexAuth>) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(super) fn same_login(previous: Option<&CodexAuth>, current: Option<&CodexAuth>) -> bool {
|
||||
same_owner(previous, current)
|
||||
}
|
||||
213
akode-rs/login/src/auth/change_state_tests.rs
Normal file
213
akode-rs/login/src/auth/change_state_tests.rs
Normal file
@@ -0,0 +1,213 @@
|
||||
use super::*;
|
||||
use crate::auth::storage::AuthStorageBackend;
|
||||
use crate::auth::storage::FileAuthStorage;
|
||||
use akode_http_client::DestinationPolicy;
|
||||
use akode_http_client::NetworkPolicyController;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
fn api_key(key: &str) -> CodexAuth {
|
||||
CodexAuth::from_api_key(key)
|
||||
}
|
||||
|
||||
fn header_auth(token: &'static str) -> CodexAuth {
|
||||
CodexAuth::Headers(AuthHeaders::new(http::HeaderMap::from_iter([(
|
||||
http::header::AUTHORIZATION,
|
||||
http::HeaderValue::from_static(token),
|
||||
)])))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_owner_generation_tracks_every_credential_change() {
|
||||
let mut manager = AuthManager::from_optional_auth_for_testing(/*auth*/ None);
|
||||
let controller = NetworkPolicyController::default();
|
||||
let policy = controller.policy();
|
||||
Arc::get_mut(&mut manager).unwrap().auth_route_config =
|
||||
AuthRouteConfig::from_http_client_factory(
|
||||
manager
|
||||
.http_client_factory()
|
||||
.with_network_policy(policy.clone()),
|
||||
);
|
||||
let endpoint = "https://example.com/".parse().unwrap();
|
||||
let mut changes = manager.auth_change_state_receiver();
|
||||
let mut legacy_changes = manager.auth_change_receiver();
|
||||
let initial = api_key("key-1");
|
||||
// Stored credentials carry no account identity, so every credential change is an owner
|
||||
// change; re-publishing the same credential is not.
|
||||
for (auth, generation, owner_generation) in [
|
||||
(Some(initial.clone()), 1, 1),
|
||||
(Some(initial), 1, 1),
|
||||
(Some(api_key("key-2")), 2, 2),
|
||||
(Some(header_auth("Bearer header-1")), 3, 3),
|
||||
(Some(header_auth("Bearer header-1")), 3, 3),
|
||||
(Some(header_auth("Bearer header-2")), 4, 4),
|
||||
(None, 5, 5),
|
||||
] {
|
||||
let previous_owner = changes.borrow().owner_generation;
|
||||
let factory = manager.http_client_factory();
|
||||
manager.set_cached_auth(auth);
|
||||
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
|
||||
assert_eq!(
|
||||
factory.network_policy().acquire(&endpoint).is_ok(),
|
||||
owner_generation == previous_owner,
|
||||
);
|
||||
assert_eq!(
|
||||
*changes.borrow_and_update(),
|
||||
AuthChangeState {
|
||||
generation,
|
||||
owner_generation,
|
||||
source_generation: generation,
|
||||
login_generation: owner_generation,
|
||||
},
|
||||
);
|
||||
assert_eq!(*legacy_changes.borrow_and_update(), generation);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial(codex_auth_env)]
|
||||
async fn auth_reload_and_refresh_read_failure_preserves_network_permit() {
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let storage = FileAuthStorage::new(home.path().to_path_buf());
|
||||
let stored = crate::AuthDotJson {
|
||||
auth_mode: Some(akode_protocol::auth::AuthMode::ApiKey),
|
||||
openai_api_key: Some("stored-key".to_string()),
|
||||
};
|
||||
storage.save(&stored).unwrap();
|
||||
let controller = NetworkPolicyController::default();
|
||||
let policy = controller.policy();
|
||||
let manager = AuthManager::new(
|
||||
home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
crate::AuthCredentialsStoreMode::File,
|
||||
crate::AuthKeyringBackendKind::default(),
|
||||
AuthRouteConfig::from_http_client_factory(
|
||||
crate::test_support::transport_default_auth_route_config()
|
||||
.http_client_factory()
|
||||
.clone()
|
||||
.with_network_policy(policy.clone()),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let initial_auth = manager.auth_cached().unwrap();
|
||||
assert_eq!(initial_auth.api_key(), Some("stored-key"));
|
||||
let changes = manager.auth_change_state_receiver();
|
||||
let initial_changes = *changes.borrow();
|
||||
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
|
||||
let permit = policy
|
||||
.acquire(&"https://example.com/".parse().unwrap())
|
||||
.unwrap();
|
||||
|
||||
let nested_secret = json!({
|
||||
"auth_mode": "apikey",
|
||||
"OPENAI_API_KEY": ["private-credential-value"],
|
||||
})
|
||||
.to_string();
|
||||
// Cover interrupted writes and credential values rejected by outer or nested JSON parsing.
|
||||
for contents in [
|
||||
"",
|
||||
r#"{"OPENAI_API_KEY":"private-credential-value""#,
|
||||
nested_secret.as_str(),
|
||||
] {
|
||||
std::fs::write(home.path().join("auth.json"), contents).unwrap();
|
||||
let reload_error = manager.reload_with_cached_auth().await.unwrap_err();
|
||||
// Stored API keys are never refreshed, so refresh leaves the cached credential alone.
|
||||
manager.refresh_token().await.unwrap();
|
||||
for formatted in [reload_error.to_string(), format!("{reload_error:?}")] {
|
||||
assert!(
|
||||
!formatted.contains("private-credential-value"),
|
||||
"{formatted}"
|
||||
);
|
||||
}
|
||||
assert_eq!(manager.auth_cached(), Some(initial_auth.clone()));
|
||||
assert_eq!(*changes.borrow(), initial_changes);
|
||||
assert_eq!(permit.check(), Ok(()));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auth_owner_generation_preserves_logout_and_switches_when_coalesced() {
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let initial = api_key("key-a");
|
||||
let manager =
|
||||
AuthManager::from_auth_for_testing_with_home(initial.clone(), home.path().to_path_buf());
|
||||
let mut changes = manager.auth_change_state_receiver();
|
||||
|
||||
let generation = changes.borrow().generation;
|
||||
manager.logout().await.unwrap();
|
||||
assert!(
|
||||
manager
|
||||
.publish_reloaded_auth(generation, Some(initial.clone()))
|
||||
.is_none()
|
||||
);
|
||||
assert!(manager.auth_cached().is_none());
|
||||
// Deletion also fences a read when the cache was already empty.
|
||||
let generation = changes.borrow().generation;
|
||||
manager.logout().await.unwrap();
|
||||
assert!(
|
||||
manager
|
||||
.publish_reloaded_auth(generation, Some(initial.clone()))
|
||||
.is_none()
|
||||
);
|
||||
manager.set_cached_auth(Some(initial.clone()));
|
||||
assert_eq!(
|
||||
*changes.borrow_and_update(),
|
||||
AuthChangeState {
|
||||
generation: 4,
|
||||
owner_generation: 2,
|
||||
source_generation: 2,
|
||||
login_generation: 2,
|
||||
},
|
||||
);
|
||||
|
||||
manager.set_cached_auth(Some(api_key("key-b")));
|
||||
manager.set_cached_auth(Some(initial));
|
||||
assert_eq!(
|
||||
*changes.borrow_and_update(),
|
||||
AuthChangeState {
|
||||
generation: 6,
|
||||
owner_generation: 4,
|
||||
source_generation: 4,
|
||||
login_generation: 4,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn captured_credentials_are_revoked_if_credentials_change_before_client_construction() {
|
||||
let mut manager = AuthManager::from_optional_auth_for_testing(/*auth*/ None);
|
||||
let controller = NetworkPolicyController::default();
|
||||
let policy = controller.policy();
|
||||
Arc::get_mut(&mut manager).unwrap().auth_route_config =
|
||||
AuthRouteConfig::from_http_client_factory(
|
||||
manager
|
||||
.http_client_factory()
|
||||
.with_network_policy(policy.clone()),
|
||||
);
|
||||
let initial = api_key("key-a");
|
||||
manager.set_cached_auth(Some(initial.clone()));
|
||||
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
|
||||
let (auth, factory) = manager.auth_with_http_client_factory().await.unwrap();
|
||||
|
||||
manager.set_cached_auth(Some(api_key("key-b")));
|
||||
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
|
||||
let client = crate::default_client::create_client_for_route_async(
|
||||
factory,
|
||||
"https://example.com/".to_string(),
|
||||
akode_http_client::ClientRouteClass::Api,
|
||||
crate::default_client::ClientRedirectPolicy::Default,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(auth.api_key(), initial.api_key());
|
||||
assert!(matches!(
|
||||
client
|
||||
.get("https://example.com/")
|
||||
.bearer_auth(auth.get_token().unwrap())
|
||||
.send()
|
||||
.await,
|
||||
Err(akode_http_client::RouteAwareRequestError::Policy(
|
||||
akode_http_client::NetworkPolicyDenied::Revoked
|
||||
))
|
||||
));
|
||||
}
|
||||
461
akode-rs/login/src/auth/default_client.rs
Normal file
461
akode-rs/login/src/auth/default_client.rs
Normal file
@@ -0,0 +1,461 @@
|
||||
//! Default Codex HTTP client: shared `User-Agent`, `originator`, optional residency header, and
|
||||
//! HTTP client and transport construction.
|
||||
//!
|
||||
//! Use [`crate::default_client`] or [`akode_login::default_client`] from other crates in this
|
||||
//! workspace.
|
||||
|
||||
use akode_http_client::BuildRouteAwareHttpClientError;
|
||||
use akode_http_client::ClientRouteClass;
|
||||
use akode_http_client::HttpClient;
|
||||
use akode_http_client::HttpClientBuilder;
|
||||
use akode_http_client::HttpClientFactory;
|
||||
use akode_http_client::OutboundProxyPolicy;
|
||||
pub use akode_http_client::RequestBuilder as CodexRequestBuilder;
|
||||
use akode_http_client::ReqwestTransport;
|
||||
use akode_http_client::RouteAwareClientPool;
|
||||
use akode_terminal_detection::user_agent;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
use http::header::USER_AGENT;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::RwLock;
|
||||
|
||||
/// Set this to add a suffix to the User-Agent string.
|
||||
///
|
||||
/// It is not ideal that we're using a global singleton for this.
|
||||
/// This is primarily designed to differentiate MCP clients from each other.
|
||||
/// Because there can only be one MCP server per process, it should be safe for this to be a global static.
|
||||
/// However, future users of this should use this with caution as a result.
|
||||
/// In addition, we want to be confident that this value is used for ALL clients and doing that requires a
|
||||
/// lot of wiring and it's easy to miss code paths by doing so.
|
||||
/// See https://github.com/openai/codex/pull/3388/files for an example of what that would look like.
|
||||
/// Finally, we want to make sure this is set for ALL mcp clients without needing to know a special env var
|
||||
/// or having to set data that they already specified in the mcp initialize request somewhere else.
|
||||
///
|
||||
/// A space is automatically added between the suffix and the rest of the User-Agent string.
|
||||
/// The full user agent string is returned from the mcp initialize response.
|
||||
/// Parenthesis will be added by Codex. This should only specify what goes inside of the parenthesis.
|
||||
pub static USER_AGENT_SUFFIX: LazyLock<Mutex<Option<String>>> = LazyLock::new(|| Mutex::new(None));
|
||||
pub const DEFAULT_ORIGINATOR: &str = "codex_cli_rs";
|
||||
pub const AKODE_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR: &str = "AKODE_INTERNAL_ORIGINATOR_OVERRIDE";
|
||||
pub use akode_model_provider_info::RESIDENCY_HEADER_NAME;
|
||||
pub use akode_model_provider_info::ResidencyRequirement;
|
||||
pub use akode_model_provider_info::read_managed_residency_requirement as read_default_client_residency_requirement;
|
||||
pub use akode_model_provider_info::set_managed_residency_requirement as set_default_client_residency_requirement;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Originator {
|
||||
pub value: String,
|
||||
pub header_value: HeaderValue,
|
||||
}
|
||||
static ORIGINATOR: LazyLock<RwLock<Option<Originator>>> = LazyLock::new(|| RwLock::new(None));
|
||||
static ROUTE_AWARE_CLIENT_BUILD_PERMIT: tokio::sync::Semaphore =
|
||||
tokio::sync::Semaphore::const_new(1);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SetOriginatorError {
|
||||
InvalidHeaderValue,
|
||||
AlreadyInitialized,
|
||||
}
|
||||
|
||||
fn get_originator_value(provided: Option<String>) -> Originator {
|
||||
let value = std::env::var(AKODE_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR)
|
||||
.ok()
|
||||
.or(provided)
|
||||
.unwrap_or(DEFAULT_ORIGINATOR.to_string());
|
||||
|
||||
match HeaderValue::from_str(&value) {
|
||||
Ok(header_value) => Originator {
|
||||
value,
|
||||
header_value,
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::error!("Unable to turn originator override {value} into header value: {e}");
|
||||
Originator {
|
||||
value: DEFAULT_ORIGINATOR.to_string(),
|
||||
header_value: HeaderValue::from_static(DEFAULT_ORIGINATOR),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_default_originator(value: String) -> Result<(), SetOriginatorError> {
|
||||
if HeaderValue::from_str(&value).is_err() {
|
||||
return Err(SetOriginatorError::InvalidHeaderValue);
|
||||
}
|
||||
let originator = get_originator_value(Some(value));
|
||||
let Ok(mut guard) = ORIGINATOR.write() else {
|
||||
return Err(SetOriginatorError::AlreadyInitialized);
|
||||
};
|
||||
if guard.is_some() {
|
||||
return Err(SetOriginatorError::AlreadyInitialized);
|
||||
}
|
||||
*guard = Some(originator);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn originator() -> Originator {
|
||||
if let Ok(guard) = ORIGINATOR.read()
|
||||
&& let Some(originator) = guard.as_ref()
|
||||
{
|
||||
return originator.clone();
|
||||
}
|
||||
|
||||
if std::env::var(AKODE_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR).is_ok() {
|
||||
let originator = get_originator_value(/*provided*/ None);
|
||||
if let Ok(mut guard) = ORIGINATOR.write() {
|
||||
match guard.as_ref() {
|
||||
Some(originator) => return originator.clone(),
|
||||
None => *guard = Some(originator.clone()),
|
||||
}
|
||||
}
|
||||
return originator;
|
||||
}
|
||||
|
||||
get_originator_value(/*provided*/ None)
|
||||
}
|
||||
|
||||
/// Adds a valid, non-default thread originator override to request headers.
|
||||
///
|
||||
/// The default client already supplies the process originator. Thread-scoped callers should use
|
||||
/// this helper to override that value only when the thread originator differs.
|
||||
pub fn add_originator_header(headers: &mut HeaderMap, originator_value: &str) {
|
||||
let default_originator = originator();
|
||||
if originator_value == default_originator.value.as_str() {
|
||||
return;
|
||||
}
|
||||
|
||||
match HeaderValue::from_str(originator_value) {
|
||||
Ok(header_value) => {
|
||||
headers.insert("originator", header_value);
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::warn!("ignoring invalid thread originator header value: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_first_party_originator(originator_value: &str) -> bool {
|
||||
originator_value == DEFAULT_ORIGINATOR
|
||||
|| originator_value == "akode-tui"
|
||||
|| originator_value == "codex_vscode"
|
||||
|| originator_value.starts_with("Codex ")
|
||||
}
|
||||
|
||||
pub fn is_first_party_chat_originator(originator_value: &str) -> bool {
|
||||
originator_value == "codex_atlas" || originator_value == "codex_chatgpt_desktop"
|
||||
}
|
||||
|
||||
pub fn get_codex_user_agent() -> String {
|
||||
// OS discovery can spawn subprocesses on Linux. Reuse it across requests,
|
||||
// while continuing to read the mutable originator and suffix below.
|
||||
static OS_INFO: LazyLock<os_info::Info> = LazyLock::new(os_info::get);
|
||||
let build_version = env!("CARGO_PKG_VERSION");
|
||||
let os_info = &*OS_INFO;
|
||||
let originator = originator();
|
||||
let prefix = format!(
|
||||
"{}/{build_version} ({} {}; {}) {}",
|
||||
originator.value.as_str(),
|
||||
os_info.os_type(),
|
||||
os_info.version(),
|
||||
os_info.architecture().unwrap_or("unknown"),
|
||||
user_agent()
|
||||
);
|
||||
let suffix = USER_AGENT_SUFFIX
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|guard| guard.clone());
|
||||
let suffix = suffix
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map_or_else(String::new, |value| format!(" ({value})"));
|
||||
|
||||
let candidate = format!("{prefix}{suffix}");
|
||||
sanitize_user_agent(candidate, &prefix)
|
||||
}
|
||||
|
||||
/// Sanitize the user agent string.
|
||||
///
|
||||
/// Invalid characters are replaced with an underscore.
|
||||
///
|
||||
/// If the user agent fails to parse, it falls back to fallback and then to ORIGINATOR.
|
||||
fn sanitize_user_agent(candidate: String, fallback: &str) -> String {
|
||||
if HeaderValue::from_str(candidate.as_str()).is_ok() {
|
||||
return candidate;
|
||||
}
|
||||
|
||||
let sanitized: String = candidate
|
||||
.chars()
|
||||
.map(|ch| if matches!(ch, ' '..='~') { ch } else { '_' })
|
||||
.collect();
|
||||
if !sanitized.is_empty() && HeaderValue::from_str(sanitized.as_str()).is_ok() {
|
||||
tracing::warn!(
|
||||
"Sanitized Codex user agent because provided suffix contained invalid header characters"
|
||||
);
|
||||
sanitized
|
||||
} else if HeaderValue::from_str(fallback).is_ok() {
|
||||
tracing::warn!(
|
||||
"Falling back to base Codex user agent because provided suffix could not be sanitized"
|
||||
);
|
||||
fallback.to_string()
|
||||
} else {
|
||||
tracing::warn!(
|
||||
"Falling back to default Codex originator because base user agent string is invalid"
|
||||
);
|
||||
originator().value
|
||||
}
|
||||
}
|
||||
|
||||
/// Create an HTTP client with default `originator` and `User-Agent` headers set.
|
||||
///
|
||||
/// This supported default path preserves the transport's existing proxy behavior and does not opt into
|
||||
/// Codex's route-aware system/PAC resolution.
|
||||
pub fn create_client() -> HttpClient {
|
||||
build_default_client(default_http_client_builder())
|
||||
}
|
||||
|
||||
/// Create the default HTTP client without request URL or response-header diagnostics.
|
||||
///
|
||||
/// This preserves the default client's legacy custom-CA fallback and transport proxy behavior while
|
||||
/// avoiding diagnostics that could expose credentials embedded in request URLs or headers.
|
||||
pub fn create_client_without_request_logging() -> HttpClient {
|
||||
build_default_client(default_http_client_builder().without_request_logging())
|
||||
}
|
||||
|
||||
/// Builds the default Codex HTTP client for a concrete outbound route.
|
||||
///
|
||||
/// When route-aware proxy handling is disabled, or the client is running inside the Codex
|
||||
/// sandbox, this preserves the default client's existing proxy behavior. Otherwise it resolves
|
||||
/// the destination through the shared system/PAC-aware routing policy.
|
||||
pub fn create_client_for_route(
|
||||
http_client_factory: &HttpClientFactory,
|
||||
request_url: &str,
|
||||
route_class: ClientRouteClass,
|
||||
redirect_policy: ClientRedirectPolicy,
|
||||
) -> Result<HttpClient, BuildRouteAwareHttpClientError> {
|
||||
let legacy_fallback = redirect_policy == ClientRedirectPolicy::Default
|
||||
|| !http_client_factory.protects_sensitive_headers();
|
||||
let builder = match redirect_policy {
|
||||
ClientRedirectPolicy::Default => default_http_client_builder(),
|
||||
ClientRedirectPolicy::Reject => default_http_client_builder().without_redirects(),
|
||||
};
|
||||
create_client_for_route_with_builder(
|
||||
http_client_factory,
|
||||
request_url,
|
||||
route_class,
|
||||
builder,
|
||||
legacy_fallback,
|
||||
)
|
||||
}
|
||||
|
||||
fn create_client_for_route_with_builder(
|
||||
http_client_factory: &HttpClientFactory,
|
||||
request_url: &str,
|
||||
route_class: ClientRouteClass,
|
||||
builder: HttpClientBuilder,
|
||||
legacy_fallback: bool,
|
||||
) -> Result<HttpClient, BuildRouteAwareHttpClientError> {
|
||||
if http_client_factory.network_policy().is_managed()
|
||||
|| http_client_factory.protects_sensitive_headers()
|
||||
|| !legacy_fallback
|
||||
{
|
||||
let mut pool = akode_http_client::RouteAwareClientPool::with_builder(
|
||||
http_client_factory.clone(),
|
||||
route_class,
|
||||
builder,
|
||||
);
|
||||
if is_sandboxed() {
|
||||
pool = if legacy_fallback {
|
||||
pool.with_legacy_direct_proxy_and_custom_ca_fallback()
|
||||
} else {
|
||||
pool.with_direct_proxy()
|
||||
};
|
||||
} else if legacy_fallback
|
||||
&& matches!(
|
||||
http_client_factory.outbound_proxy_policy(),
|
||||
OutboundProxyPolicy::ReqwestDefault
|
||||
)
|
||||
{
|
||||
pool = pool.with_legacy_custom_ca_fallback();
|
||||
}
|
||||
return Ok(pool.into_client());
|
||||
}
|
||||
if matches!(
|
||||
http_client_factory.outbound_proxy_policy(),
|
||||
OutboundProxyPolicy::ReqwestDefault
|
||||
) {
|
||||
return Ok(build_default_client(builder));
|
||||
}
|
||||
if is_sandboxed() {
|
||||
// Preserve the sandbox's existing no-proxy policy; sandboxed command egress is routed
|
||||
// separately through network-proxy.
|
||||
return Ok(build_default_client(builder));
|
||||
}
|
||||
|
||||
builder.build_respecting_outbound_proxy_policy(http_client_factory, request_url, route_class)
|
||||
}
|
||||
|
||||
/// Redirect handling for the shared HTTP client builders.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ClientRedirectPolicy {
|
||||
Default,
|
||||
Reject,
|
||||
}
|
||||
|
||||
/// Builds the default Codex HTTP client for a concrete outbound route without blocking the
|
||||
/// async runtime worker that initiated the request.
|
||||
pub async fn create_client_for_route_async(
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_url: String,
|
||||
route_class: ClientRouteClass,
|
||||
redirect_policy: ClientRedirectPolicy,
|
||||
) -> std::io::Result<HttpClient> {
|
||||
let legacy_fallback = redirect_policy == ClientRedirectPolicy::Default
|
||||
|| !http_client_factory.protects_sensitive_headers();
|
||||
create_client_for_route_async_with_builder(
|
||||
http_client_factory,
|
||||
request_url,
|
||||
route_class,
|
||||
move || match redirect_policy {
|
||||
ClientRedirectPolicy::Default => default_http_client_builder(),
|
||||
ClientRedirectPolicy::Reject => default_http_client_builder().without_redirects(),
|
||||
},
|
||||
legacy_fallback,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Builds a routed default client without request URL or response-header diagnostics.
|
||||
pub async fn create_client_for_route_without_request_logging_async(
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_url: String,
|
||||
route_class: ClientRouteClass,
|
||||
) -> std::io::Result<HttpClient> {
|
||||
create_client_for_route_async_with_builder(
|
||||
http_client_factory,
|
||||
request_url,
|
||||
route_class,
|
||||
|| default_http_client_builder().without_request_logging(),
|
||||
/*legacy_fallback*/ true,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn create_client_for_route_async_with_builder(
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_url: String,
|
||||
route_class: ClientRouteClass,
|
||||
builder: impl FnOnce() -> HttpClientBuilder + Send + 'static,
|
||||
legacy_fallback: bool,
|
||||
) -> std::io::Result<HttpClient> {
|
||||
let permit = ROUTE_AWARE_CLIENT_BUILD_PERMIT
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(std::io::Error::other)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let _permit = permit;
|
||||
create_client_for_route_with_builder(
|
||||
&http_client_factory,
|
||||
&request_url,
|
||||
route_class,
|
||||
builder(),
|
||||
legacy_fallback,
|
||||
)
|
||||
.map_err(std::io::Error::from)
|
||||
})
|
||||
.await
|
||||
.map_err(std::io::Error::other)?
|
||||
}
|
||||
|
||||
/// Builds the default Codex transport without blocking the async runtime worker.
|
||||
///
|
||||
/// Route-aware proxy handling resolves each request and redirect destination. When it is disabled,
|
||||
/// or the client is running inside the Codex sandbox, this preserves the default client's proxy
|
||||
/// behavior while retaining managed application network policy enforcement.
|
||||
pub async fn create_transport_for_routes_async(
|
||||
http_client_factory: HttpClientFactory,
|
||||
route_class: ClientRouteClass,
|
||||
redirect_policy: ClientRedirectPolicy,
|
||||
) -> std::io::Result<ReqwestTransport> {
|
||||
let permit = ROUTE_AWARE_CLIENT_BUILD_PERMIT
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(std::io::Error::other)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let _permit = permit;
|
||||
let sandboxed = is_sandboxed();
|
||||
let transport_default_proxy = matches!(
|
||||
http_client_factory.outbound_proxy_policy(),
|
||||
OutboundProxyPolicy::ReqwestDefault
|
||||
);
|
||||
if redirect_policy == ClientRedirectPolicy::Default
|
||||
&& !http_client_factory.network_policy().is_managed()
|
||||
&& !http_client_factory.protects_sensitive_headers()
|
||||
&& (transport_default_proxy || sandboxed)
|
||||
{
|
||||
return ReqwestTransport::from_http_client(create_client());
|
||||
}
|
||||
|
||||
let mut pool = RouteAwareClientPool::with_builder(
|
||||
http_client_factory,
|
||||
route_class,
|
||||
match redirect_policy {
|
||||
ClientRedirectPolicy::Default => default_http_client_builder(),
|
||||
ClientRedirectPolicy::Reject => default_http_client_builder().without_redirects(),
|
||||
},
|
||||
);
|
||||
if sandboxed {
|
||||
pool = match redirect_policy {
|
||||
ClientRedirectPolicy::Default => {
|
||||
pool.with_legacy_direct_proxy_and_custom_ca_fallback()
|
||||
}
|
||||
ClientRedirectPolicy::Reject => pool.with_direct_proxy(),
|
||||
};
|
||||
} else if transport_default_proxy && redirect_policy == ClientRedirectPolicy::Default {
|
||||
pool = pool.with_legacy_custom_ca_fallback();
|
||||
}
|
||||
ReqwestTransport::from_route_aware_client_pool(pool)
|
||||
})
|
||||
.await
|
||||
.map_err(std::io::Error::other)
|
||||
}
|
||||
|
||||
fn default_http_client_builder() -> HttpClientBuilder {
|
||||
HttpClientBuilder::new().default_headers(default_headers())
|
||||
}
|
||||
|
||||
// These legacy constructors intentionally preserve the infallible behavior of `create_client`.
|
||||
// New endpoint-aware call sites use `create_client_for_route` and propagate construction errors.
|
||||
#[allow(deprecated)]
|
||||
fn build_default_client(builder: HttpClientBuilder) -> HttpClient {
|
||||
if is_sandboxed() {
|
||||
builder.build_direct_with_custom_ca_fallback()
|
||||
} else {
|
||||
builder.build_with_transport_default_proxy_and_custom_ca_fallback()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_headers() -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("originator", originator().header_value);
|
||||
if let Ok(user_agent) = HeaderValue::from_str(&get_codex_user_agent()) {
|
||||
headers.insert(USER_AGENT, user_agent);
|
||||
}
|
||||
if let Some(requirement) = read_default_client_residency_requirement() {
|
||||
let value = match requirement {
|
||||
ResidencyRequirement::Us => HeaderValue::from_static("us"),
|
||||
};
|
||||
headers.insert(RESIDENCY_HEADER_NAME, value);
|
||||
}
|
||||
headers
|
||||
}
|
||||
|
||||
fn is_sandboxed() -> bool {
|
||||
std::env::var("AKODE_SANDBOX").as_deref() == Ok("seatbelt")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "default_client_tests.rs"]
|
||||
mod tests;
|
||||
413
akode-rs/login/src/auth/default_client_tests.rs
Normal file
413
akode-rs/login/src/auth/default_client_tests.rs
Normal file
@@ -0,0 +1,413 @@
|
||||
use super::sanitize_user_agent;
|
||||
use super::*;
|
||||
use core_test_support::skip_if_no_network;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestLogWriter {
|
||||
buffer: Arc<Mutex<Vec<u8>>>,
|
||||
}
|
||||
|
||||
struct TestLogSink {
|
||||
buffer: Arc<Mutex<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for TestLogWriter {
|
||||
type Writer = TestLogSink;
|
||||
|
||||
fn make_writer(&'a self) -> Self::Writer {
|
||||
TestLogSink {
|
||||
buffer: Arc::clone(&self.buffer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for TestLogSink {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.buffer.lock().expect("log buffer lock").extend(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_codex_user_agent() {
|
||||
let user_agent = get_codex_user_agent();
|
||||
let originator = originator().value;
|
||||
let prefix = format!("{originator}/");
|
||||
assert!(user_agent.starts_with(&prefix));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "linux")]
|
||||
fn os_discovery_is_cached_without_freezing_user_agent_overrides() {
|
||||
const PROBE_DIR: &str = "AKODE_TEST_USER_AGENT_PROBE_DIR";
|
||||
if std::env::var_os(PROBE_DIR).is_some() {
|
||||
// Race the first lookup as well as exercising repeated requests.
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..8 {
|
||||
scope.spawn(|| {
|
||||
for _ in 0..4 {
|
||||
assert!(get_codex_user_agent().contains("Ubuntu 99.7.3"));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
set_default_originator("cached-os-test".to_string()).expect("set originator");
|
||||
*USER_AGENT_SUFFIX.lock().expect("suffix lock") = Some("updated-client".to_string());
|
||||
let user_agent = get_codex_user_agent();
|
||||
assert!(user_agent.starts_with("cached-os-test/"));
|
||||
assert!(user_agent.ends_with(" (updated-client)"));
|
||||
return;
|
||||
}
|
||||
|
||||
// Use a fresh process so neither the cached OS nor the mutable overrides can
|
||||
// be initialized by another test. Only the child's environment is changed.
|
||||
let temp = tempfile::tempdir().expect("probe directory");
|
||||
for (program, output) in [
|
||||
("lsb_release", "Distributor ID: Ubuntu\nRelease: 99.7.3\n"),
|
||||
("getconf", "64\n"),
|
||||
] {
|
||||
let script = temp.path().join(program);
|
||||
akode_utils_cargo_bin::write_executable(
|
||||
&script,
|
||||
&format!(
|
||||
"#!/bin/sh\nprintf '{program}\\n' >> \"${PROBE_DIR}/calls\"\nprintf '{output}'\n"
|
||||
),
|
||||
)
|
||||
.expect("write probe");
|
||||
}
|
||||
let output = std::process::Command::new(std::env::current_exe().expect("test executable"))
|
||||
.args([
|
||||
"--exact",
|
||||
concat!(
|
||||
module_path!(),
|
||||
"::os_discovery_is_cached_without_freezing_user_agent_overrides"
|
||||
)
|
||||
.trim_start_matches("akode_login::"),
|
||||
"--nocapture",
|
||||
])
|
||||
.env(PROBE_DIR, temp.path())
|
||||
.env("PATH", temp.path())
|
||||
.env_remove(AKODE_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR)
|
||||
.output()
|
||||
.expect("run isolated user-agent test");
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
let calls = std::fs::read_to_string(temp.path().join("calls")).expect("probe calls");
|
||||
let mut calls = calls.lines().collect::<Vec<_>>();
|
||||
calls.sort_unstable();
|
||||
assert_eq!(calls, vec!["getconf", "lsb_release"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_first_party_originator_matches_known_values() {
|
||||
assert_eq!(is_first_party_originator(DEFAULT_ORIGINATOR), true);
|
||||
assert_eq!(is_first_party_originator("akode-tui"), true);
|
||||
assert_eq!(is_first_party_originator("codex_vscode"), true);
|
||||
assert_eq!(is_first_party_originator("Codex Something Else"), true);
|
||||
assert_eq!(is_first_party_originator("akode_cli"), false);
|
||||
assert_eq!(is_first_party_originator("Other"), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_first_party_chat_originator_matches_known_values() {
|
||||
assert_eq!(is_first_party_chat_originator("codex_atlas"), true);
|
||||
assert_eq!(
|
||||
is_first_party_chat_originator("codex_chatgpt_desktop"),
|
||||
true
|
||||
);
|
||||
assert_eq!(is_first_party_chat_originator(DEFAULT_ORIGINATOR), false);
|
||||
assert_eq!(is_first_party_chat_originator("codex_vscode"), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_originator_header_inserts_non_default_originator() {
|
||||
let default_originator = originator();
|
||||
let thread_originator = if default_originator.value == "chatgpt_cca" {
|
||||
"codex_work_cca"
|
||||
} else {
|
||||
"chatgpt_cca"
|
||||
};
|
||||
let mut headers = HeaderMap::new();
|
||||
|
||||
add_originator_header(&mut headers, thread_originator);
|
||||
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("originator")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some(thread_originator)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_originator_header_preserves_provider_default() {
|
||||
let default_originator = originator();
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"originator",
|
||||
HeaderValue::from_static("provider-originator"),
|
||||
);
|
||||
|
||||
add_originator_header(&mut headers, &default_originator.value);
|
||||
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("originator")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("provider-originator")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_originator_header_omits_invalid_originator() {
|
||||
let mut headers = HeaderMap::new();
|
||||
|
||||
add_originator_header(&mut headers, "invalid\noriginator");
|
||||
|
||||
assert!(headers.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_create_client_sets_default_headers() {
|
||||
skip_if_no_network!();
|
||||
|
||||
set_default_client_residency_requirement(Some(ResidencyRequirement::Us));
|
||||
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
let client = create_client();
|
||||
|
||||
// Spin up a local mock server and capture a request.
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/"))
|
||||
.respond_with(ResponseTemplate::new(200))
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let resp = client
|
||||
.get(server.uri())
|
||||
.send()
|
||||
.await
|
||||
.expect("failed to send request");
|
||||
assert!(resp.status().is_success());
|
||||
|
||||
let requests = server
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("failed to fetch received requests");
|
||||
assert!(!requests.is_empty());
|
||||
let headers = &requests[0].headers;
|
||||
|
||||
// originator header is set to the provided value
|
||||
let originator_header = headers
|
||||
.get("originator")
|
||||
.expect("originator header missing");
|
||||
assert_eq!(originator_header.to_str().unwrap(), originator().value);
|
||||
|
||||
// User-Agent matches the computed Codex UA for that originator
|
||||
let expected_ua = get_codex_user_agent();
|
||||
let ua_header = headers
|
||||
.get("user-agent")
|
||||
.expect("user-agent header missing");
|
||||
assert_eq!(ua_header.to_str().unwrap(), expected_ua);
|
||||
|
||||
let residency_header = headers
|
||||
.get(RESIDENCY_HEADER_NAME)
|
||||
.expect("residency header missing");
|
||||
assert_eq!(residency_header.to_str().unwrap(), "us");
|
||||
|
||||
set_default_client_residency_requirement(/*enforce_residency*/ None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raw_auth_client_does_not_log_sensitive_request_or_response_data() {
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/token"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.insert_header("x-sensitive-response", "response-secret-value"),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let authority = server
|
||||
.uri()
|
||||
.strip_prefix("http://")
|
||||
.expect("wiremock URI should use HTTP")
|
||||
.to_string();
|
||||
let endpoint = format!(
|
||||
"http://auth-user:password-secret-value@{authority}/token?client_secret=query-secret-value"
|
||||
);
|
||||
let client = crate::test_support::transport_default_auth_route_config()
|
||||
.http_client_factory()
|
||||
.build_client_without_request_logging(&endpoint, ClientRouteClass::Auth)
|
||||
.expect("raw auth client should build");
|
||||
let buffer = Arc::new(Mutex::new(Vec::new()));
|
||||
let subscriber = tracing_subscriber::registry().with(
|
||||
tracing_subscriber::fmt::layer()
|
||||
.with_ansi(false)
|
||||
.with_writer(TestLogWriter {
|
||||
buffer: Arc::clone(&buffer),
|
||||
}),
|
||||
);
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
tracing::debug!("log capture sentinel");
|
||||
|
||||
let response = client
|
||||
.post(&endpoint)
|
||||
.header("x-sensitive-request", "request-header-secret-value")
|
||||
.body("request-body-secret-value")
|
||||
.send()
|
||||
.await
|
||||
.expect("raw auth request should succeed");
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let unresponsive_listener = std::net::TcpListener::bind("127.0.0.1:0")
|
||||
.expect("unresponsive local listener should bind");
|
||||
let unresponsive_addr = unresponsive_listener
|
||||
.local_addr()
|
||||
.expect("unresponsive local address should be available");
|
||||
let unresponsive_endpoint = format!(
|
||||
"http://auth-user:failure-password-secret-value@{unresponsive_addr}/token?client_secret=failure-query-secret-value"
|
||||
);
|
||||
let unresponsive_client = crate::test_support::transport_default_auth_route_config()
|
||||
.http_client_factory()
|
||||
.build_client_without_request_logging(&unresponsive_endpoint, ClientRouteClass::Auth)
|
||||
.expect("raw auth client should build");
|
||||
let error = unresponsive_client
|
||||
.post(&unresponsive_endpoint)
|
||||
.header("x-sensitive-request", "failure-request-header-secret-value")
|
||||
.body("failure-request-body-secret-value")
|
||||
.timeout(std::time::Duration::from_secs(1))
|
||||
.send()
|
||||
.await
|
||||
.expect_err("request to an unresponsive local listener should time out");
|
||||
assert!(error.is_timeout());
|
||||
|
||||
let logs = String::from_utf8(buffer.lock().expect("log buffer lock").clone())
|
||||
.expect("logs should be UTF-8");
|
||||
assert!(logs.contains("log capture sentinel"));
|
||||
assert!(!logs.contains("password-secret-value"));
|
||||
assert!(!logs.contains("query-secret-value"));
|
||||
assert!(!logs.contains("request-header-secret-value"));
|
||||
assert!(!logs.contains("request-body-secret-value"));
|
||||
assert!(!logs.contains("response-secret-value"));
|
||||
assert!(!logs.contains("failure-password-secret-value"));
|
||||
assert!(!logs.contains("failure-query-secret-value"));
|
||||
assert!(!logs.contains("failure-request-header-secret-value"));
|
||||
assert!(!logs.contains("failure-request-body-secret-value"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_suffix_is_sanitized() {
|
||||
let prefix = "codex_cli_rs/0.0.0";
|
||||
let suffix = "bad\rsuffix";
|
||||
|
||||
assert_eq!(
|
||||
sanitize_user_agent(format!("{prefix} ({suffix})"), prefix),
|
||||
"codex_cli_rs/0.0.0 (bad_suffix)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_suffix_is_sanitized2() {
|
||||
let prefix = "codex_cli_rs/0.0.0";
|
||||
let suffix = "bad\0suffix";
|
||||
|
||||
assert_eq!(
|
||||
sanitize_user_agent(format!("{prefix} ({suffix})"), prefix),
|
||||
"codex_cli_rs/0.0.0 (bad_suffix)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn test_macos() {
|
||||
use regex_lite::Regex;
|
||||
let user_agent = get_codex_user_agent();
|
||||
let originator = regex_lite::escape(originator().value.as_str());
|
||||
let re = Regex::new(&format!(
|
||||
r"^{originator}/\d+\.\d+\.\d+ \(Mac OS \d+\.\d+\.\d+; (x86_64|arm64)\) (\S+)$"
|
||||
))
|
||||
.unwrap();
|
||||
assert!(re.is_match(&user_agent));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn signed_reject_routes_preserve_invalid_ca_errors() {
|
||||
const CHILD: &str = "AKODE_TEST_SIGNED_ROUTE_INVALID_CA";
|
||||
if std::env::var_os(CHILD).is_none() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let ca = dir.path().join("invalid.pem");
|
||||
std::fs::write(&ca, "invalid certificate").unwrap();
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.arg("signed_reject_routes_preserve_invalid_ca_errors")
|
||||
.arg("--nocapture")
|
||||
.env(CHILD, "1")
|
||||
.env("AKODE_CA_CERTIFICATE", ca)
|
||||
.env_remove("SSL_CERT_FILE")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
|
||||
return;
|
||||
}
|
||||
|
||||
let url = "https://127.0.0.1:9/";
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
.with_sensitive_header_protection();
|
||||
let sync_client = create_client_for_route(
|
||||
&factory,
|
||||
url,
|
||||
ClientRouteClass::Api,
|
||||
ClientRedirectPolicy::Reject,
|
||||
)
|
||||
.unwrap();
|
||||
let async_client = create_client_for_route_async(
|
||||
factory,
|
||||
url.into(),
|
||||
ClientRouteClass::Api,
|
||||
ClientRedirectPolicy::Reject,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for client in [sync_client, async_client] {
|
||||
let error = client.get(url).send().await.unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
error,
|
||||
akode_http_client::HttpError::Route(
|
||||
akode_http_client::RouteAwareClientPoolError::Build(
|
||||
akode_http_client::BuildRouteAwareHttpClientError::CustomCa(_)
|
||||
)
|
||||
)
|
||||
),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
2
akode-rs/login/src/auth/error.rs
Normal file
2
akode-rs/login/src/auth/error.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub use akode_protocol::auth::RefreshTokenFailedError;
|
||||
pub use akode_protocol::auth::RefreshTokenFailedReason;
|
||||
184
akode-rs/login/src/auth/external_bearer.rs
Normal file
184
akode-rs/login/src/auth/external_bearer.rs
Normal file
@@ -0,0 +1,184 @@
|
||||
use super::manager::CodexAuth;
|
||||
use super::manager::ExternalAuth;
|
||||
use super::manager::ExternalAuthFuture;
|
||||
use super::manager::ExternalAuthRefreshContext;
|
||||
use akode_protocol::config_types::ModelProviderAuthInfo;
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsString;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::ops::Deref;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
use tokio::process::Command;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct BearerTokenRefresher {
|
||||
state: Arc<ExternalBearerAuthState>,
|
||||
}
|
||||
|
||||
impl BearerTokenRefresher {
|
||||
pub(crate) fn new(config: ModelProviderAuthInfo, env: HashMap<String, OsString>) -> Self {
|
||||
Self {
|
||||
state: Arc::new(ExternalBearerAuthState::new(config, env)),
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "external bearer cache misses intentionally hold cached_token across the provider command to avoid duplicate refreshes"
|
||||
)]
|
||||
async fn resolve(&self) -> io::Result<CodexAuth> {
|
||||
let access_token = {
|
||||
let mut cached = self.state.cached_token.lock().await;
|
||||
if let Some(cached_token) = cached.as_ref() {
|
||||
let should_use_cached_token = match self.state.config.refresh_interval() {
|
||||
Some(refresh_interval) => cached_token.fetched_at.elapsed() < refresh_interval,
|
||||
None => true,
|
||||
};
|
||||
if should_use_cached_token {
|
||||
return Ok(CodexAuth::from_api_key(cached_token.access_token.as_str()));
|
||||
}
|
||||
}
|
||||
|
||||
let access_token =
|
||||
run_provider_auth_command(&self.state.config, &self.state.env).await?;
|
||||
*cached = Some(CachedExternalBearerToken {
|
||||
access_token: access_token.clone(),
|
||||
fetched_at: Instant::now(),
|
||||
});
|
||||
access_token
|
||||
};
|
||||
Ok(CodexAuth::from_api_key(access_token.as_str()))
|
||||
}
|
||||
|
||||
async fn refresh(&self, _context: ExternalAuthRefreshContext) -> io::Result<CodexAuth> {
|
||||
let access_token = run_provider_auth_command(&self.state.config, &self.state.env).await?;
|
||||
let mut cached = self.state.cached_token.lock().await;
|
||||
*cached = Some(CachedExternalBearerToken {
|
||||
access_token: access_token.clone(),
|
||||
fetched_at: Instant::now(),
|
||||
});
|
||||
Ok(CodexAuth::from_api_key(access_token.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
impl ExternalAuth for BearerTokenRefresher {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(BearerTokenRefresher::resolve(self))
|
||||
}
|
||||
|
||||
fn refresh(&self, context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(BearerTokenRefresher::refresh(self, context))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for BearerTokenRefresher {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("BearerTokenRefresher")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
struct ExternalBearerAuthState {
|
||||
config: ModelProviderAuthInfo,
|
||||
env: HashMap<String, OsString>,
|
||||
cached_token: Mutex<Option<CachedExternalBearerToken>>,
|
||||
}
|
||||
|
||||
impl ExternalBearerAuthState {
|
||||
fn new(config: ModelProviderAuthInfo, env: HashMap<String, OsString>) -> Self {
|
||||
Self {
|
||||
config,
|
||||
env,
|
||||
cached_token: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct CachedExternalBearerToken {
|
||||
access_token: String,
|
||||
fetched_at: Instant,
|
||||
}
|
||||
|
||||
async fn run_provider_auth_command(
|
||||
config: &ModelProviderAuthInfo,
|
||||
env: &HashMap<String, OsString>,
|
||||
) -> io::Result<String> {
|
||||
let program = resolve_provider_auth_program(&config.command, &config.cwd)?;
|
||||
let mut command = Command::from(akode_utils_process::background_command(&program));
|
||||
command
|
||||
.args(config.args.iter().map(Deref::deref))
|
||||
.envs(env)
|
||||
.current_dir(config.cwd.as_path())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
|
||||
let output = tokio::time::timeout(config.timeout(), command.output())
|
||||
.await
|
||||
.map_err(|_| {
|
||||
io::Error::other(format!(
|
||||
"provider auth command `{}` timed out after {} ms",
|
||||
config.command,
|
||||
config.timeout_ms.get()
|
||||
))
|
||||
})?
|
||||
.map_err(|err| {
|
||||
io::Error::new(
|
||||
err.kind(),
|
||||
format!(
|
||||
"provider auth command `{}` failed to start: {err}",
|
||||
config.command
|
||||
),
|
||||
)
|
||||
})?;
|
||||
|
||||
if !output.status.success() {
|
||||
let status = output.status;
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
let stderr_suffix = if stderr.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(": {stderr}")
|
||||
};
|
||||
return Err(io::Error::other(format!(
|
||||
"provider auth command `{}` exited with status {status}{stderr_suffix}",
|
||||
config.command
|
||||
)));
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8(output.stdout).map_err(|_| {
|
||||
io::Error::other(format!(
|
||||
"provider auth command `{}` wrote non-UTF-8 data to stdout",
|
||||
config.command
|
||||
))
|
||||
})?;
|
||||
let access_token = stdout.trim().to_string();
|
||||
if access_token.is_empty() {
|
||||
return Err(io::Error::other(format!(
|
||||
"provider auth command `{}` produced an empty token",
|
||||
config.command
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(access_token)
|
||||
}
|
||||
|
||||
fn resolve_provider_auth_program(command: &str, cwd: &Path) -> io::Result<PathBuf> {
|
||||
let path = Path::new(command);
|
||||
if path.is_absolute() {
|
||||
return Ok(path.to_path_buf());
|
||||
}
|
||||
|
||||
if path.components().count() > 1 {
|
||||
return Ok(cwd.join(path));
|
||||
}
|
||||
|
||||
Ok(PathBuf::from(command))
|
||||
}
|
||||
1618
akode-rs/login/src/auth/manager.rs
Normal file
1618
akode-rs/login/src/auth/manager.rs
Normal file
File diff suppressed because it is too large
Load Diff
25
akode-rs/login/src/auth/mod.rs
Normal file
25
akode-rs/login/src/auth/mod.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
mod api_key;
|
||||
mod auth_headers;
|
||||
mod change_state;
|
||||
pub mod default_client;
|
||||
pub mod error;
|
||||
mod source;
|
||||
mod storage;
|
||||
|
||||
mod external_bearer;
|
||||
mod manager;
|
||||
mod provider_api_key;
|
||||
|
||||
pub use api_key::is_fedramp_api_key;
|
||||
pub use auth_headers::AuthHeaders;
|
||||
pub use change_state::AuthChangeState;
|
||||
pub use change_state::AuthOwner;
|
||||
pub use change_state::RequestAuthChange;
|
||||
pub use error::RefreshTokenFailedError;
|
||||
pub use error::RefreshTokenFailedReason;
|
||||
pub use manager::*;
|
||||
pub use provider_api_key::PROVIDER_API_KEYS_FILE;
|
||||
pub use provider_api_key::ProviderApiKeyFileStore;
|
||||
pub use provider_api_key::configured_provider_api_key_store;
|
||||
pub use provider_api_key::configured_provider_api_key_store_with_keyring;
|
||||
pub use provider_api_key::install_provider_api_key_store;
|
||||
256
akode-rs/login/src/auth/provider_api_key.rs
Normal file
256
akode-rs/login/src/auth/provider_api_key.rs
Normal file
@@ -0,0 +1,256 @@
|
||||
//! Per-provider API key storage for `api_key = "keyring"` providers.
|
||||
//!
|
||||
//! Follows the same policy as CLI auth storage (`AuthCredentialsStoreMode`):
|
||||
//! - `keyring`: system keyring only (Keychain, Credential Manager, Secret Service/keyutils);
|
||||
//! - `file`: `AKODE_HOME/provider_api_keys.json`, private like `auth.json`;
|
||||
//! - `auto` (default): keyring when available, otherwise the file (for example headless
|
||||
//! Linux without Secret Service/D-Bus);
|
||||
//! - `ephemeral`: process memory only.
|
||||
//!
|
||||
//! Keys never appear in errors, `Debug` output or logs.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use akode_config::types::AuthCredentialsStoreMode;
|
||||
use akode_keyring_store::DefaultKeyringStore;
|
||||
use akode_keyring_store::KeyringStore;
|
||||
use akode_model_provider_info::KeyringProviderApiKeyStore;
|
||||
use akode_model_provider_info::ProviderApiKeyLocation;
|
||||
use akode_model_provider_info::ProviderApiKeyStore;
|
||||
use tracing::warn;
|
||||
|
||||
use super::storage::write_private_credential_file;
|
||||
|
||||
/// File name of the fallback store in AKODE_HOME.
|
||||
pub const PROVIDER_API_KEYS_FILE: &str = "provider_api_keys.json";
|
||||
|
||||
/// Private JSON file mapping provider ids to API keys.
|
||||
#[derive(Clone)]
|
||||
pub struct ProviderApiKeyFileStore {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ProviderApiKeyFileStore {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ProviderApiKeyFileStore")
|
||||
.field("path", &self.path)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl ProviderApiKeyFileStore {
|
||||
pub fn new(codex_home: &Path) -> Self {
|
||||
Self {
|
||||
path: codex_home.join(PROVIDER_API_KEYS_FILE),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
fn read_all(&self) -> Result<BTreeMap<String, String>, String> {
|
||||
match std::fs::read(&self.path) {
|
||||
Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| {
|
||||
// serde_json may quote values; report only the position.
|
||||
format!(
|
||||
"{} is not valid (line {} column {})",
|
||||
self.path.display(),
|
||||
error.line(),
|
||||
error.column()
|
||||
)
|
||||
}),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(BTreeMap::new()),
|
||||
Err(error) => Err(format!("cannot read {}: {error}", self.path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_all(&self, keys: &BTreeMap<String, String>) -> Result<(), String> {
|
||||
if keys.is_empty() {
|
||||
return match std::fs::remove_file(&self.path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(error) => Err(format!("cannot remove {}: {error}", self.path.display())),
|
||||
};
|
||||
}
|
||||
let data = serde_json::to_vec_pretty(keys)
|
||||
.map_err(|_| "cannot encode provider API keys".to_string())?;
|
||||
write_private_credential_file(&self.path, &data)
|
||||
.map_err(|error| format!("cannot write {}: {error}", self.path.display()))
|
||||
}
|
||||
|
||||
fn location(&self) -> ProviderApiKeyLocation {
|
||||
ProviderApiKeyLocation::File {
|
||||
path: self.path.display().to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ProviderApiKeyStore for ProviderApiKeyFileStore {
|
||||
fn load(&self, provider_id: &str) -> Result<Option<String>, String> {
|
||||
Ok(self
|
||||
.read_all()?
|
||||
.remove(provider_id)
|
||||
.filter(|key| !key.trim().is_empty()))
|
||||
}
|
||||
|
||||
fn save(&self, provider_id: &str, api_key: &str) -> Result<ProviderApiKeyLocation, String> {
|
||||
let mut keys = self.read_all()?;
|
||||
keys.insert(provider_id.to_string(), api_key.to_string());
|
||||
self.write_all(&keys)?;
|
||||
Ok(self.location())
|
||||
}
|
||||
|
||||
fn delete(&self, provider_id: &str) -> Result<bool, String> {
|
||||
let mut keys = self.read_all()?;
|
||||
let removed = keys.remove(provider_id).is_some();
|
||||
if removed {
|
||||
self.write_all(&keys)?;
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
fn locate(&self, provider_id: &str) -> Result<Option<ProviderApiKeyLocation>, String> {
|
||||
Ok(self.load(provider_id)?.map(|_| self.location()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Keyring first; the file when the keyring is unavailable or has no entry.
|
||||
#[derive(Debug)]
|
||||
struct AutoProviderApiKeyStore {
|
||||
keyring: KeyringProviderApiKeyStore,
|
||||
file: ProviderApiKeyFileStore,
|
||||
}
|
||||
|
||||
impl ProviderApiKeyStore for AutoProviderApiKeyStore {
|
||||
fn load(&self, provider_id: &str) -> Result<Option<String>, String> {
|
||||
match self.keyring.load(provider_id) {
|
||||
Ok(Some(key)) => Ok(Some(key)),
|
||||
Ok(None) => self.file.load(provider_id),
|
||||
Err(error) => {
|
||||
warn!("provider API key keyring unavailable, using file storage: {error}");
|
||||
self.file.load(provider_id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn save(&self, provider_id: &str, api_key: &str) -> Result<ProviderApiKeyLocation, String> {
|
||||
match self.keyring.save(provider_id, api_key) {
|
||||
Ok(location) => {
|
||||
// Do not leave an older copy behind in the fallback file.
|
||||
if let Err(error) = self.file.delete(provider_id) {
|
||||
warn!("could not remove the old file copy of a provider API key: {error}");
|
||||
}
|
||||
Ok(location)
|
||||
}
|
||||
Err(error) => {
|
||||
warn!("provider API key keyring unavailable, using file storage: {error}");
|
||||
self.file.save(provider_id, api_key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn delete(&self, provider_id: &str) -> Result<bool, String> {
|
||||
let keyring = self.keyring.delete(provider_id);
|
||||
let file = self.file.delete(provider_id)?;
|
||||
match keyring {
|
||||
Ok(removed) => Ok(removed || file),
|
||||
Err(_) if file => Ok(true),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn locate(&self, provider_id: &str) -> Result<Option<ProviderApiKeyLocation>, String> {
|
||||
match self.keyring.locate(provider_id) {
|
||||
Ok(Some(location)) => Ok(Some(location)),
|
||||
Ok(None) | Err(_) => self.file.locate(provider_id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Process-memory store for `ephemeral` mode.
|
||||
#[derive(Default)]
|
||||
struct EphemeralProviderApiKeyStore {
|
||||
keys: Mutex<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EphemeralProviderApiKeyStore {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("EphemeralProviderApiKeyStore")
|
||||
}
|
||||
}
|
||||
|
||||
impl ProviderApiKeyStore for EphemeralProviderApiKeyStore {
|
||||
fn load(&self, provider_id: &str) -> Result<Option<String>, String> {
|
||||
Ok(self
|
||||
.keys
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.get(provider_id)
|
||||
.cloned())
|
||||
}
|
||||
|
||||
fn save(&self, provider_id: &str, api_key: &str) -> Result<ProviderApiKeyLocation, String> {
|
||||
self.keys
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.insert(provider_id.to_string(), api_key.to_string());
|
||||
Ok(ProviderApiKeyLocation::Memory)
|
||||
}
|
||||
|
||||
fn delete(&self, provider_id: &str) -> Result<bool, String> {
|
||||
Ok(self
|
||||
.keys
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(provider_id)
|
||||
.is_some())
|
||||
}
|
||||
|
||||
fn locate(&self, provider_id: &str) -> Result<Option<ProviderApiKeyLocation>, String> {
|
||||
Ok(self
|
||||
.load(provider_id)?
|
||||
.map(|_| ProviderApiKeyLocation::Memory))
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the provider key store for `mode` with an explicit keyring backend.
|
||||
pub fn configured_provider_api_key_store_with_keyring(
|
||||
codex_home: &Path,
|
||||
mode: AuthCredentialsStoreMode,
|
||||
keyring: Arc<dyn KeyringStore>,
|
||||
) -> Arc<dyn ProviderApiKeyStore> {
|
||||
let keyring = KeyringProviderApiKeyStore::new(keyring);
|
||||
let file = ProviderApiKeyFileStore::new(codex_home);
|
||||
match mode {
|
||||
AuthCredentialsStoreMode::Keyring => Arc::new(keyring),
|
||||
AuthCredentialsStoreMode::File => Arc::new(file),
|
||||
AuthCredentialsStoreMode::Auto => Arc::new(AutoProviderApiKeyStore { keyring, file }),
|
||||
AuthCredentialsStoreMode::Ephemeral => Arc::new(EphemeralProviderApiKeyStore::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the provider key store for `mode` using the system keyring.
|
||||
pub fn configured_provider_api_key_store(
|
||||
codex_home: &Path,
|
||||
mode: AuthCredentialsStoreMode,
|
||||
) -> Arc<dyn ProviderApiKeyStore> {
|
||||
configured_provider_api_key_store_with_keyring(codex_home, mode, Arc::new(DefaultKeyringStore))
|
||||
}
|
||||
|
||||
/// Installs the process-wide provider key store used by `api_key = "keyring"`.
|
||||
pub fn install_provider_api_key_store(codex_home: &Path, mode: AuthCredentialsStoreMode) {
|
||||
akode_model_provider_info::set_provider_api_key_store(configured_provider_api_key_store(
|
||||
codex_home, mode,
|
||||
));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "provider_api_key_tests.rs"]
|
||||
mod tests;
|
||||
143
akode-rs/login/src/auth/provider_api_key_tests.rs
Normal file
143
akode-rs/login/src/auth/provider_api_key_tests.rs
Normal file
@@ -0,0 +1,143 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use akode_config::types::AuthCredentialsStoreMode;
|
||||
use akode_keyring_store::tests::MockKeyringStore;
|
||||
use akode_model_provider_info::ProviderApiKeyLocation;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use super::*;
|
||||
|
||||
const SECRET: &str = "sk-provider-secret-0123456789";
|
||||
const ACCOUNT: &str = "model-provider:imeai";
|
||||
|
||||
fn failing_keyring() -> MockKeyringStore {
|
||||
let keyring = MockKeyringStore::default();
|
||||
keyring.set_error(
|
||||
ACCOUNT,
|
||||
keyring::Error::NoStorageAccess(std::io::Error::other("no secret service").into()),
|
||||
);
|
||||
keyring
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_mode_prefers_the_keyring() {
|
||||
let home = TempDir::new().unwrap();
|
||||
let keyring = MockKeyringStore::default();
|
||||
let store = configured_provider_api_key_store_with_keyring(
|
||||
home.path(),
|
||||
AuthCredentialsStoreMode::Auto,
|
||||
Arc::new(keyring.clone()),
|
||||
);
|
||||
let location = store.save("imeai", SECRET).unwrap();
|
||||
assert!(matches!(location, ProviderApiKeyLocation::Keyring { .. }));
|
||||
assert_eq!(keyring.saved_value(ACCOUNT).as_deref(), Some(SECRET));
|
||||
assert!(!home.path().join(PROVIDER_API_KEYS_FILE).exists());
|
||||
assert_eq!(store.load("imeai").unwrap().as_deref(), Some(SECRET));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_mode_falls_back_to_a_private_file_without_a_keyring() {
|
||||
let home = TempDir::new().unwrap();
|
||||
let store = configured_provider_api_key_store_with_keyring(
|
||||
home.path(),
|
||||
AuthCredentialsStoreMode::Auto,
|
||||
Arc::new(failing_keyring()),
|
||||
);
|
||||
let location = store.save("imeai", SECRET).unwrap();
|
||||
let path = home.path().join(PROVIDER_API_KEYS_FILE);
|
||||
assert_eq!(
|
||||
location,
|
||||
ProviderApiKeyLocation::File {
|
||||
path: path.display().to_string()
|
||||
}
|
||||
);
|
||||
assert_eq!(store.load("imeai").unwrap().as_deref(), Some(SECRET));
|
||||
assert_eq!(store.locate("imeai").unwrap(), Some(location.clone()));
|
||||
// The displayed location never includes the key.
|
||||
assert!(!location.to_string().contains(SECRET));
|
||||
assert!(store.delete("imeai").unwrap());
|
||||
assert_eq!(store.load("imeai").unwrap(), None);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn file_store_is_readable_only_by_the_owner() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let home = TempDir::new().unwrap();
|
||||
let store = ProviderApiKeyFileStore::new(home.path());
|
||||
store.save("imeai", SECRET).unwrap();
|
||||
store.save("other", "second-secret").unwrap();
|
||||
let mode = std::fs::metadata(store.path())
|
||||
.unwrap()
|
||||
.permissions()
|
||||
.mode()
|
||||
& 0o777;
|
||||
assert_eq!(mode, 0o600);
|
||||
assert_eq!(
|
||||
store.load("other").unwrap().as_deref(),
|
||||
Some("second-secret")
|
||||
);
|
||||
assert_eq!(store.load("imeai").unwrap().as_deref(), Some(SECRET));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyring_mode_never_writes_a_file() {
|
||||
let home = TempDir::new().unwrap();
|
||||
let store = configured_provider_api_key_store_with_keyring(
|
||||
home.path(),
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
Arc::new(failing_keyring()),
|
||||
);
|
||||
let error = store.save("imeai", SECRET).unwrap_err();
|
||||
assert!(!error.contains(SECRET), "{error}");
|
||||
assert!(!home.path().join(PROVIDER_API_KEYS_FILE).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_mode_ignores_the_keyring() {
|
||||
let home = TempDir::new().unwrap();
|
||||
let keyring = MockKeyringStore::default();
|
||||
let store = configured_provider_api_key_store_with_keyring(
|
||||
home.path(),
|
||||
AuthCredentialsStoreMode::File,
|
||||
Arc::new(keyring.clone()),
|
||||
);
|
||||
store.save("imeai", SECRET).unwrap();
|
||||
assert!(!keyring.contains(ACCOUNT));
|
||||
assert!(home.path().join(PROVIDER_API_KEYS_FILE).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_file_errors_and_debug_never_contain_keys() {
|
||||
let home = TempDir::new().unwrap();
|
||||
let path = home.path().join(PROVIDER_API_KEYS_FILE);
|
||||
std::fs::write(&path, format!("{{\"imeai\": \"{SECRET}\", broken")).unwrap();
|
||||
let store = ProviderApiKeyFileStore::new(home.path());
|
||||
let error = store.load("imeai").unwrap_err();
|
||||
assert!(!error.contains(SECRET), "{error}");
|
||||
let auto = configured_provider_api_key_store_with_keyring(
|
||||
home.path(),
|
||||
AuthCredentialsStoreMode::Auto,
|
||||
Arc::new(MockKeyringStore::default()),
|
||||
);
|
||||
assert!(!format!("{auto:?}").contains(SECRET));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ephemeral_mode_keeps_keys_in_memory() {
|
||||
let home = TempDir::new().unwrap();
|
||||
let store = configured_provider_api_key_store_with_keyring(
|
||||
home.path(),
|
||||
AuthCredentialsStoreMode::Ephemeral,
|
||||
Arc::new(MockKeyringStore::default()),
|
||||
);
|
||||
assert_eq!(
|
||||
store.save("imeai", SECRET).unwrap(),
|
||||
ProviderApiKeyLocation::Memory
|
||||
);
|
||||
assert_eq!(store.load("imeai").unwrap().as_deref(), Some(SECRET));
|
||||
assert!(!home.path().join(PROVIDER_API_KEYS_FILE).exists());
|
||||
assert!(!format!("{store:?}").contains(SECRET));
|
||||
}
|
||||
19
akode-rs/login/src/auth/source.rs
Normal file
19
akode-rs/login/src/auth/source.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
//! Compare credential sources for local reuse of credential-bound state.
|
||||
|
||||
use super::CodexAuth;
|
||||
|
||||
/// Two credentials share a source only when they are the same kind and expose the
|
||||
/// same bearer token. Header credentials never share a source.
|
||||
pub(super) fn same_source(previous: Option<&CodexAuth>, current: Option<&CodexAuth>) -> bool {
|
||||
let (Some(previous), Some(current)) = (previous, current) else {
|
||||
return false;
|
||||
};
|
||||
if previous.auth_mode() != current.auth_mode() {
|
||||
return false;
|
||||
}
|
||||
let (Ok(previous_token), Ok(current_token)) = (previous.get_token(), current.get_token())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
previous_token == current_token
|
||||
}
|
||||
116
akode-rs/login/src/auth/source_tests.rs
Normal file
116
akode-rs/login/src/auth/source_tests.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
//! Credential-bound state follows the credential source.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn api_key_replacement_and_logout_retire_the_previous_source() {
|
||||
let key_a = CodexAuth::from_api_key("key-a");
|
||||
let key_b = CodexAuth::from_api_key("key-b");
|
||||
let manager = AuthManager::from_auth_for_testing(key_a.clone());
|
||||
let first = manager.auth_change_state_for(&key_a).unwrap();
|
||||
manager.set_cached_auth(Some(key_a.clone()));
|
||||
assert_eq!(first, manager.auth_change_state_for(&key_a).unwrap());
|
||||
manager.set_cached_auth(Some(key_b.clone()));
|
||||
assert!(manager.auth_change_state_for(&key_a).is_none());
|
||||
let second = manager.auth_change_state_for(&key_b).unwrap();
|
||||
manager.set_cached_auth(/*new_auth*/ None);
|
||||
assert!(manager.auth_change_state_for(&key_b).is_none());
|
||||
manager.set_cached_auth(Some(key_b.clone()));
|
||||
assert_ne!(
|
||||
second.source_generation,
|
||||
manager
|
||||
.auth_change_state_for(&key_b)
|
||||
.unwrap()
|
||||
.source_generation
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_api_key_never_reloads_an_ambient_credential() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
login_with_api_key(
|
||||
home.path(),
|
||||
"ambient-key",
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::Direct,
|
||||
)?;
|
||||
let runtime = AuthRuntimeConfig {
|
||||
codex_home: home.path().to_path_buf(),
|
||||
auth_route_config: crate::test_support::transport_default_auth_route_config(),
|
||||
};
|
||||
let manager = AuthManager::from_api_key("selected-key", runtime.clone());
|
||||
for _ in 0..2 {
|
||||
manager.reload().await;
|
||||
assert_eq!(
|
||||
manager.auth().await.expect("selected key").api_key(),
|
||||
Some("selected-key")
|
||||
);
|
||||
assert_eq!(manager.runtime_config(), runtime);
|
||||
}
|
||||
let stored = create_auth_storage(
|
||||
home.path().to_path_buf(),
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::Direct,
|
||||
)
|
||||
.load()?
|
||||
.expect("ambient login remains stored");
|
||||
assert_eq!(stored.openai_api_key.as_deref(), Some("ambient-key"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct RecoverableExternalAuth {
|
||||
current: RwLock<Option<CodexAuth>>,
|
||||
}
|
||||
|
||||
impl ExternalAuth for RecoverableExternalAuth {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async {
|
||||
self.current
|
||||
.read()
|
||||
.unwrap()
|
||||
.clone()
|
||||
.ok_or_else(|| std::io::Error::other("credential source unavailable"))
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn external_source_outage_keeps_cached_credentials_and_identity() {
|
||||
let initial_auth = CodexAuth::from_api_key("external-key-1");
|
||||
let manager = AuthManager::from_auth_for_testing(initial_auth.clone());
|
||||
let source = Arc::new(RecoverableExternalAuth {
|
||||
current: RwLock::new(Some(initial_auth.clone())),
|
||||
});
|
||||
manager.set_external_auth(source.clone()).await.unwrap();
|
||||
let initial = manager.auth_change_state_for(&initial_auth).unwrap();
|
||||
*source.current.write().unwrap() = None;
|
||||
assert_eq!(manager.auth().await, Some(initial_auth.clone()));
|
||||
let (cached_auth, _) = manager.auth_with_http_client_factory().await.unwrap();
|
||||
assert_eq!(cached_auth, initial_auth);
|
||||
assert!(!manager.reload().await);
|
||||
assert_eq!(manager.auth_change_state_for(&initial_auth), Some(initial));
|
||||
|
||||
// A rotated credential is served and retires the previous source.
|
||||
let refreshed = CodexAuth::from_api_key("external-key-2");
|
||||
*source.current.write().unwrap() = Some(refreshed.clone());
|
||||
assert_eq!(manager.auth().await, Some(refreshed.clone()));
|
||||
assert!(manager.auth_change_state_for(&initial_auth).is_none());
|
||||
assert!(manager.auth_change_state_for(&refreshed).is_some());
|
||||
|
||||
manager.clear_external_auth();
|
||||
assert!(manager.auth_change_state_for(&refreshed).is_none());
|
||||
*source.current.write().unwrap() = Some(initial_auth.clone());
|
||||
manager.set_external_auth(source).await.unwrap();
|
||||
assert_ne!(
|
||||
initial.source_generation,
|
||||
manager
|
||||
.auth_change_state_for(&initial_auth)
|
||||
.unwrap()
|
||||
.source_generation
|
||||
);
|
||||
}
|
||||
648
akode-rs/login/src/auth/storage.rs
Normal file
648
akode-rs/login/src/auth/storage.rs
Normal file
@@ -0,0 +1,648 @@
|
||||
use akode_otel::auth_storage::Operation;
|
||||
use akode_otel::auth_storage::Store;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Debug;
|
||||
use std::fs::File;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use tracing::warn;
|
||||
|
||||
#[path = "storage_error.rs"]
|
||||
mod storage_error;
|
||||
|
||||
#[path = "storage_file.rs"]
|
||||
mod storage_file;
|
||||
|
||||
#[path = "storage_commit.rs"]
|
||||
mod storage_commit;
|
||||
|
||||
#[path = "storage_telemetry.rs"]
|
||||
mod storage_telemetry;
|
||||
|
||||
use akode_config::types::AuthCredentialsStoreMode;
|
||||
pub use akode_config::types::AuthKeyringBackendKind;
|
||||
use akode_keyring_store::DefaultKeyringStore;
|
||||
use akode_keyring_store::KeyringStore;
|
||||
use akode_protocol::auth::AuthMode;
|
||||
use akode_secrets::LocalSecretsNamespace;
|
||||
use akode_secrets::SecretName;
|
||||
use akode_secrets::SecretScope;
|
||||
use akode_secrets::SecretsBackendKind;
|
||||
use akode_secrets::SecretsManager;
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
/// Expected structure for $AKODE_HOME/auth.json.
|
||||
#[derive(Serialize, Clone, Debug, PartialEq)]
|
||||
pub struct AuthDotJson {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub auth_mode: Option<AuthMode>,
|
||||
|
||||
#[serde(rename = "OPENAI_API_KEY")]
|
||||
pub openai_api_key: Option<String>,
|
||||
}
|
||||
|
||||
/// On-disk representation that tolerates records written by sign-in methods that
|
||||
/// are no longer supported (for example ChatGPT OAuth tokens).
|
||||
#[derive(Deserialize)]
|
||||
struct StoredAuthDotJson {
|
||||
#[serde(default)]
|
||||
auth_mode: Option<String>,
|
||||
|
||||
#[serde(rename = "OPENAI_API_KEY", default)]
|
||||
openai_api_key: Option<String>,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for AuthDotJson {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let stored = StoredAuthDotJson::deserialize(deserializer)?;
|
||||
let auth_mode = match stored.auth_mode {
|
||||
None => None,
|
||||
Some(raw) => match serde_json::from_value::<AuthMode>(serde_json::Value::String(raw)) {
|
||||
Ok(mode) => Some(mode),
|
||||
// Unsupported legacy credentials must never be reinterpreted as another
|
||||
// credential kind; expose an empty record so callers treat it as logged out.
|
||||
Err(_) => {
|
||||
return Ok(Self {
|
||||
auth_mode: None,
|
||||
openai_api_key: None,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
Ok(Self {
|
||||
auth_mode,
|
||||
openai_api_key: stored.openai_api_key,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Atomically replaces a credential file in AKODE_HOME, like `auth.json`: private (0600 on
|
||||
/// Unix; on Windows the destination DACL, or AKODE_HOME's inherited one, is kept), never
|
||||
/// truncated for concurrent readers, symlinks resolved to their target.
|
||||
pub(crate) fn write_private_credential_file(path: &Path, data: &[u8]) -> std::io::Result<()> {
|
||||
let path = storage_file::resolve_auth_file(path.to_path_buf())?;
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| std::io::Error::other("credential file has no parent"))?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
storage_file::check_replaceable(&path)?;
|
||||
let mut replacement = storage_file::replacement(&path)?;
|
||||
replacement.write_all(data)?;
|
||||
replacement.as_file().sync_all()?;
|
||||
let (_file, temp_path) = replacement.keep().map_err(|error| error.error)?;
|
||||
let mut temp_path = tempfile::TempPath::try_from_path(temp_path)?;
|
||||
std::fs::rename(&temp_path, path)?;
|
||||
temp_path.disable_cleanup(/*disable_cleanup*/ true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn get_auth_file(codex_home: &Path) -> PathBuf {
|
||||
codex_home.join("auth.json")
|
||||
}
|
||||
|
||||
pub(super) fn delete_file_if_exists(codex_home: &Path) -> std::io::Result<bool> {
|
||||
let auth_file = get_auth_file(codex_home);
|
||||
match std::fs::remove_file(&auth_file) {
|
||||
Ok(()) => Ok(true),
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
// Protect in-process read-modify-write commits, never network requests.
|
||||
static AUTH_STORAGE_COMMIT: Mutex<()> = Mutex::new(());
|
||||
|
||||
pub(super) fn auth_storage_commit_guard() -> std::io::Result<std::sync::MutexGuard<'static, ()>> {
|
||||
AUTH_STORAGE_COMMIT
|
||||
.lock()
|
||||
.map_err(|_| std::io::Error::other("Auth storage commit lock is unavailable."))
|
||||
}
|
||||
|
||||
pub(super) trait AuthStorageBackend: Debug + Send + Sync {
|
||||
fn persistent_home(&self) -> Option<&Path> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Serialize the whole read/modify/write across managers and processes.
|
||||
fn lock_for_write(
|
||||
&self,
|
||||
) -> std::io::Result<(std::sync::MutexGuard<'static, ()>, Option<File>)> {
|
||||
let guard = auth_storage_commit_guard()?;
|
||||
let file = if let Some(home) = self.persistent_home() {
|
||||
std::fs::create_dir_all(home)?;
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(home.join("auth.lock"))?;
|
||||
file.lock()?;
|
||||
Some(file)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok((guard, file))
|
||||
}
|
||||
|
||||
fn load(&self) -> std::io::Result<Option<AuthDotJson>>;
|
||||
fn save(&self, auth: &AuthDotJson) -> std::io::Result<()>;
|
||||
fn delete(&self) -> std::io::Result<bool>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct FileAuthStorage {
|
||||
codex_home: PathBuf,
|
||||
}
|
||||
|
||||
impl FileAuthStorage {
|
||||
pub(super) fn new(codex_home: PathBuf) -> Self {
|
||||
Self { codex_home }
|
||||
}
|
||||
|
||||
/// Attempt to read and parse the `auth.json` file in the given `AKODE_HOME` directory.
|
||||
/// Returns the full AuthDotJson structure.
|
||||
pub(super) fn try_read_auth_json(&self, auth_file: &Path) -> std::io::Result<AuthDotJson> {
|
||||
let mut file = File::open(auth_file)?;
|
||||
let mut contents = String::new();
|
||||
file.read_to_string(&mut contents)?;
|
||||
let auth_dot_json: AuthDotJson = serde_json::from_str(&contents).map_err(|err| {
|
||||
storage_error::with_context("failed to deserialize CLI auth from file", err)
|
||||
})?;
|
||||
|
||||
Ok(auth_dot_json)
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthStorageBackend for FileAuthStorage {
|
||||
fn persistent_home(&self) -> Option<&Path> {
|
||||
Some(&self.codex_home)
|
||||
}
|
||||
|
||||
fn load(&self) -> std::io::Result<Option<AuthDotJson>> {
|
||||
let auth_file = get_auth_file(&self.codex_home);
|
||||
let auth_dot_json = match self.try_read_auth_json(&auth_file) {
|
||||
Ok(auth) => auth,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
Ok(Some(auth_dot_json))
|
||||
}
|
||||
|
||||
fn save(&self, auth_dot_json: &AuthDotJson) -> std::io::Result<()> {
|
||||
let auth_file = storage_file::resolve_auth_file(get_auth_file(&self.codex_home))?;
|
||||
let parent = auth_file
|
||||
.parent()
|
||||
.ok_or_else(|| std::io::Error::other("auth file has no parent"))?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let json_data = serde_json::to_string_pretty(auth_dot_json)?;
|
||||
storage_file::check_replaceable(&auth_file)?;
|
||||
// tempfile creates a private (0600 on Unix) file in the same filesystem.
|
||||
// Readers see the complete old or new document, never a truncated auth.json.
|
||||
let mut replacement = storage_file::replacement(&auth_file)?;
|
||||
replacement.write_all(json_data.as_bytes())?;
|
||||
replacement.as_file().sync_all()?;
|
||||
// Clear Windows' temporary attribute, then restore cleanup protection.
|
||||
// std::fs::rename can replace a file held open by a reader on Windows;
|
||||
// tempfile::persist only uses MoveFileExW, which rejects that case.
|
||||
let (_file, path) = replacement.keep().map_err(|error| error.error)?;
|
||||
let mut path = tempfile::TempPath::try_from_path(path)?;
|
||||
std::fs::rename(&path, auth_file)?;
|
||||
path.disable_cleanup(/*disable_cleanup*/ true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete(&self) -> std::io::Result<bool> {
|
||||
delete_file_if_exists(&self.codex_home)
|
||||
}
|
||||
}
|
||||
|
||||
static AKODE_AUTH_SECRET_NAME: Lazy<SecretName> =
|
||||
Lazy::new(|| match SecretName::new("AKODE_AUTH") {
|
||||
Ok(name) => name,
|
||||
Err(err) => unreachable!("AKODE_AUTH should be a valid secret name: {err}"),
|
||||
});
|
||||
const KEYRING_SERVICE: &str = "aKode Auth";
|
||||
|
||||
// turns codex_home path into a stable, short key string
|
||||
fn compute_store_key(codex_home: &Path) -> std::io::Result<String> {
|
||||
let canonical = codex_home
|
||||
.canonicalize()
|
||||
.unwrap_or_else(|_| codex_home.to_path_buf());
|
||||
let path_str = canonical.to_string_lossy();
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(path_str.as_bytes());
|
||||
let digest = hasher.finalize();
|
||||
let hex = format!("{digest:x}");
|
||||
let truncated = hex.get(..16).unwrap_or(&hex);
|
||||
Ok(format!("cli|{truncated}"))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct DirectKeyringAuthStorage {
|
||||
codex_home: PathBuf,
|
||||
mode: AuthCredentialsStoreMode,
|
||||
keyring_store: Arc<dyn KeyringStore>,
|
||||
}
|
||||
|
||||
impl DirectKeyringAuthStorage {
|
||||
fn new(
|
||||
codex_home: PathBuf,
|
||||
keyring_store: Arc<dyn KeyringStore>,
|
||||
mode: AuthCredentialsStoreMode,
|
||||
) -> Self {
|
||||
Self {
|
||||
codex_home,
|
||||
keyring_store,
|
||||
mode,
|
||||
}
|
||||
}
|
||||
|
||||
fn load_from_keyring(&self, key: &str) -> std::io::Result<Option<AuthDotJson>> {
|
||||
match self
|
||||
.keyring_store
|
||||
.load(KEYRING_SERVICE, key)
|
||||
.map_err(std::io::Error::from)
|
||||
.map_err(|error| {
|
||||
storage_error::with_context("failed to load CLI auth from keyring", error)
|
||||
})? {
|
||||
Some(serialized) => serde_json::from_str(&serialized).map(Some).map_err(|err| {
|
||||
storage_error::with_context("failed to deserialize CLI auth from keyring", err)
|
||||
}),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn save_to_keyring(&self, key: &str, value: &str) -> std::io::Result<()> {
|
||||
self.keyring_store
|
||||
.save(KEYRING_SERVICE, key, value)
|
||||
.map_err(std::io::Error::from)
|
||||
.map_err(|error| {
|
||||
let error =
|
||||
storage_error::with_context("failed to write CLI auth to keyring", error);
|
||||
if self.mode == AuthCredentialsStoreMode::Keyring {
|
||||
warn!("{error}");
|
||||
}
|
||||
error
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthStorageBackend for DirectKeyringAuthStorage {
|
||||
fn persistent_home(&self) -> Option<&Path> {
|
||||
Some(&self.codex_home)
|
||||
}
|
||||
|
||||
fn load(&self) -> std::io::Result<Option<AuthDotJson>> {
|
||||
let key = compute_store_key(&self.codex_home)?;
|
||||
self.load_from_keyring(&key)
|
||||
}
|
||||
|
||||
fn save(&self, auth: &AuthDotJson) -> std::io::Result<()> {
|
||||
let key = compute_store_key(&self.codex_home)?;
|
||||
// Simpler error mapping per style: prefer method reference over closure
|
||||
let serialized = serde_json::to_string(auth).map_err(std::io::Error::other)?;
|
||||
self.save_to_keyring(&key, &serialized)?;
|
||||
let mut telemetry = storage_telemetry::telemetry(
|
||||
self.mode,
|
||||
AuthKeyringBackendKind::Direct,
|
||||
Operation::Cleanup,
|
||||
);
|
||||
let result = delete_file_if_exists(&self.codex_home);
|
||||
telemetry.record_delete_attempt(Store::File, &result);
|
||||
if let Err(err) = &result {
|
||||
warn!("failed to remove CLI auth fallback file: {err}");
|
||||
}
|
||||
drop(telemetry);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete(&self) -> std::io::Result<bool> {
|
||||
let key = compute_store_key(&self.codex_home)?;
|
||||
let keyring_removed = self
|
||||
.keyring_store
|
||||
.delete(KEYRING_SERVICE, &key)
|
||||
.map_err(std::io::Error::from)
|
||||
.map_err(|error| {
|
||||
storage_error::with_context("failed to delete auth from keyring", error)
|
||||
})?;
|
||||
let file_removed = delete_file_if_exists(&self.codex_home)?;
|
||||
Ok(keyring_removed || file_removed)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct SecretsKeyringAuthStorage {
|
||||
codex_home: PathBuf,
|
||||
mode: AuthCredentialsStoreMode,
|
||||
direct_storage: DirectKeyringAuthStorage,
|
||||
secrets_manager: SecretsManager,
|
||||
}
|
||||
|
||||
impl Debug for SecretsKeyringAuthStorage {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("SecretsKeyringAuthStorage")
|
||||
.field("codex_home", &self.codex_home)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl SecretsKeyringAuthStorage {
|
||||
fn new(
|
||||
codex_home: PathBuf,
|
||||
keyring_store: Arc<dyn KeyringStore>,
|
||||
mode: AuthCredentialsStoreMode,
|
||||
) -> Self {
|
||||
let direct_storage =
|
||||
DirectKeyringAuthStorage::new(codex_home.clone(), Arc::clone(&keyring_store), mode);
|
||||
let secrets_manager = SecretsManager::new_with_keyring_store_and_namespace(
|
||||
codex_home.clone(),
|
||||
SecretsBackendKind::Local,
|
||||
keyring_store,
|
||||
LocalSecretsNamespace::CodexAuth,
|
||||
);
|
||||
Self {
|
||||
codex_home,
|
||||
mode,
|
||||
direct_storage,
|
||||
secrets_manager,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthStorageBackend for SecretsKeyringAuthStorage {
|
||||
fn persistent_home(&self) -> Option<&Path> {
|
||||
Some(&self.codex_home)
|
||||
}
|
||||
|
||||
fn load(&self) -> std::io::Result<Option<AuthDotJson>> {
|
||||
match self
|
||||
.secrets_manager
|
||||
.get(&SecretScope::Global, &AKODE_AUTH_SECRET_NAME)
|
||||
.map_err(|error| {
|
||||
storage_error::with_context(
|
||||
"failed to load CLI auth from encrypted auth storage",
|
||||
error,
|
||||
)
|
||||
})? {
|
||||
Some(serialized) => serde_json::from_str(&serialized).map(Some).map_err(|err| {
|
||||
storage_error::with_context(
|
||||
"failed to deserialize CLI auth from encrypted auth storage",
|
||||
err,
|
||||
)
|
||||
}),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn save(&self, auth: &AuthDotJson) -> std::io::Result<()> {
|
||||
let serialized = serde_json::to_string(auth).map_err(std::io::Error::other)?;
|
||||
self.secrets_manager
|
||||
.set(&SecretScope::Global, &AKODE_AUTH_SECRET_NAME, &serialized)
|
||||
.map_err(|error| {
|
||||
let error = storage_error::with_context(
|
||||
"failed to write CLI auth to encrypted auth storage",
|
||||
error,
|
||||
);
|
||||
if self.mode == AuthCredentialsStoreMode::Keyring {
|
||||
warn!("{error}");
|
||||
}
|
||||
error
|
||||
})?;
|
||||
let mut telemetry = storage_telemetry::telemetry(
|
||||
self.mode,
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
Operation::Cleanup,
|
||||
);
|
||||
let result = delete_file_if_exists(&self.codex_home);
|
||||
telemetry.record_delete_attempt(Store::File, &result);
|
||||
if let Err(err) = &result {
|
||||
warn!("failed to remove CLI auth fallback file: {err}");
|
||||
}
|
||||
drop(telemetry);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete(&self) -> std::io::Result<bool> {
|
||||
let keyring_removed = self
|
||||
.secrets_manager
|
||||
.delete(&SecretScope::Global, &AKODE_AUTH_SECRET_NAME)
|
||||
.map_err(|error| {
|
||||
storage_error::with_context(
|
||||
"failed to delete auth from encrypted auth storage",
|
||||
error,
|
||||
)
|
||||
})?;
|
||||
let file_removed = delete_file_if_exists(&self.codex_home)?;
|
||||
let direct_removed = self.direct_storage.delete()?;
|
||||
Ok(keyring_removed || file_removed || direct_removed)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct AutoAuthStorage {
|
||||
keyring_storage: Arc<dyn AuthStorageBackend>,
|
||||
file_storage: Arc<FileAuthStorage>,
|
||||
keyring_backend_kind: AuthKeyringBackendKind,
|
||||
}
|
||||
|
||||
impl AutoAuthStorage {
|
||||
fn new(
|
||||
codex_home: PathBuf,
|
||||
keyring_store: Arc<dyn KeyringStore>,
|
||||
keyring_backend_kind: AuthKeyringBackendKind,
|
||||
) -> Self {
|
||||
Self {
|
||||
keyring_storage: create_keyring_auth_storage(
|
||||
codex_home.clone(),
|
||||
keyring_store,
|
||||
keyring_backend_kind,
|
||||
AuthCredentialsStoreMode::Auto,
|
||||
),
|
||||
file_storage: Arc::new(FileAuthStorage::new(codex_home)),
|
||||
keyring_backend_kind,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthStorageBackend for AutoAuthStorage {
|
||||
fn persistent_home(&self) -> Option<&Path> {
|
||||
Some(&self.file_storage.codex_home)
|
||||
}
|
||||
|
||||
fn load(&self) -> std::io::Result<Option<AuthDotJson>> {
|
||||
let mut telemetry = storage_telemetry::telemetry(
|
||||
AuthCredentialsStoreMode::Auto,
|
||||
self.keyring_backend_kind,
|
||||
Operation::Load,
|
||||
);
|
||||
let result = self.keyring_storage.load();
|
||||
telemetry.record_load_attempt(
|
||||
storage_telemetry::keyring_store(self.keyring_backend_kind),
|
||||
&result,
|
||||
);
|
||||
match result {
|
||||
Ok(Some(auth)) => Ok(Some(auth)),
|
||||
Ok(None) => {
|
||||
let result = self.file_storage.load();
|
||||
telemetry.record_load_attempt(Store::File, &result);
|
||||
result
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("failed to load CLI auth from keyring, falling back to file storage: {err}");
|
||||
telemetry.record_secure_error(&err);
|
||||
let result = self.file_storage.load();
|
||||
telemetry.record_load_attempt(Store::File, &result);
|
||||
result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn save(&self, auth: &AuthDotJson) -> std::io::Result<()> {
|
||||
let mut telemetry = storage_telemetry::telemetry(
|
||||
AuthCredentialsStoreMode::Auto,
|
||||
self.keyring_backend_kind,
|
||||
Operation::Save,
|
||||
);
|
||||
let result = self.keyring_storage.save(auth);
|
||||
telemetry.record_save_attempt(
|
||||
storage_telemetry::keyring_store(self.keyring_backend_kind),
|
||||
&result,
|
||||
);
|
||||
match result {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) => {
|
||||
warn!("failed to save auth to keyring, falling back to file storage: {err}");
|
||||
telemetry.record_secure_error(&err);
|
||||
let result = self.file_storage.save(auth);
|
||||
telemetry.record_save_attempt(Store::File, &result);
|
||||
result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn delete(&self) -> std::io::Result<bool> {
|
||||
// Keyring storage will delete from disk as well
|
||||
let mut telemetry = storage_telemetry::telemetry(
|
||||
AuthCredentialsStoreMode::Auto,
|
||||
self.keyring_backend_kind,
|
||||
Operation::Delete,
|
||||
);
|
||||
let result = self.keyring_storage.delete();
|
||||
telemetry.record_delete_attempt(Store::Multiple, &result);
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
// A global in-memory store for mapping codex_home -> AuthDotJson.
|
||||
static EPHEMERAL_AUTH_STORE: Lazy<Mutex<HashMap<String, AuthDotJson>>> =
|
||||
Lazy::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct EphemeralAuthStorage {
|
||||
codex_home: PathBuf,
|
||||
}
|
||||
|
||||
impl EphemeralAuthStorage {
|
||||
fn new(codex_home: PathBuf) -> Self {
|
||||
Self { codex_home }
|
||||
}
|
||||
|
||||
fn with_store<F, T>(&self, action: F) -> std::io::Result<T>
|
||||
where
|
||||
F: FnOnce(&mut HashMap<String, AuthDotJson>, String) -> std::io::Result<T>,
|
||||
{
|
||||
let key = compute_store_key(&self.codex_home)?;
|
||||
let mut store = EPHEMERAL_AUTH_STORE
|
||||
.lock()
|
||||
.map_err(|_| std::io::Error::other("failed to lock ephemeral auth storage"))?;
|
||||
action(&mut store, key)
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthStorageBackend for EphemeralAuthStorage {
|
||||
fn load(&self) -> std::io::Result<Option<AuthDotJson>> {
|
||||
self.with_store(|store, key| Ok(store.get(&key).cloned()))
|
||||
}
|
||||
|
||||
fn save(&self, auth: &AuthDotJson) -> std::io::Result<()> {
|
||||
self.with_store(|store, key| {
|
||||
store.insert(key, auth.clone());
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn delete(&self) -> std::io::Result<bool> {
|
||||
self.with_store(|store, key| Ok(store.remove(&key).is_some()))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn create_auth_storage(
|
||||
codex_home: PathBuf,
|
||||
mode: AuthCredentialsStoreMode,
|
||||
keyring_backend_kind: AuthKeyringBackendKind,
|
||||
) -> Arc<dyn AuthStorageBackend> {
|
||||
let keyring_store: Arc<dyn KeyringStore> = Arc::new(DefaultKeyringStore);
|
||||
create_auth_storage_with_store(codex_home, mode, keyring_store, keyring_backend_kind)
|
||||
}
|
||||
|
||||
fn create_auth_storage_with_store(
|
||||
codex_home: PathBuf,
|
||||
mode: AuthCredentialsStoreMode,
|
||||
keyring_store: Arc<dyn KeyringStore>,
|
||||
keyring_backend_kind: AuthKeyringBackendKind,
|
||||
) -> Arc<dyn AuthStorageBackend> {
|
||||
let commit_home = codex_home.clone();
|
||||
let storage: Arc<dyn AuthStorageBackend> = match mode {
|
||||
AuthCredentialsStoreMode::File => Arc::new(FileAuthStorage::new(codex_home)),
|
||||
AuthCredentialsStoreMode::Keyring => {
|
||||
create_keyring_auth_storage(codex_home, keyring_store, keyring_backend_kind, mode)
|
||||
}
|
||||
AuthCredentialsStoreMode::Auto => Arc::new(AutoAuthStorage::new(
|
||||
codex_home,
|
||||
keyring_store,
|
||||
keyring_backend_kind,
|
||||
)),
|
||||
AuthCredentialsStoreMode::Ephemeral => Arc::new(EphemeralAuthStorage::new(codex_home)),
|
||||
};
|
||||
storage_commit::wrap(
|
||||
storage_telemetry::observe(storage, mode, keyring_backend_kind),
|
||||
commit_home,
|
||||
mode,
|
||||
)
|
||||
}
|
||||
|
||||
fn create_keyring_auth_storage(
|
||||
codex_home: PathBuf,
|
||||
keyring_store: Arc<dyn KeyringStore>,
|
||||
keyring_backend_kind: AuthKeyringBackendKind,
|
||||
mode: AuthCredentialsStoreMode,
|
||||
) -> Arc<dyn AuthStorageBackend> {
|
||||
match keyring_backend_kind {
|
||||
AuthKeyringBackendKind::Direct => Arc::new(DirectKeyringAuthStorage::new(
|
||||
codex_home,
|
||||
keyring_store,
|
||||
mode,
|
||||
)),
|
||||
AuthKeyringBackendKind::Secrets => Arc::new(SecretsKeyringAuthStorage::new(
|
||||
codex_home,
|
||||
keyring_store,
|
||||
mode,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "storage_tests.rs"]
|
||||
mod tests;
|
||||
98
akode-rs/login/src/auth/storage_commit.rs
Normal file
98
akode-rs/login/src/auth/storage_commit.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
//! Serializes cooperating processes' credential commits, including saves and deletes.
|
||||
//! The stable sidecar is never renamed or removed; network requests never hold it.
|
||||
|
||||
use super::*;
|
||||
use std::fs::OpenOptions;
|
||||
use std::fs::TryLockError;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
pub(super) fn wrap(
|
||||
inner: Arc<dyn AuthStorageBackend>,
|
||||
home: PathBuf,
|
||||
mode: AuthCredentialsStoreMode,
|
||||
) -> Arc<dyn AuthStorageBackend> {
|
||||
if mode == AuthCredentialsStoreMode::Ephemeral {
|
||||
return inner;
|
||||
}
|
||||
Arc::new(CommittedStorage { inner, home, mode })
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CommittedStorage {
|
||||
inner: Arc<dyn AuthStorageBackend>,
|
||||
home: PathBuf,
|
||||
mode: AuthCredentialsStoreMode,
|
||||
}
|
||||
|
||||
impl CommittedStorage {
|
||||
fn lock(&self) -> std::io::Result<File> {
|
||||
let auth_file = get_auth_file(&self.home);
|
||||
// Keyring commits can unlink an intermediate symlink used by another
|
||||
// home, so resolvable chains must share the target's commit lock.
|
||||
let path = match storage_file::resolve_auth_file(auth_file.clone()) {
|
||||
Ok(path) => path,
|
||||
// Unresolvable fallback links can still be removed by keyring commits.
|
||||
Err(_) if self.mode == AuthCredentialsStoreMode::Keyring => auth_file,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
.with_extension("json.lock");
|
||||
std::fs::create_dir_all(
|
||||
path.parent()
|
||||
.ok_or_else(|| std::io::Error::other("credential lock has no parent"))?,
|
||||
)?;
|
||||
let mut options = OpenOptions::new();
|
||||
options.read(true).write(true).create(true).truncate(false);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let file = options.open(path)?;
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
match file.try_lock() {
|
||||
Ok(()) => return Ok(file),
|
||||
Err(TryLockError::WouldBlock) if Instant::now() < deadline => {
|
||||
std::thread::sleep(Duration::from_millis(10))
|
||||
}
|
||||
Err(TryLockError::WouldBlock) => {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::TimedOut,
|
||||
"credential commit lock timed out",
|
||||
));
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthStorageBackend for CommittedStorage {
|
||||
fn persistent_home(&self) -> Option<&Path> {
|
||||
self.inner.persistent_home()
|
||||
}
|
||||
|
||||
fn load(&self) -> std::io::Result<Option<AuthDotJson>> {
|
||||
self.inner.load()
|
||||
}
|
||||
fn save(&self, auth: &AuthDotJson) -> std::io::Result<()> {
|
||||
let _guard = self.lock()?;
|
||||
self.inner.save(auth)
|
||||
}
|
||||
fn delete(&self) -> std::io::Result<bool> {
|
||||
// A missing file-store directory contains no credentials to delete.
|
||||
// Linearize this no-op before any concurrent creator, without creating
|
||||
// a directory just to leave a lock behind. Secure stores may still have
|
||||
// credentials even when the directory is absent and must take the lock.
|
||||
if self.mode == AuthCredentialsStoreMode::File && !self.home.try_exists()? {
|
||||
return Ok(false);
|
||||
}
|
||||
let _guard = self.lock()?;
|
||||
self.inner.delete()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "storage_commit_tests.rs"]
|
||||
mod tests;
|
||||
234
akode-rs/login/src/auth/storage_commit_tests.rs
Normal file
234
akode-rs/login/src/auth/storage_commit_tests.rs
Normal file
@@ -0,0 +1,234 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io::BufRead;
|
||||
use std::io::Read;
|
||||
use std::process::Stdio;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn keyring_commits_ignore_unusable_fallback_symlink_targets() -> anyhow::Result<()> {
|
||||
use akode_keyring_store::tests::MockKeyringStore;
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
for kind in [
|
||||
AuthKeyringBackendKind::Direct,
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
] {
|
||||
for target in ["auth.json", "not-a-directory/auth.json"] {
|
||||
let home = tempfile::tempdir()?;
|
||||
std::fs::write(home.path().join("not-a-directory"), "")?;
|
||||
let auth_file = get_auth_file(home.path());
|
||||
let storage = create_auth_storage_with_store(
|
||||
home.path().to_path_buf(),
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
Arc::new(MockKeyringStore::default()),
|
||||
kind,
|
||||
);
|
||||
let first = serde_json::from_value(serde_json::json!({"OPENAI_API_KEY": "first"}))?;
|
||||
let second = serde_json::from_value(serde_json::json!({"OPENAI_API_KEY": "second"}))?;
|
||||
let _guard = storage.lock_for_write()?;
|
||||
|
||||
symlink(target, &auth_file)?;
|
||||
storage.save(&first)?;
|
||||
assert_eq!(storage.load()?, Some(first.clone()));
|
||||
assert_eq!(
|
||||
std::fs::symlink_metadata(&auth_file).unwrap_err().kind(),
|
||||
std::io::ErrorKind::NotFound
|
||||
);
|
||||
|
||||
symlink(target, &auth_file)?;
|
||||
storage.save(&second)?;
|
||||
assert_eq!(storage.load()?, Some(second));
|
||||
|
||||
symlink(target, &auth_file)?;
|
||||
assert!(storage.delete()?);
|
||||
assert_eq!(storage.load()?, None);
|
||||
assert_eq!(
|
||||
std::fs::symlink_metadata(&auth_file).unwrap_err().kind(),
|
||||
std::io::ErrorKind::NotFound
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_absent_file_store_does_not_create_home() -> anyhow::Result<()> {
|
||||
let root = tempfile::tempdir()?;
|
||||
let home = root.path().join("missing");
|
||||
let storage = create_auth_storage(
|
||||
home.clone(),
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
);
|
||||
assert!(!storage.delete()?);
|
||||
assert!(!home.try_exists()?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_lock_coordinates_with_existing_auth_lock() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let storage = create_auth_storage(
|
||||
home.path().to_path_buf(),
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
);
|
||||
let _guard = storage.lock_for_write()?;
|
||||
let other_writer = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(home.path().join("auth.lock"))?;
|
||||
assert!(matches!(
|
||||
other_writer.try_lock(),
|
||||
Err(TryLockError::WouldBlock)
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commits_respect_another_process_lock() -> anyhow::Result<()> {
|
||||
const CHILD_HOME: &str = "AKODE_AUTH_COMMIT_TEST_HOME";
|
||||
if let Some(home) = std::env::var_os(CHILD_HOME) {
|
||||
let home = PathBuf::from(home);
|
||||
let storage = CommittedStorage {
|
||||
inner: Arc::new(FileAuthStorage::new(home.clone())),
|
||||
home,
|
||||
mode: AuthCredentialsStoreMode::File,
|
||||
};
|
||||
let _guard = storage.lock()?;
|
||||
println!("LOCK_HELD");
|
||||
let mut release = String::new();
|
||||
std::io::stdin().read_to_string(&mut release)?;
|
||||
return Ok(());
|
||||
}
|
||||
let home = tempfile::tempdir()?;
|
||||
let storage = create_auth_storage(
|
||||
home.path().to_path_buf(),
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
);
|
||||
let old: AuthDotJson = serde_json::from_value(serde_json::json!({"OPENAI_API_KEY":"old"}))?;
|
||||
let new: AuthDotJson = serde_json::from_value(serde_json::json!({"OPENAI_API_KEY":"new"}))?;
|
||||
storage.save(&old)?;
|
||||
let mut child = akode_utils_process::background_command(std::env::current_exe()?)
|
||||
.args([
|
||||
"--exact",
|
||||
"auth::storage::storage_commit::tests::commits_respect_another_process_lock",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD_HOME, home.path())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()?;
|
||||
let input = child.stdin.take();
|
||||
let mut output = std::io::BufReader::new(child.stdout.take().unwrap());
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
anyhow::ensure!(
|
||||
output.read_line(&mut line)? > 0,
|
||||
"lock holder exited before acquiring the lock"
|
||||
);
|
||||
if line.contains("LOCK_HELD") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let result = storage.save(&new);
|
||||
drop(input);
|
||||
let status = child.wait()?;
|
||||
assert!(status.success());
|
||||
assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::TimedOut);
|
||||
assert_eq!(storage.load()?, Some(old.clone()));
|
||||
storage.save(&new)?;
|
||||
assert_eq!(storage.load()?, Some(new));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn keyring_logout_coordinates_with_writer_through_chained_symlinks() -> anyhow::Result<()> {
|
||||
use akode_keyring_store::tests::MockKeyringStore;
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
const CHILD_HOME: &str = "AKODE_AUTH_CHAINED_WRITER_TEST_HOME";
|
||||
let old: AuthDotJson = serde_json::from_value(serde_json::json!({"OPENAI_API_KEY": "old"}))?;
|
||||
let new: AuthDotJson = serde_json::from_value(serde_json::json!({"OPENAI_API_KEY": "new"}))?;
|
||||
if let Some(home) = std::env::var_os(CHILD_HOME) {
|
||||
let home = PathBuf::from(home);
|
||||
let storage = CommittedStorage {
|
||||
inner: Arc::new(FileAuthStorage::new(home.clone())),
|
||||
home,
|
||||
mode: AuthCredentialsStoreMode::File,
|
||||
};
|
||||
let _write_guard = storage.lock_for_write()?;
|
||||
let _commit_guard = storage.lock()?;
|
||||
// Pause between reading and saving under the commit lock.
|
||||
assert_eq!(storage.inner.load()?, Some(old));
|
||||
println!("REFRESH_VALIDATED");
|
||||
let mut release = String::new();
|
||||
std::io::stdin().read_to_string(&mut release)?;
|
||||
storage.inner.save(&new)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for kind in [
|
||||
AuthKeyringBackendKind::Direct,
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
] {
|
||||
let shared = tempfile::tempdir()?;
|
||||
let keyring_home = tempfile::tempdir()?;
|
||||
let writer_home = tempfile::tempdir()?;
|
||||
let shared_storage = FileAuthStorage::new(shared.path().to_path_buf());
|
||||
shared_storage.save(&old)?;
|
||||
let middle = get_auth_file(keyring_home.path());
|
||||
symlink(get_auth_file(shared.path()), &middle)?;
|
||||
symlink(&middle, get_auth_file(writer_home.path()))?;
|
||||
let storage = create_auth_storage_with_store(
|
||||
keyring_home.path().to_path_buf(),
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
Arc::new(MockKeyringStore::default()),
|
||||
kind,
|
||||
);
|
||||
let _guard = storage.lock_for_write()?;
|
||||
let mut child = akode_utils_process::background_command(std::env::current_exe()?)
|
||||
.args([
|
||||
"--exact",
|
||||
"auth::storage::storage_commit::tests::keyring_logout_coordinates_with_writer_through_chained_symlinks",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD_HOME, writer_home.path())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()?;
|
||||
let input = child.stdin.take();
|
||||
let mut output = std::io::BufReader::new(child.stdout.take().unwrap());
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
anyhow::ensure!(
|
||||
output.read_line(&mut line)? > 0,
|
||||
"writer exited before reading credentials"
|
||||
);
|
||||
if line.contains("REFRESH_VALIDATED") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let result = storage.delete();
|
||||
drop(input);
|
||||
let status = child.wait()?;
|
||||
assert!(status.success());
|
||||
assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::TimedOut);
|
||||
assert!(std::fs::symlink_metadata(&middle)?.file_type().is_symlink());
|
||||
assert_eq!(shared_storage.load()?, Some(new.clone()));
|
||||
|
||||
// Logout can unlink the middle symlink once the writer has committed.
|
||||
assert!(storage.delete()?);
|
||||
assert_eq!(
|
||||
std::fs::symlink_metadata(&middle).unwrap_err().kind(),
|
||||
std::io::ErrorKind::NotFound
|
||||
);
|
||||
assert_eq!(shared_storage.load()?, Some(new.clone()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
49
akode-rs/login/src/auth/storage_error.rs
Normal file
49
akode-rs/login/src/auth/storage_error.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
//! Removes credential JSON data errors while preserving native storage diagnostics and typed causes.
|
||||
|
||||
#[derive(thiserror::Error)]
|
||||
struct CredentialStorageError {
|
||||
context: &'static str,
|
||||
#[source]
|
||||
source: anyhow::Error,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CredentialStorageError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}: {:#}", self.context, self.source)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for CredentialStorageError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
std::fmt::Display::fmt(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn with_context(
|
||||
context: &'static str,
|
||||
source: impl Into<anyhow::Error>,
|
||||
) -> std::io::Error {
|
||||
let mut source = source.into();
|
||||
let mut cause: Option<&(dyn std::error::Error + 'static)> = Some(source.as_ref());
|
||||
while let Some(error) = cause {
|
||||
if let Some(error) = error.downcast_ref::<serde_json::Error>()
|
||||
&& error.is_data()
|
||||
{
|
||||
// Discard the entire chain: serde errors and their context may contain credentials.
|
||||
source = anyhow::anyhow!(
|
||||
"invalid credential JSON ({:?} at line {} column {})",
|
||||
error.classify(),
|
||||
error.line(),
|
||||
error.column(),
|
||||
);
|
||||
break;
|
||||
}
|
||||
cause = if let Some(error) = error.downcast_ref::<std::io::Error>() {
|
||||
// io::Error::source() skips its contained error.
|
||||
error.get_ref().map(|error| error as &dyn std::error::Error)
|
||||
} else {
|
||||
error.source()
|
||||
};
|
||||
}
|
||||
std::io::Error::other(CredentialStorageError { context, source })
|
||||
}
|
||||
151
akode-rs/login/src/auth/storage_error_tests.rs
Normal file
151
akode-rs/login/src/auth/storage_error_tests.rs
Normal file
@@ -0,0 +1,151 @@
|
||||
//! Checks that storage diagnostics preserve useful causes without exposing credential values.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn secure_storage_errors_display_the_underlying_cause() -> anyhow::Result<()> {
|
||||
for kind in [
|
||||
AuthKeyringBackendKind::Direct,
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
] {
|
||||
for (error_kind, cause) in [
|
||||
(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
"permission denied by keyring",
|
||||
),
|
||||
(std::io::ErrorKind::NotConnected, "keyring unavailable"),
|
||||
] {
|
||||
let home = tempdir()?;
|
||||
let keyring = MockKeyringStore::default();
|
||||
let storage = create_auth_storage_with_store(
|
||||
home.path().to_path_buf(),
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
Arc::new(keyring.clone()),
|
||||
kind,
|
||||
);
|
||||
let auth = auth_with_prefix("private credential value");
|
||||
storage.save(&auth)?;
|
||||
let key = match kind {
|
||||
AuthKeyringBackendKind::Direct => compute_store_key(home.path())?,
|
||||
AuthKeyringBackendKind::Secrets => {
|
||||
compute_keyring_account(home.path(), LocalSecretsNamespace::CodexAuth)
|
||||
}
|
||||
};
|
||||
for operation in [Operation::Load, Operation::Save, Operation::Delete] {
|
||||
keyring.set_error(
|
||||
&key,
|
||||
KeyringError::PlatformFailure(Box::new(std::io::Error::new(error_kind, cause))),
|
||||
);
|
||||
let error = match operation {
|
||||
Operation::Load => storage.load().unwrap_err(),
|
||||
Operation::Save => storage.save(&auth).unwrap_err(),
|
||||
Operation::Delete => storage.delete().unwrap_err(),
|
||||
Operation::Cleanup | Operation::RefreshPersist => unreachable!(),
|
||||
};
|
||||
let message = error.to_string();
|
||||
assert!(message.starts_with("failed to "), "{message}");
|
||||
assert!(message.contains(cause), "{message}");
|
||||
assert!(!message.contains("private credential value"));
|
||||
let debug = format!("{error:?}");
|
||||
assert!(debug.contains(cause), "{debug}");
|
||||
assert!(!debug.contains("private credential value"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_syntax_and_eof_errors_preserve_diagnostics() {
|
||||
for (input, category) in [
|
||||
(
|
||||
r#"{"OPENAI_API_KEY" "private-credential-value"}"#,
|
||||
serde_json::error::Category::Syntax,
|
||||
),
|
||||
(
|
||||
r#"{"OPENAI_API_KEY":"private-credential-value""#,
|
||||
serde_json::error::Category::Eof,
|
||||
),
|
||||
] {
|
||||
let source = serde_json::from_str::<AuthDotJson>(input).unwrap_err();
|
||||
assert_eq!(source.classify(), category);
|
||||
let expected = format!("failed to load auth: decrypted auth JSON: {source}");
|
||||
let error = storage_error::with_context(
|
||||
"failed to load auth",
|
||||
anyhow::Error::new(source).context("decrypted auth JSON"),
|
||||
);
|
||||
let inner = error.get_ref().unwrap();
|
||||
assert_eq!(
|
||||
(error.to_string(), format!("{inner:?}")),
|
||||
(expected.clone(), expected)
|
||||
);
|
||||
assert!(!format!("{error:?}").contains("private-credential-value"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_data_errors_redact_credential_values() {
|
||||
enum Wrapper {
|
||||
Direct,
|
||||
AnyhowContext,
|
||||
Io,
|
||||
Nested,
|
||||
}
|
||||
|
||||
for wrapper in [
|
||||
Wrapper::Direct,
|
||||
Wrapper::AnyhowContext,
|
||||
Wrapper::Io,
|
||||
Wrapper::Nested,
|
||||
] {
|
||||
let source =
|
||||
serde_json::from_str::<AuthDotJson>(r#"{"OPENAI_API_KEY":424242424242}"#).unwrap_err();
|
||||
// serde_json echoes the rejected value; the storage error must not.
|
||||
assert!(source.to_string().contains("424242424242"));
|
||||
let expected = format!(
|
||||
"failed to load auth: invalid credential JSON (Data at line {} column {})",
|
||||
source.line(),
|
||||
source.column(),
|
||||
);
|
||||
let source = match wrapper {
|
||||
Wrapper::Direct => anyhow::Error::new(source),
|
||||
Wrapper::AnyhowContext => anyhow::Error::new(source).context("decrypted auth JSON"),
|
||||
Wrapper::Io => anyhow::Error::new(std::io::Error::other(source)),
|
||||
Wrapper::Nested => anyhow::Error::new(std::io::Error::other(
|
||||
anyhow::Error::new(std::io::Error::other(source))
|
||||
.context("private-credential-value"),
|
||||
))
|
||||
.context("decrypted auth JSON"),
|
||||
};
|
||||
let error = storage_error::with_context("failed to load auth", source);
|
||||
let inner = error.get_ref().unwrap();
|
||||
assert_eq!(
|
||||
(error.to_string(), format!("{inner:?}")),
|
||||
(expected.clone(), expected)
|
||||
);
|
||||
assert!(
|
||||
!format!("{error:?}").contains("private-credential-value")
|
||||
&& !format!("{error:?}").contains("424242424242")
|
||||
);
|
||||
|
||||
let error = anyhow::Error::new(error).context("credential storage failed");
|
||||
for formatted in [format!("{error:#}"), format!("{error:?}")] {
|
||||
assert!(
|
||||
!formatted.contains("private-credential-value")
|
||||
&& !formatted.contains("424242424242"),
|
||||
"{formatted}"
|
||||
);
|
||||
}
|
||||
for cause in error.chain() {
|
||||
assert!(cause.downcast_ref::<serde_json::Error>().is_none());
|
||||
for formatted in [cause.to_string(), format!("{cause:?}")] {
|
||||
assert!(
|
||||
!formatted.contains("private-credential-value")
|
||||
&& !formatted.contains("424242424242"),
|
||||
"{formatted}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
73
akode-rs/login/src/auth/storage_file.rs
Normal file
73
akode-rs/login/src/auth/storage_file.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
//! Atomic credential-file replacement without broadening existing file permissions.
|
||||
//! Symlinks retain their target; hard links and read-only files fail rather than split identity.
|
||||
|
||||
#[cfg(not(windows))]
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(super) fn resolve_auth_file(mut path: PathBuf) -> io::Result<PathBuf> {
|
||||
for _ in 0..40 {
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Ok(metadata) if metadata.file_type().is_symlink() => {
|
||||
let target = std::fs::read_link(&path)?;
|
||||
path = if target.is_absolute() {
|
||||
target
|
||||
} else {
|
||||
path.parent()
|
||||
.ok_or_else(|| io::Error::other("credential link has no parent"))?
|
||||
.join(target)
|
||||
};
|
||||
}
|
||||
Ok(_) => return Ok(path),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(path),
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"too many credential symlinks",
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn check_replaceable(path: &Path) -> io::Result<()> {
|
||||
let metadata = match std::fs::metadata(path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if metadata.permissions().readonly() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"credential file is read-only",
|
||||
));
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
if metadata.nlink() > 1 && metadata.is_file() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"atomic credential replacement does not support hard-linked files",
|
||||
));
|
||||
}
|
||||
}
|
||||
// Check the destination's write permission, not only its parent directory's.
|
||||
std::fs::OpenOptions::new().write(true).open(path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub(super) fn replacement(path: &Path) -> io::Result<tempfile::NamedTempFile<File>> {
|
||||
tempfile::Builder::new().prefix(".auth-").tempfile_in(
|
||||
path.parent()
|
||||
.ok_or_else(|| io::Error::other("credential file has no parent"))?,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[path = "storage_file_windows.rs"]
|
||||
mod windows;
|
||||
#[cfg(windows)]
|
||||
pub(super) use windows::replacement;
|
||||
128
akode-rs/login/src/auth/storage_file_windows.rs
Normal file
128
akode-rs/login/src/auth/storage_file_windows.rs
Normal file
@@ -0,0 +1,128 @@
|
||||
//! Creates replacement files with the destination DACL before any secret is written.
|
||||
//! Protect the captured DACL from broader parent inheritance during creation.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::fs::File;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::path::Path;
|
||||
use std::ptr;
|
||||
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
|
||||
use windows_sys::Win32::Foundation::GENERIC_READ;
|
||||
use windows_sys::Win32::Foundation::GENERIC_WRITE;
|
||||
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
|
||||
use windows_sys::Win32::Foundation::LocalFree;
|
||||
use windows_sys::Win32::Security::Authorization::GetSecurityInfo;
|
||||
use windows_sys::Win32::Security::Authorization::SE_FILE_OBJECT;
|
||||
use windows_sys::Win32::Security::DACL_SECURITY_INFORMATION;
|
||||
use windows_sys::Win32::Security::SE_DACL_PROTECTED;
|
||||
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
|
||||
use windows_sys::Win32::Security::SetSecurityDescriptorControl;
|
||||
use windows_sys::Win32::Storage::FileSystem::CREATE_NEW;
|
||||
use windows_sys::Win32::Storage::FileSystem::CreateFileW;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_DELETE;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetFileInformationByHandle;
|
||||
use windows_sys::Win32::Storage::FileSystem::READ_CONTROL;
|
||||
|
||||
struct Descriptor(*mut c_void);
|
||||
|
||||
impl Drop for Descriptor {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: GetSecurityInfo allocates this descriptor with LocalAlloc.
|
||||
unsafe {
|
||||
LocalFree(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::auth::storage) fn replacement(
|
||||
path: &Path,
|
||||
) -> io::Result<tempfile::NamedTempFile<File>> {
|
||||
let descriptor = match OpenOptions::new().access_mode(READ_CONTROL).open(path) {
|
||||
Ok(file) => {
|
||||
// SAFETY: BY_HANDLE_FILE_INFORMATION is an all-integer output structure.
|
||||
let mut info = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: file is open and info is a valid output structure.
|
||||
if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if info.nNumberOfLinks > 1 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"atomic credential replacement does not support hard-linked files",
|
||||
));
|
||||
}
|
||||
let mut descriptor = ptr::null_mut();
|
||||
// SAFETY: the file handle and output pointer remain valid for this call.
|
||||
let status = unsafe {
|
||||
GetSecurityInfo(
|
||||
file.as_raw_handle(),
|
||||
SE_FILE_OBJECT,
|
||||
DACL_SECURITY_INFORMATION,
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
&mut descriptor,
|
||||
)
|
||||
};
|
||||
if status != ERROR_SUCCESS {
|
||||
return Err(io::Error::from_raw_os_error(status as i32));
|
||||
}
|
||||
let descriptor = Descriptor(descriptor);
|
||||
// SAFETY: this is the owned descriptor returned by GetSecurityInfo.
|
||||
if unsafe {
|
||||
SetSecurityDescriptorControl(descriptor.0, SE_DACL_PROTECTED, SE_DACL_PROTECTED)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Some(descriptor)
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => None,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let parent = std::fs::canonicalize(
|
||||
path.parent()
|
||||
.ok_or_else(|| io::Error::other("credential file has no parent"))?,
|
||||
)?;
|
||||
tempfile::Builder::new()
|
||||
.prefix(".auth-")
|
||||
.make_in(parent, |temporary| {
|
||||
let name: Vec<u16> = temporary.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
let attributes = SECURITY_ATTRIBUTES {
|
||||
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||
lpSecurityDescriptor: descriptor.as_ref().map_or(ptr::null_mut(), |value| value.0),
|
||||
bInheritHandle: 0,
|
||||
};
|
||||
// SAFETY: name is NUL-terminated; the owned descriptor outlives creation.
|
||||
// CREATE_NEW prevents opening an attacker-created temporary path.
|
||||
let handle = unsafe {
|
||||
CreateFileW(
|
||||
name.as_ptr(),
|
||||
GENERIC_READ | GENERIC_WRITE,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
||||
&attributes,
|
||||
CREATE_NEW,
|
||||
FILE_ATTRIBUTE_NORMAL,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if handle == INVALID_HANDLE_VALUE {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
// SAFETY: this is a newly opened handle owned exclusively by this File.
|
||||
Ok(unsafe { File::from_raw_handle(handle) })
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "storage_file_windows_tests.rs"]
|
||||
mod tests;
|
||||
100
akode-rs/login/src/auth/storage_file_windows_tests.rs
Normal file
100
akode-rs/login/src/auth/storage_file_windows_tests.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io::Write;
|
||||
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
|
||||
use windows_sys::Win32::Security::Authorization::SetNamedSecurityInfoW;
|
||||
use windows_sys::Win32::Security::GetSecurityDescriptorDacl;
|
||||
use windows_sys::Win32::Security::PROTECTED_DACL_SECURITY_INFORMATION;
|
||||
|
||||
fn set_dacl(path: &Path, sddl: &str) -> io::Result<()> {
|
||||
let text: Vec<u16> = sddl.encode_utf16().chain(Some(0)).collect();
|
||||
let mut descriptor = ptr::null_mut();
|
||||
// SAFETY: text is NUL-terminated, the result is freed by Descriptor.
|
||||
if unsafe {
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
text.as_ptr(),
|
||||
1,
|
||||
&mut descriptor,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let descriptor = Descriptor(descriptor);
|
||||
let mut present = 0;
|
||||
let mut defaulted = 0;
|
||||
let mut acl = ptr::null_mut();
|
||||
// SAFETY: all output pointers are valid; descriptor owns the returned ACL.
|
||||
if unsafe { GetSecurityDescriptorDacl(descriptor.0, &mut present, &mut acl, &mut defaulted) }
|
||||
== 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
assert_ne!(present, 0);
|
||||
let path: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
// SAFETY: the path and ACL remain valid for this call.
|
||||
let status = unsafe {
|
||||
SetNamedSecurityInfoW(
|
||||
path.as_ptr(),
|
||||
SE_FILE_OBJECT,
|
||||
DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
acl,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if status != ERROR_SUCCESS {
|
||||
return Err(io::Error::from_raw_os_error(status as i32));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn dacl(path: &Path) -> io::Result<Vec<u8>> {
|
||||
let file = OpenOptions::new().access_mode(READ_CONTROL).open(path)?;
|
||||
let mut acl = ptr::null_mut();
|
||||
let mut descriptor = ptr::null_mut();
|
||||
// SAFETY: the file and output pointers are valid.
|
||||
let status = unsafe {
|
||||
GetSecurityInfo(
|
||||
file.as_raw_handle(),
|
||||
SE_FILE_OBJECT,
|
||||
DACL_SECURITY_INFORMATION,
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
&mut acl,
|
||||
ptr::null_mut(),
|
||||
&mut descriptor,
|
||||
)
|
||||
};
|
||||
if status != ERROR_SUCCESS {
|
||||
return Err(io::Error::from_raw_os_error(status as i32));
|
||||
}
|
||||
let _descriptor = Descriptor(descriptor);
|
||||
assert!(!acl.is_null());
|
||||
// SAFETY: the descriptor owns an ACL with AclSize bytes for this scope.
|
||||
Ok(unsafe { std::slice::from_raw_parts(acl.cast::<u8>(), (*acl).AclSize as usize) }.to_vec())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacement_keeps_restricted_dacl_before_secret_is_written() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
// Everyone can read child files by inheritance; the credential explicitly cannot.
|
||||
set_dacl(home.path(), "D:P(A;OICI;FA;;;WD)")?;
|
||||
let path = home.path().join("auth.json");
|
||||
std::fs::write(&path, "old")?;
|
||||
// OWNER RIGHTS grants access only to the owner, not Everyone from the parent.
|
||||
set_dacl(&path, "D:P(A;;FA;;;OW)")?;
|
||||
let expected = dacl(&path)?;
|
||||
let mut temporary = replacement(&path)?;
|
||||
assert_eq!(dacl(temporary.path())?, expected);
|
||||
temporary.write_all(b"fake-secret")?;
|
||||
let (_file, temporary_path) = temporary.keep()?;
|
||||
std::fs::rename(temporary_path, &path)?;
|
||||
assert_eq!(dacl(&path)?, expected);
|
||||
assert_eq!(std::fs::read(&path)?, b"fake-secret");
|
||||
Ok(())
|
||||
}
|
||||
443
akode-rs/login/src/auth/storage_policy_tests.rs
Normal file
443
akode-rs/login/src/auth/storage_policy_tests.rs
Normal file
@@ -0,0 +1,443 @@
|
||||
//! Exercises configured storage policy and its emitted metadata.
|
||||
|
||||
use super::*;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn storage_metrics_distinguish_explicit_file_from_secure_failure_fallback() -> anyhow::Result<()> {
|
||||
if std::env::var_os("AKODE_AUTH_STORAGE_TEST_CHILD").is_none() {
|
||||
let output = std::process::Command::new(std::env::current_exe()?)
|
||||
.args([
|
||||
"--exact",
|
||||
std::thread::current().name().unwrap(),
|
||||
"--nocapture",
|
||||
])
|
||||
.env("AKODE_AUTH_STORAGE_TEST_CHILD", "1")
|
||||
.output()?;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
use std::collections::BTreeMap;
|
||||
let metrics = akode_otel::install_global_metrics(akode_otel::MetricsClient::new(
|
||||
akode_otel::MetricsConfig::in_memory("test", "test", "1", Default::default())
|
||||
.with_runtime_reader(),
|
||||
)?);
|
||||
let mut expected = BTreeMap::new();
|
||||
for kind in [
|
||||
AuthKeyringBackendKind::Direct,
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
] {
|
||||
for (scenario, mode, operation, actual, secure, outcome, reason, error) in [
|
||||
(
|
||||
"success",
|
||||
AuthCredentialsStoreMode::Auto,
|
||||
"save",
|
||||
storage_telemetry::keyring_store(kind).as_ref(),
|
||||
"success",
|
||||
"success",
|
||||
"none",
|
||||
"none",
|
||||
),
|
||||
(
|
||||
"cleanup_failed",
|
||||
AuthCredentialsStoreMode::Auto,
|
||||
"save",
|
||||
storage_telemetry::keyring_store(kind).as_ref(),
|
||||
"success",
|
||||
"success",
|
||||
"none",
|
||||
"none",
|
||||
),
|
||||
(
|
||||
"success",
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
"save",
|
||||
storage_telemetry::keyring_store(kind).as_ref(),
|
||||
"success",
|
||||
"success",
|
||||
"none",
|
||||
"none",
|
||||
),
|
||||
(
|
||||
"cleanup_failed",
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
"save",
|
||||
storage_telemetry::keyring_store(kind).as_ref(),
|
||||
"success",
|
||||
"success",
|
||||
"none",
|
||||
"none",
|
||||
),
|
||||
(
|
||||
"denied",
|
||||
AuthCredentialsStoreMode::Auto,
|
||||
"save",
|
||||
"file",
|
||||
"error",
|
||||
"success",
|
||||
"secure_error",
|
||||
"access_denied",
|
||||
),
|
||||
(
|
||||
"explicit",
|
||||
AuthCredentialsStoreMode::File,
|
||||
"save",
|
||||
"file",
|
||||
"not_attempted",
|
||||
"success",
|
||||
"none",
|
||||
"none",
|
||||
),
|
||||
(
|
||||
"missing",
|
||||
AuthCredentialsStoreMode::Auto,
|
||||
"load",
|
||||
"file",
|
||||
"not_found",
|
||||
"success",
|
||||
"secure_entry_missing",
|
||||
"none",
|
||||
),
|
||||
(
|
||||
"failed_file",
|
||||
AuthCredentialsStoreMode::Auto,
|
||||
"load",
|
||||
"file",
|
||||
"error",
|
||||
"error",
|
||||
"secure_error",
|
||||
"access_denied",
|
||||
),
|
||||
] {
|
||||
let home = tempdir()?;
|
||||
let keyring = MockKeyringStore::default();
|
||||
let key = match kind {
|
||||
AuthKeyringBackendKind::Direct => compute_store_key(home.path())?,
|
||||
AuthKeyringBackendKind::Secrets => {
|
||||
compute_keyring_account(home.path(), LocalSecretsNamespace::CodexAuth)
|
||||
}
|
||||
};
|
||||
let auth = auth_with_prefix("private credential value");
|
||||
if operation == "load" || scenario == "success" {
|
||||
FileAuthStorage::new(home.path().to_path_buf()).save(&auth)?;
|
||||
}
|
||||
if scenario == "cleanup_failed" {
|
||||
std::fs::create_dir(get_auth_file(home.path()))?;
|
||||
}
|
||||
if scenario == "failed_file" {
|
||||
std::fs::write(get_auth_file(home.path()), "invalid private file contents")?;
|
||||
}
|
||||
if error == "access_denied" {
|
||||
keyring.set_error(
|
||||
&key,
|
||||
KeyringError::PlatformFailure(Box::new(std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
"private account path error",
|
||||
))),
|
||||
);
|
||||
// Secrets loads consult the keyring only when an encrypted file exists.
|
||||
if operation == "load" && kind == AuthKeyringBackendKind::Secrets {
|
||||
let manager = SecretsManager::new_with_keyring_store_and_namespace(
|
||||
home.path().to_path_buf(),
|
||||
SecretsBackendKind::Local,
|
||||
Arc::new(MockKeyringStore::default()),
|
||||
LocalSecretsNamespace::CodexAuth,
|
||||
);
|
||||
manager.set(&SecretScope::Global, &AKODE_AUTH_SECRET_NAME, "{}")?;
|
||||
}
|
||||
}
|
||||
let storage = create_auth_storage_with_store(
|
||||
home.path().to_path_buf(),
|
||||
mode,
|
||||
Arc::new(keyring),
|
||||
kind,
|
||||
);
|
||||
if operation == "load" {
|
||||
let result = storage.load();
|
||||
if outcome == "error" {
|
||||
assert!(result.is_err());
|
||||
} else {
|
||||
assert_eq!(result?, Some(auth.clone()));
|
||||
}
|
||||
} else {
|
||||
storage.save(&auth)?;
|
||||
}
|
||||
let store_mode = match mode {
|
||||
AuthCredentialsStoreMode::Auto => "auto",
|
||||
AuthCredentialsStoreMode::Keyring => "keyring",
|
||||
AuthCredentialsStoreMode::File => "file",
|
||||
AuthCredentialsStoreMode::Ephemeral => "ephemeral",
|
||||
};
|
||||
let tags: BTreeMap<String, String> = BTreeMap::from([
|
||||
("credential_kind".into(), "codex".into()),
|
||||
("store_mode".into(), store_mode.into()),
|
||||
(
|
||||
"selected_store".into(),
|
||||
storage_telemetry::keyring_store(kind).as_ref().into(),
|
||||
),
|
||||
("actual_store".into(), actual.into()),
|
||||
("operation".into(), operation.into()),
|
||||
("secure_outcome".into(), secure.into()),
|
||||
("outcome".into(), outcome.into()),
|
||||
("fallback_reason".into(), reason.into()),
|
||||
("secure_error".into(), error.into()),
|
||||
("storage_phase".into(), "policy".into()),
|
||||
("originator".into(), "none".into()),
|
||||
]);
|
||||
if secure == "success" {
|
||||
let mut cleanup_tags = tags.clone();
|
||||
cleanup_tags.extend([
|
||||
("actual_store".into(), "file".into()),
|
||||
("operation".into(), "cleanup".into()),
|
||||
("secure_outcome".into(), "not_attempted".into()),
|
||||
(
|
||||
"outcome".into(),
|
||||
if scenario == "cleanup_failed" {
|
||||
"error"
|
||||
} else {
|
||||
"success"
|
||||
}
|
||||
.into(),
|
||||
),
|
||||
]);
|
||||
*expected.entry(cleanup_tags).or_insert(0) += 1;
|
||||
}
|
||||
*expected.entry(tags).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
let snapshot = metrics.snapshot()?;
|
||||
let mut actual = Vec::new();
|
||||
for metric in snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
|
||||
{
|
||||
if metric.name() == "codex.auth_storage.operation"
|
||||
&& let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data()
|
||||
{
|
||||
for point in sum.data_points() {
|
||||
let tags: BTreeMap<String, String> = point
|
||||
.attributes()
|
||||
.map(|a| (a.key.to_string(), a.value.to_string()))
|
||||
.collect();
|
||||
actual.push((point.value(), tags));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut expected: Vec<_> = expected
|
||||
.into_iter()
|
||||
.map(|(tags, count)| (count, tags))
|
||||
.collect();
|
||||
actual.sort();
|
||||
expected.sort();
|
||||
assert_eq!(actual, expected);
|
||||
metrics.shutdown()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_auth_storage_load_prefers_keyring_value() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let mock_keyring = MockKeyringStore::default();
|
||||
let storage = AutoAuthStorage::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
Arc::new(mock_keyring.clone()),
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
);
|
||||
let keyring_auth = auth_with_prefix("keyring");
|
||||
seed_secrets_backend_with_auth(&mock_keyring, codex_home.path(), &keyring_auth)?;
|
||||
|
||||
let file_auth = auth_with_prefix("file");
|
||||
storage.file_storage.save(&file_auth)?;
|
||||
|
||||
let loaded = storage.load()?;
|
||||
assert_eq!(loaded, Some(keyring_auth));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_auth_storage_load_uses_file_when_keyring_empty() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let mock_keyring = MockKeyringStore::default();
|
||||
let storage = AutoAuthStorage::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
Arc::new(mock_keyring),
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
);
|
||||
|
||||
let expected = auth_with_prefix("file-only");
|
||||
storage.file_storage.save(&expected)?;
|
||||
|
||||
let loaded = storage.load()?;
|
||||
assert_eq!(loaded, Some(expected));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_auth_storage_load_falls_back_when_keyring_errors() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let mock_keyring = MockKeyringStore::default();
|
||||
let storage = AutoAuthStorage::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
Arc::new(mock_keyring.clone()),
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
);
|
||||
let key = compute_keyring_account(codex_home.path(), LocalSecretsNamespace::CodexAuth);
|
||||
|
||||
let encrypted = auth_with_prefix("encrypted");
|
||||
seed_secrets_backend_with_auth(&mock_keyring, codex_home.path(), &encrypted)?;
|
||||
assert_eq!(storage.load()?, Some(encrypted.clone()));
|
||||
mock_keyring.set_error(&key, KeyringError::Invalid("error".into(), "load".into()));
|
||||
|
||||
let expected = auth_with_prefix("fallback");
|
||||
storage.file_storage.save(&expected)?;
|
||||
|
||||
let loaded = storage.load()?;
|
||||
assert_eq!(loaded, Some(expected.clone()));
|
||||
// An absent fallback must not select a plaintext destination for cached credentials.
|
||||
storage.file_storage.delete()?;
|
||||
mock_keyring.set_error(&key, KeyringError::Invalid("error".into(), "load".into()));
|
||||
assert_eq!(storage.load()?, None);
|
||||
storage.save(&auth_with_prefix("cached"))?;
|
||||
assert_keyring_saved_auth_and_removed_fallback(
|
||||
&mock_keyring,
|
||||
codex_home.path(),
|
||||
&auth_with_prefix("cached"),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_auth_storage_save_prefers_keyring() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let mock_keyring = MockKeyringStore::default();
|
||||
let storage = AutoAuthStorage::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
Arc::new(mock_keyring.clone()),
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
);
|
||||
let stale = auth_with_prefix("stale");
|
||||
storage.file_storage.save(&stale)?;
|
||||
|
||||
let expected = auth_with_prefix("to-save");
|
||||
storage.save(&expected)?;
|
||||
|
||||
assert_keyring_saved_auth_and_removed_fallback(&mock_keyring, codex_home.path(), &expected)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_auth_storage_save_falls_back_when_keyring_errors() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let mock_keyring = MockKeyringStore::default();
|
||||
let storage = AutoAuthStorage::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
Arc::new(mock_keyring.clone()),
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
);
|
||||
let key = compute_keyring_account(codex_home.path(), LocalSecretsNamespace::CodexAuth);
|
||||
mock_keyring.set_error(&key, KeyringError::Invalid("error".into(), "save".into()));
|
||||
|
||||
let auth = auth_with_prefix("fallback");
|
||||
storage.save(&auth)?;
|
||||
|
||||
let auth_file = get_auth_file(codex_home.path());
|
||||
assert!(
|
||||
auth_file.exists(),
|
||||
"fallback auth.json should be created when keyring save fails"
|
||||
);
|
||||
let saved = storage
|
||||
.file_storage
|
||||
.load()?
|
||||
.context("fallback auth should exist")?;
|
||||
assert_eq!(saved, auth);
|
||||
assert!(
|
||||
mock_keyring.saved_value(&key).is_none(),
|
||||
"keyring should not contain value when save fails"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_auth_storage_delete_removes_keyring_and_file() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let mock_keyring = MockKeyringStore::default();
|
||||
let storage = AutoAuthStorage::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
Arc::new(mock_keyring.clone()),
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
);
|
||||
let auth = auth_with_prefix("to-delete");
|
||||
let auth_file = seed_secrets_backend_and_fallback_auth_file_for_delete(
|
||||
&mock_keyring,
|
||||
codex_home.path(),
|
||||
&auth,
|
||||
)?;
|
||||
|
||||
let removed = storage.delete()?;
|
||||
|
||||
assert!(removed, "delete should report removal");
|
||||
assert_eq!(storage.load()?, None, "encrypted auth should be removed");
|
||||
assert!(
|
||||
!auth_file.exists(),
|
||||
"fallback auth.json should be removed after delete"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_keyring_auth_storage_saves_legacy_keyring_entry() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let mock_keyring = MockKeyringStore::default();
|
||||
let storage = DirectKeyringAuthStorage::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
Arc::new(mock_keyring.clone()),
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
);
|
||||
let auth_file = get_auth_file(codex_home.path());
|
||||
std::fs::write(&auth_file, "stale")?;
|
||||
let auth = auth_with_prefix("direct");
|
||||
|
||||
storage.save(&auth)?;
|
||||
|
||||
let legacy_key = compute_store_key(codex_home.path())?;
|
||||
let saved_value = mock_keyring
|
||||
.saved_value(&legacy_key)
|
||||
.context("direct keyring auth entry should exist")?;
|
||||
assert_eq!(saved_value, serde_json::to_string(&auth)?);
|
||||
assert!(!encrypted_auth_file(codex_home.path()).exists());
|
||||
assert!(
|
||||
!auth_file.exists(),
|
||||
"fallback auth.json should be removed after keyring save"
|
||||
);
|
||||
assert_eq!(storage.load()?, Some(auth));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secrets_keyring_auth_storage_save_persists_and_removes_fallback_file() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let mock_keyring = MockKeyringStore::default();
|
||||
let storage = SecretsKeyringAuthStorage::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
Arc::new(mock_keyring.clone()),
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
);
|
||||
let auth_file = get_auth_file(codex_home.path());
|
||||
std::fs::write(&auth_file, "stale")?;
|
||||
let auth = AuthDotJson {
|
||||
auth_mode: Some(AuthMode::ApiKey),
|
||||
openai_api_key: Some("sk-keyring-test".to_string()),
|
||||
};
|
||||
|
||||
storage.save(&auth)?;
|
||||
|
||||
assert_keyring_saved_auth_and_removed_fallback(&mock_keyring, codex_home.path(), &auth)?;
|
||||
Ok(())
|
||||
}
|
||||
112
akode-rs/login/src/auth/storage_telemetry.rs
Normal file
112
akode-rs/login/src/auth/storage_telemetry.rs
Normal file
@@ -0,0 +1,112 @@
|
||||
//! Observes logical Codex credential operations without inspecting authentication material.
|
||||
|
||||
use super::AuthDotJson;
|
||||
use super::AuthStorageBackend;
|
||||
use akode_config::types::AuthCredentialsStoreMode;
|
||||
use akode_config::types::AuthKeyringBackendKind;
|
||||
use akode_otel::auth_storage::AuthStorageOriginator;
|
||||
use akode_otel::auth_storage::CredentialKind;
|
||||
use akode_otel::auth_storage::Operation;
|
||||
use akode_otel::auth_storage::StorageTelemetry;
|
||||
use akode_otel::auth_storage::Store;
|
||||
use akode_otel::auth_storage::StoreMode;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(super) fn keyring_store(kind: AuthKeyringBackendKind) -> Store {
|
||||
match kind {
|
||||
AuthKeyringBackendKind::Direct => Store::DirectKeyring,
|
||||
AuthKeyringBackendKind::Secrets => Store::Secrets,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn telemetry(
|
||||
mode: AuthCredentialsStoreMode,
|
||||
kind: AuthKeyringBackendKind,
|
||||
operation: Operation,
|
||||
) -> StorageTelemetry {
|
||||
let mode = match mode {
|
||||
AuthCredentialsStoreMode::File => StoreMode::File,
|
||||
AuthCredentialsStoreMode::Auto => StoreMode::Auto,
|
||||
AuthCredentialsStoreMode::Keyring => StoreMode::Keyring,
|
||||
AuthCredentialsStoreMode::Ephemeral => StoreMode::Ephemeral,
|
||||
};
|
||||
StorageTelemetry::new(
|
||||
CredentialKind::Codex,
|
||||
mode,
|
||||
keyring_store(kind),
|
||||
operation,
|
||||
AuthStorageOriginator::current(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn observe(
|
||||
inner: Arc<dyn AuthStorageBackend>,
|
||||
mode: AuthCredentialsStoreMode,
|
||||
kind: AuthKeyringBackendKind,
|
||||
) -> Arc<dyn AuthStorageBackend> {
|
||||
// Auto records both attempts together so file fallback cannot hide a secure-store failure.
|
||||
if mode == AuthCredentialsStoreMode::Auto {
|
||||
return inner;
|
||||
}
|
||||
Arc::new(ObservedStorage { inner, mode, kind })
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ObservedStorage {
|
||||
inner: Arc<dyn AuthStorageBackend>,
|
||||
mode: AuthCredentialsStoreMode,
|
||||
kind: AuthKeyringBackendKind,
|
||||
}
|
||||
|
||||
impl ObservedStorage {
|
||||
fn store(&self) -> Store {
|
||||
match self.mode {
|
||||
AuthCredentialsStoreMode::File => Store::File,
|
||||
AuthCredentialsStoreMode::Ephemeral => Store::Ephemeral,
|
||||
AuthCredentialsStoreMode::Keyring | AuthCredentialsStoreMode::Auto => {
|
||||
keyring_store(self.kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthStorageBackend for ObservedStorage {
|
||||
fn persistent_home(&self) -> Option<&std::path::Path> {
|
||||
self.inner.persistent_home()
|
||||
}
|
||||
|
||||
fn load(&self) -> std::io::Result<Option<AuthDotJson>> {
|
||||
let mut telemetry = telemetry(self.mode, self.kind, Operation::Load);
|
||||
let result = self.inner.load();
|
||||
telemetry.record_load_attempt(self.store(), &result);
|
||||
if self.mode == AuthCredentialsStoreMode::Keyring
|
||||
&& let Err(error) = &result
|
||||
{
|
||||
telemetry.record_secure_error(error);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn save(&self, auth: &AuthDotJson) -> std::io::Result<()> {
|
||||
let mut telemetry = telemetry(self.mode, self.kind, Operation::Save);
|
||||
let result = self.inner.save(auth);
|
||||
telemetry.record_save_attempt(self.store(), &result);
|
||||
if self.mode == AuthCredentialsStoreMode::Keyring
|
||||
&& let Err(error) = &result
|
||||
{
|
||||
telemetry.record_secure_error(error);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn delete(&self) -> std::io::Result<bool> {
|
||||
let store = match self.mode {
|
||||
AuthCredentialsStoreMode::File | AuthCredentialsStoreMode::Ephemeral => self.store(),
|
||||
AuthCredentialsStoreMode::Auto | AuthCredentialsStoreMode::Keyring => Store::Multiple,
|
||||
};
|
||||
let mut telemetry = telemetry(self.mode, self.kind, Operation::Delete);
|
||||
let result = self.inner.delete();
|
||||
telemetry.record_delete_attempt(store, &result);
|
||||
result
|
||||
}
|
||||
}
|
||||
459
akode-rs/login/src/auth/storage_tests.rs
Normal file
459
akode-rs/login/src/auth/storage_tests.rs
Normal file
@@ -0,0 +1,459 @@
|
||||
use super::*;
|
||||
use anyhow::Context;
|
||||
use akode_secrets::LocalSecretsNamespace;
|
||||
use akode_secrets::SecretScope;
|
||||
use akode_secrets::SecretsBackendKind;
|
||||
use akode_secrets::SecretsManager;
|
||||
use akode_secrets::compute_keyring_account;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::tempdir;
|
||||
|
||||
use akode_keyring_store::tests::MockKeyringStore;
|
||||
use keyring::Error as KeyringError;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn file_storage_creates_dangling_symlink_target_and_rejects_cycles() -> anyhow::Result<()> {
|
||||
use std::os::unix::fs::symlink;
|
||||
let home = tempdir()?;
|
||||
let auth = serde_json::from_value(json!({"OPENAI_API_KEY":"fake-key"}))?;
|
||||
let storage = FileAuthStorage::new(home.path().to_path_buf());
|
||||
symlink("intermediate", home.path().join("auth.json"))?;
|
||||
symlink("new-target.json", home.path().join("intermediate"))?;
|
||||
storage.save(&auth)?;
|
||||
assert_eq!(storage.load()?, Some(auth.clone()));
|
||||
assert!(
|
||||
std::fs::symlink_metadata(home.path().join("auth.json"))?
|
||||
.file_type()
|
||||
.is_symlink()
|
||||
);
|
||||
std::fs::remove_file(home.path().join("new-target.json"))?;
|
||||
symlink("auth.json", home.path().join("new-target.json"))?;
|
||||
assert_eq!(
|
||||
storage.save(&auth).unwrap_err().kind(),
|
||||
std::io::ErrorKind::InvalidInput
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn file_storage_does_not_replace_read_only_or_hard_linked_credentials() -> anyhow::Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let home = tempdir()?;
|
||||
let path = home.path().join("auth.json");
|
||||
let storage = FileAuthStorage::new(home.path().to_path_buf());
|
||||
let first = serde_json::from_value(json!({"OPENAI_API_KEY":"first"}))?;
|
||||
let second = serde_json::from_value(json!({"OPENAI_API_KEY":"second"}))?;
|
||||
storage.save(&first)?;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400))?;
|
||||
assert_eq!(
|
||||
storage.save(&second).unwrap_err().kind(),
|
||||
std::io::ErrorKind::PermissionDenied
|
||||
);
|
||||
assert_eq!(storage.load()?, Some(first.clone()));
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
|
||||
let peer = home.path().join("peer.json");
|
||||
std::fs::hard_link(&path, &peer)?;
|
||||
assert_eq!(
|
||||
storage.save(&second).unwrap_err().kind(),
|
||||
std::io::ErrorKind::Unsupported
|
||||
);
|
||||
assert_eq!(std::fs::read(path)?, std::fs::read(peer)?);
|
||||
assert_eq!(storage.load()?, Some(first));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn file_storage_load_returns_auth_dot_json() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let storage = FileAuthStorage::new(codex_home.path().to_path_buf());
|
||||
let auth_dot_json = AuthDotJson {
|
||||
auth_mode: Some(AuthMode::ApiKey),
|
||||
openai_api_key: Some("test-key".to_string()),
|
||||
};
|
||||
|
||||
storage
|
||||
.save(&auth_dot_json)
|
||||
.context("failed to save auth file")?;
|
||||
|
||||
let loaded = storage.load().context("failed to load auth file")?;
|
||||
assert_eq!(Some(auth_dot_json), loaded);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn file_storage_save_persists_auth_dot_json() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let storage = FileAuthStorage::new(codex_home.path().to_path_buf());
|
||||
let auth_dot_json = AuthDotJson {
|
||||
auth_mode: Some(AuthMode::ApiKey),
|
||||
openai_api_key: Some("test-key".to_string()),
|
||||
};
|
||||
|
||||
let file = get_auth_file(codex_home.path());
|
||||
storage
|
||||
.save(&auth_dot_json)
|
||||
.context("failed to save auth file")?;
|
||||
|
||||
let same_auth_dot_json = storage
|
||||
.try_read_auth_json(&file)
|
||||
.context("failed to read auth file after save")?;
|
||||
assert_eq!(auth_dot_json, same_auth_dot_json);
|
||||
|
||||
// An overlapping reader must keep seeing the complete old document.
|
||||
let mut overlapping_reader = File::open(&file)?;
|
||||
let mut replacement = auth_dot_json.clone();
|
||||
replacement.openai_api_key = Some("replacement-with-a-different-length".to_string());
|
||||
storage
|
||||
.save(&replacement)
|
||||
.context("atomically replace auth while the original reader remains open")?;
|
||||
let mut original_contents = String::new();
|
||||
overlapping_reader.read_to_string(&mut original_contents)?;
|
||||
assert_eq!(
|
||||
serde_json::from_str::<AuthDotJson>(&original_contents)?,
|
||||
auth_dot_json
|
||||
);
|
||||
assert_eq!(storage.load()?, Some(replacement));
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(
|
||||
std::fs::metadata(&file)?.permissions().mode() & 0o777,
|
||||
0o600
|
||||
);
|
||||
|
||||
let linked_home = tempdir()?;
|
||||
let link = get_auth_file(linked_home.path());
|
||||
std::os::unix::fs::symlink(&file, &link)?;
|
||||
FileAuthStorage::new(linked_home.path().to_path_buf()).save(&auth_dot_json)?;
|
||||
assert!(std::fs::symlink_metadata(link)?.file_type().is_symlink());
|
||||
assert_eq!(storage.load()?, Some(auth_dot_json));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_storage_failed_replacement_cleans_up_temporary_file() -> anyhow::Result<()> {
|
||||
let home = tempdir()?;
|
||||
let auth_path = get_auth_file(home.path());
|
||||
// A directory cannot be replaced by an auth file on any supported platform.
|
||||
std::fs::create_dir(&auth_path)?;
|
||||
let storage = FileAuthStorage::new(home.path().to_path_buf());
|
||||
let auth = serde_json::from_value(json!({"OPENAI_API_KEY": "test-key"}))?;
|
||||
assert!(storage.save(&auth).is_err());
|
||||
let entries = std::fs::read_dir(home.path())?
|
||||
.map(|entry| entry.map(|entry| entry.file_name()))
|
||||
.collect::<std::io::Result<Vec<_>>>()?;
|
||||
assert_eq!(entries, vec![std::ffi::OsString::from("auth.json")]);
|
||||
assert!(auth_path.is_dir());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_storage_delete_removes_auth_file() -> anyhow::Result<()> {
|
||||
let dir = tempdir()?;
|
||||
let auth_dot_json = AuthDotJson {
|
||||
auth_mode: Some(AuthMode::ApiKey),
|
||||
openai_api_key: Some("sk-test-key".to_string()),
|
||||
};
|
||||
let storage = create_auth_storage(
|
||||
dir.path().to_path_buf(),
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
);
|
||||
storage.save(&auth_dot_json)?;
|
||||
assert!(dir.path().join("auth.json").exists());
|
||||
let storage = FileAuthStorage::new(dir.path().to_path_buf());
|
||||
let removed = storage.delete()?;
|
||||
assert!(removed);
|
||||
assert!(!dir.path().join("auth.json").exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ephemeral_storage_save_load_delete_is_in_memory_only() -> anyhow::Result<()> {
|
||||
let dir = tempdir()?;
|
||||
let storage = create_auth_storage(
|
||||
dir.path().to_path_buf(),
|
||||
AuthCredentialsStoreMode::Ephemeral,
|
||||
AuthKeyringBackendKind::default(),
|
||||
);
|
||||
let auth_dot_json = AuthDotJson {
|
||||
auth_mode: Some(AuthMode::ApiKey),
|
||||
openai_api_key: Some("sk-ephemeral".to_string()),
|
||||
};
|
||||
|
||||
storage.save(&auth_dot_json)?;
|
||||
let loaded = storage.load()?;
|
||||
assert_eq!(Some(auth_dot_json), loaded);
|
||||
|
||||
let removed = storage.delete()?;
|
||||
assert!(removed);
|
||||
let loaded = storage.load()?;
|
||||
assert_eq!(None, loaded);
|
||||
assert!(!get_auth_file(dir.path()).exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn seed_secrets_backend_and_fallback_auth_file_for_delete(
|
||||
mock_keyring: &MockKeyringStore,
|
||||
codex_home: &Path,
|
||||
auth: &AuthDotJson,
|
||||
) -> anyhow::Result<PathBuf> {
|
||||
let manager = SecretsManager::new_with_keyring_store_and_namespace(
|
||||
codex_home.to_path_buf(),
|
||||
SecretsBackendKind::Local,
|
||||
Arc::new(mock_keyring.clone()),
|
||||
LocalSecretsNamespace::CodexAuth,
|
||||
);
|
||||
manager.set(
|
||||
&SecretScope::Global,
|
||||
&AKODE_AUTH_SECRET_NAME,
|
||||
&serde_json::to_string(auth)?,
|
||||
)?;
|
||||
let auth_file = get_auth_file(codex_home);
|
||||
std::fs::write(&auth_file, "stale")?;
|
||||
Ok(auth_file)
|
||||
}
|
||||
|
||||
fn seed_secrets_backend_with_auth(
|
||||
mock_keyring: &MockKeyringStore,
|
||||
codex_home: &Path,
|
||||
auth: &AuthDotJson,
|
||||
) -> anyhow::Result<()> {
|
||||
let manager = SecretsManager::new_with_keyring_store_and_namespace(
|
||||
codex_home.to_path_buf(),
|
||||
SecretsBackendKind::Local,
|
||||
Arc::new(mock_keyring.clone()),
|
||||
LocalSecretsNamespace::CodexAuth,
|
||||
);
|
||||
manager.set(
|
||||
&SecretScope::Global,
|
||||
&AKODE_AUTH_SECRET_NAME,
|
||||
&serde_json::to_string(auth)?,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn assert_keyring_saved_auth_and_removed_fallback(
|
||||
mock_keyring: &MockKeyringStore,
|
||||
codex_home: &Path,
|
||||
expected: &AuthDotJson,
|
||||
) -> anyhow::Result<()> {
|
||||
let manager = SecretsManager::new_with_keyring_store_and_namespace(
|
||||
codex_home.to_path_buf(),
|
||||
SecretsBackendKind::Local,
|
||||
Arc::new(mock_keyring.clone()),
|
||||
LocalSecretsNamespace::CodexAuth,
|
||||
);
|
||||
let saved_value = manager
|
||||
.get(&SecretScope::Global, &AKODE_AUTH_SECRET_NAME)?
|
||||
.context("encrypted auth entry should exist")?;
|
||||
let expected_serialized = serde_json::to_string(expected)?;
|
||||
assert_eq!(saved_value, expected_serialized);
|
||||
let old_key = compute_store_key(codex_home)?;
|
||||
assert!(
|
||||
mock_keyring.saved_value(&old_key).is_none(),
|
||||
"legacy keyring auth entry should not be used"
|
||||
);
|
||||
let secrets_key = compute_keyring_account(codex_home, LocalSecretsNamespace::CodexAuth);
|
||||
assert!(
|
||||
mock_keyring.saved_value(&secrets_key).is_some(),
|
||||
"secrets backend should persist an encryption passphrase in the keyring"
|
||||
);
|
||||
assert!(encrypted_auth_file(codex_home).exists());
|
||||
let auth_file = get_auth_file(codex_home);
|
||||
assert!(
|
||||
!auth_file.exists(),
|
||||
"fallback auth.json should be removed after keyring save"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn encrypted_auth_file(codex_home: &Path) -> PathBuf {
|
||||
codex_home.join("secrets").join("codex_auth.age")
|
||||
}
|
||||
|
||||
fn auth_with_prefix(prefix: &str) -> AuthDotJson {
|
||||
AuthDotJson {
|
||||
auth_mode: Some(AuthMode::ApiKey),
|
||||
openai_api_key: Some(format!("{prefix}-api-key")),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secrets_keyring_auth_storage_load_returns_deserialized_auth() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let mock_keyring = MockKeyringStore::default();
|
||||
let storage = SecretsKeyringAuthStorage::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
Arc::new(mock_keyring.clone()),
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
);
|
||||
let expected = AuthDotJson {
|
||||
auth_mode: Some(AuthMode::ApiKey),
|
||||
openai_api_key: Some("sk-test".to_string()),
|
||||
};
|
||||
seed_secrets_backend_with_auth(&mock_keyring, codex_home.path(), &expected)?;
|
||||
|
||||
let loaded = storage.load()?;
|
||||
assert_eq!(Some(expected), loaded);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyring_auth_storage_compute_store_key_for_home_directory() -> anyhow::Result<()> {
|
||||
let codex_home = PathBuf::from("~/.akode");
|
||||
|
||||
let key = compute_store_key(codex_home.as_path())?;
|
||||
|
||||
assert_eq!(key, "cli|940db7b1d0e4eb40");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_keyring_auth_storage_delete_removes_keyring_and_file() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let mock_keyring = MockKeyringStore::default();
|
||||
let storage = DirectKeyringAuthStorage::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
Arc::new(mock_keyring.clone()),
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
);
|
||||
let auth = auth_with_prefix("direct-delete");
|
||||
storage.save(&auth)?;
|
||||
let auth_file = get_auth_file(codex_home.path());
|
||||
std::fs::write(&auth_file, "stale")?;
|
||||
|
||||
let removed = storage.delete()?;
|
||||
|
||||
assert!(removed, "delete should report removal");
|
||||
assert_eq!(storage.load()?, None, "keyring auth should be removed");
|
||||
assert!(
|
||||
mock_keyring
|
||||
.saved_value(&compute_store_key(codex_home.path())?)
|
||||
.is_none(),
|
||||
"legacy keyring auth entry should be removed"
|
||||
);
|
||||
assert!(
|
||||
!auth_file.exists(),
|
||||
"fallback auth.json should be removed after keyring delete"
|
||||
);
|
||||
assert!(!encrypted_auth_file(codex_home.path()).exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn factory_uses_secrets_backend_only_when_requested() -> anyhow::Result<()> {
|
||||
let direct_home = tempdir()?;
|
||||
let direct_keyring = MockKeyringStore::default();
|
||||
let direct_storage = create_auth_storage_with_store(
|
||||
direct_home.path().to_path_buf(),
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
Arc::new(direct_keyring.clone()),
|
||||
AuthKeyringBackendKind::Direct,
|
||||
);
|
||||
let direct_auth = auth_with_prefix("factory-direct");
|
||||
direct_storage.save(&direct_auth)?;
|
||||
assert!(
|
||||
direct_keyring
|
||||
.saved_value(&compute_store_key(direct_home.path())?)
|
||||
.is_some()
|
||||
);
|
||||
assert!(!encrypted_auth_file(direct_home.path()).exists());
|
||||
|
||||
let secrets_home = tempdir()?;
|
||||
let secrets_keyring = MockKeyringStore::default();
|
||||
let secrets_storage = create_auth_storage_with_store(
|
||||
secrets_home.path().to_path_buf(),
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
Arc::new(secrets_keyring.clone()),
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
);
|
||||
let secrets_auth = auth_with_prefix("factory-secrets");
|
||||
secrets_storage.save(&secrets_auth)?;
|
||||
assert!(
|
||||
secrets_keyring
|
||||
.saved_value(&compute_keyring_account(
|
||||
secrets_home.path(),
|
||||
LocalSecretsNamespace::CodexAuth,
|
||||
))
|
||||
.is_some()
|
||||
);
|
||||
assert!(encrypted_auth_file(secrets_home.path()).exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secrets_keyring_auth_storage_delete_removes_keyring_and_file() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let mock_keyring = MockKeyringStore::default();
|
||||
let storage = SecretsKeyringAuthStorage::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
Arc::new(mock_keyring.clone()),
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
);
|
||||
let auth = auth_with_prefix("to-delete");
|
||||
let auth_file = seed_secrets_backend_and_fallback_auth_file_for_delete(
|
||||
&mock_keyring,
|
||||
codex_home.path(),
|
||||
&auth,
|
||||
)?;
|
||||
|
||||
let removed = storage.delete()?;
|
||||
|
||||
assert!(removed, "delete should report removal");
|
||||
assert_eq!(storage.load()?, None, "encrypted auth should be removed");
|
||||
assert!(
|
||||
!auth_file.exists(),
|
||||
"fallback auth.json should be removed after keyring delete"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secrets_keyring_auth_storage_delete_removes_legacy_direct_keyring_entry() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let mock_keyring = MockKeyringStore::default();
|
||||
let direct_storage = DirectKeyringAuthStorage::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
Arc::new(mock_keyring.clone()),
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
);
|
||||
direct_storage.save(&auth_with_prefix("legacy-direct"))?;
|
||||
let storage = SecretsKeyringAuthStorage::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
Arc::new(mock_keyring.clone()),
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
);
|
||||
let auth = auth_with_prefix("to-delete");
|
||||
let auth_file = seed_secrets_backend_and_fallback_auth_file_for_delete(
|
||||
&mock_keyring,
|
||||
codex_home.path(),
|
||||
&auth,
|
||||
)?;
|
||||
|
||||
let removed = storage.delete()?;
|
||||
|
||||
assert!(removed, "delete should report removal");
|
||||
assert_eq!(storage.load()?, None, "encrypted auth should be removed");
|
||||
assert_eq!(
|
||||
direct_storage.load()?,
|
||||
None,
|
||||
"legacy direct keyring auth should be removed"
|
||||
);
|
||||
assert!(
|
||||
!auth_file.exists(),
|
||||
"fallback auth.json should be removed after keyring delete"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[path = "storage_policy_tests.rs"]
|
||||
mod policy;
|
||||
|
||||
#[path = "storage_error_tests.rs"]
|
||||
mod errors;
|
||||
Reference in New Issue
Block a user