use std::{
process::Command,
sync::{Arc, Mutex},
};
use pretty_assertions::assert_eq;
use rho_protocol::{
methods::{AuthChooseStore, AuthKey, AuthLogout, JobList, SessionPrompt, Status},
AuthChooseStoreParams, AuthChooseStoreResponse, AuthKeyParams, AuthKeyResponse,
AuthLogoutParams, AuthLogoutResponse, Client, ClientEnvironment, ClientError, ContentBlock,
CredentialStoreKind, CredentialStoreStatus, EnvironmentOverride, ErrorCode, JobListParams,
JobState, RpcError, SessionId, SessionPromptParams, StatusParams, StoreSelectedBy, TurnError,
TurnErrorKind, TurnOutcome,
};
use rho_providers::credentials::{CredentialStore, FileCredentialStore};
use serde_json::Value;
use super::{key_checking_provider::spawn_provider, sessions::Sandbox};
pub(super) const FIRST_KEY: &str = "test-first-key";
const SECOND_KEY: &str = "test-second-key";
const WRONG_KEY: &str = "test-wrong-key";
const AUTH: &str = "mock-api-key";
pub(super) const KEY_ACCOUNT: &str = "provider:mock:api-key";
const KEY_VARIABLE: &str = "RHO_MOCK_API_KEY";
pub(super) struct Fixture {
pub(super) sandbox: Sandbox,
pub(super) store: FileCredentialStore,
}
impl Fixture {
async fn start(valid: &Arc<Mutex<String>>, environment: &[(&str, &str)]) -> Self {
Self::start_with(valid, |command| {
command.envs(environment.iter().copied());
})
.await
}
pub(super) async fn start_with(
valid: &Arc<Mutex<String>>,
configure: impl FnOnce(&mut Command),
) -> Self {
let fixture = Self::without_daemon(valid);
let mut command = fixture.sandbox.rho("fixed");
command.env_remove("RHO_AUTOMATION_TEST_MODE");
configure(&mut command);
fixture.sandbox.spawn_daemon(command, &[]).await;
fixture
}
pub(super) fn without_daemon(valid: &Arc<Mutex<String>>) -> Self {
let address = spawn_provider(Arc::clone(valid));
let sandbox = Sandbox::new();
std::fs::write(
&sandbox.isolated.config_path,
format!(
r#"[model]
provider = "mock"
model = "mock-model"
auth = "{AUTH}"
[providers.custom.mock]
base_url = "http://{address}/v1"
[behavior]
[web_search]
mode = "off"
"#
),
)
.unwrap();
let store = FileCredentialStore::with_rho_home(sandbox.isolated.rho_home()).unwrap();
Self { sandbox, store }
}
async fn prompt(&self, client: &Client, session: &SessionId) -> Result<JobState, RpcError> {
self.prompt_from(client, session, self.sandbox.client_environment())
.await
}
pub(super) async fn prompt_from(
&self,
client: &Client,
session: &SessionId,
environment: ClientEnvironment,
) -> Result<JobState, RpcError> {
client
.request::<SessionPrompt>(&SessionPromptParams {
author: rho_protocol::PromptAuthor::Person,
session: session.clone(),
content: vec![ContentBlock::Text {
text: "hello".into(),
}],
timeout_ms: None,
environment,
idempotency_key: None,
grant: None,
})
.await
.map_err(rpc_error)?;
Ok(self
.sandbox
.poll_until("the turn to end", async || {
let jobs = client.request::<JobList>(&JobListParams {}).await.unwrap();
let job = jobs
.jobs
.into_iter()
.find(|job| job.session.as_ref() == Some(session))
.expect("the daemon lists the session's job");
match job.state {
JobState::Queued | JobState::Running | JobState::WaitingForInput => None,
state => Some(state),
}
})
.await)
}
pub(super) fn saved_key(&self) -> Option<String> {
self.store.get_secret(KEY_ACCOUNT).unwrap()
}
}
pub(super) fn rpc_error(error: ClientError) -> RpcError {
match error {
ClientError::Rpc { error, .. } => error,
error => panic!("the request failed outside the protocol: {error}"),
}
}
async fn save_key(client: &Client, key: &str) -> Result<AuthKeyResponse, RpcError> {
save_key_from(client, key, ClientEnvironment::default()).await
}
async fn save_key_from(
client: &Client,
key: &str,
environment: ClientEnvironment,
) -> Result<AuthKeyResponse, RpcError> {
client
.request::<AuthKey>(&AuthKeyParams {
auth: AUTH.into(),
key: key.into(),
environment,
})
.await
.map_err(rpc_error)
}
async fn logout(client: &Client) -> Result<AuthLogoutResponse, RpcError> {
logout_from(client, ClientEnvironment::default()).await
}
async fn logout_from(
client: &Client,
environment: ClientEnvironment,
) -> Result<AuthLogoutResponse, RpcError> {
client
.request::<AuthLogout>(&AuthLogoutParams {
auth: AUTH.into(),
environment,
})
.await
.map_err(rpc_error)
}
pub(super) async fn store_status(client: &Client) -> CredentialStoreStatus {
client
.request::<Status>(&StatusParams {})
.await
.unwrap()
.credential_store
}
async fn choose_store(
client: &Client,
store: CredentialStoreKind,
) -> Result<AuthChooseStoreResponse, RpcError> {
client
.request::<AuthChooseStore>(&AuthChooseStoreParams {
store,
environment: ClientEnvironment::default(),
})
.await
.map_err(rpc_error)
}
fn error_of<T: std::fmt::Debug>(result: Result<T, RpcError>) -> (Option<ErrorCode>, Option<Value>) {
let error = result.expect_err("the daemon refuses");
(error.error_code(), error.data)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_key_saved_or_deleted_by_one_client_applies_to_another_clients_session() {
let valid = Arc::new(Mutex::new(FIRST_KEY.to_owned()));
let fixture = Fixture::start(&valid, &[]).await;
let (first, second) = (
fixture.sandbox.connect().await,
fixture.sandbox.connect().await,
);
assert_eq!(
save_key(&first, FIRST_KEY).await,
Ok(AuthKeyResponse { unchecked: None })
);
let session = fixture.sandbox.new_session(&first).await;
assert_eq!(
fixture.prompt(&first, &session).await,
Ok(JobState::Completed),
"log:\n{}",
fixture.sandbox.isolated.daemon_log()
);
*valid.lock().unwrap() = SECOND_KEY.to_owned();
assert_eq!(
(save_key(&second, WRONG_KEY).await, fixture.saved_key()),
(
Err(RpcError::new(
ErrorCode::KeyRefused,
"mock refused the key: its models endpoint answered HTTP 401 Unauthorized"
)),
Some(FIRST_KEY.into())
)
);
assert_eq!(
save_key(&second, SECOND_KEY).await,
Ok(AuthKeyResponse { unchecked: None })
);
assert_eq!(
fixture.prompt(&first, &session).await,
Ok(JobState::Completed),
"the session renews to the saved key; log:\n{}",
fixture.sandbox.isolated.daemon_log()
);
assert_eq!(logout(&second).await, Ok(AuthLogoutResponse {}));
let failed = TurnOutcome::Failed {
error: TurnError {
kind: TurnErrorKind::Authentication,
message: "authentication failed for mock (auth: mock-api-key); run /login mock".into(),
},
};
assert_eq!(
(
fixture.saved_key(),
error_of(fixture.prompt(&first, &session).await)
),
(
None,
(
Some(ErrorCode::TurnEnded),
Some(serde_json::to_value(failed).unwrap())
)
),
"log:\n{}",
fixture.sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_key_in_a_clients_environment_refuses_its_sign_in_and_out() {
let valid = Arc::new(Mutex::new(FIRST_KEY.to_owned()));
let fixture = Fixture::start(&valid, &[(KEY_VARIABLE, SECOND_KEY)]).await;
fixture.store.set_secret(KEY_ACCOUNT, FIRST_KEY).unwrap();
let client = fixture.sandbox.connect().await;
let exporting = || -> ClientEnvironment {
[(KEY_VARIABLE.to_owned(), SECOND_KEY.to_owned())]
.into_iter()
.collect()
};
let overridden = (
Some(ErrorCode::EnvironmentOverride),
Some(
serde_json::to_value(EnvironmentOverride {
variable: KEY_VARIABLE.into(),
})
.unwrap(),
),
);
assert_eq!(
(
error_of(save_key_from(&client, FIRST_KEY, exporting()).await),
error_of(logout_from(&client, exporting()).await),
fixture.saved_key(),
),
(overridden.clone(), overridden, Some(FIRST_KEY.into()))
);
assert_eq!(
(
save_key(&client, FIRST_KEY).await,
logout(&client).await,
fixture.saved_key(),
),
(
Ok(AuthKeyResponse { unchecked: None }),
Ok(AuthLogoutResponse {}),
None
),
"log:\n{}",
fixture.sandbox.isolated.daemon_log()
);
}
#[cfg(target_os = "linux")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_daemon_without_a_session_bus_fails_closed_until_a_client_chooses_the_file_store() {
let valid = Arc::new(Mutex::new(FIRST_KEY.to_owned()));
let fixture = Fixture::start_with(&valid, |command| {
command.env_remove("RHO_CREDENTIAL_STORE");
})
.await;
let client = fixture.sandbox.connect().await;
let headless = store_status(&client).await;
assert_eq!(
(
headless.store,
headless.selected_by,
headless.unreachable.is_some()
),
(CredentialStoreKind::Os, StoreSelectedBy::Default, true),
"{headless:?}"
);
let login = client
.request::<rho_protocol::methods::AuthLogin>(&rho_protocol::AuthLoginParams {
auth: "xai-oauth".into(),
flow: None,
environment: ClientEnvironment::default(),
})
.await
.map_err(rpc_error);
assert_eq!(
(
error_of(save_key(&client, FIRST_KEY).await).0,
error_of(login).0,
error_of(choose_store(&client, CredentialStoreKind::Os).await).0,
fixture.saved_key(),
),
(
Some(ErrorCode::CredentialStoreUnavailable),
Some(ErrorCode::CredentialStoreUnavailable),
Some(ErrorCode::CredentialStoreUnavailable),
None
)
);
let chosen = CredentialStoreStatus {
store: CredentialStoreKind::File,
selected_by: StoreSelectedBy::Config,
unreachable: None,
};
assert_eq!(
choose_store(&client, CredentialStoreKind::File).await,
Ok(AuthChooseStoreResponse {
credential_store: chosen.clone()
})
);
assert_eq!(store_status(&client).await, chosen);
assert_eq!(
save_key(&client, FIRST_KEY).await,
Ok(AuthKeyResponse { unchecked: None })
);
let session = fixture.sandbox.new_session(&client).await;
assert_eq!(
(fixture.saved_key(), fixture.prompt(&client, &session).await),
(Some(FIRST_KEY.into()), Ok(JobState::Completed)),
"log:\n{}",
fixture.sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_store_the_daemons_environment_chose_cannot_be_replaced() {
let valid = Arc::new(Mutex::new(FIRST_KEY.to_owned()));
let fixture = Fixture::start(&valid, &[]).await;
let client = fixture.sandbox.connect().await;
assert_eq!(
(
store_status(&client).await,
error_of(choose_store(&client, CredentialStoreKind::File).await),
),
(
CredentialStoreStatus {
store: CredentialStoreKind::File,
selected_by: StoreSelectedBy::Environment,
unreachable: None,
},
(
Some(ErrorCode::EnvironmentOverride),
Some(
serde_json::to_value(EnvironmentOverride {
variable: "RHO_CREDENTIAL_STORE".into(),
})
.unwrap()
)
)
)
);
}