214 lines
7.9 KiB
Rust
214 lines
7.9 KiB
Rust
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
|
|
))
|
|
));
|
|
}
|