use std::sync::Arc;
use rho_protocol::{
AuthKeyParams, AuthKeyResponse, AuthKind, AuthListParams, AuthListResponse, AuthLogoutParams,
AuthLogoutResponse, AuthStatus, AuthSummary, ClientEnvironment, ErrorCode, RpcError,
UncheckedKey, UncheckedReason,
};
use rho_providers::{
auth::login_dispatch::{AuthenticationMethod, ProviderAuthentication},
credentials::{available_auth_modes, CredentialStore},
model::catalog::{self, LoginTarget},
};
use super::sessions::{session_environment, Sessions};
use crate::{
app::{
config_repository::ConfigRepository,
credential_writes::{self, ApiKeyAuth, CredentialWriteError, KeyCheck},
},
config::Config,
credential_store::AppCredentialStore,
};
pub(super) fn client_credentials(
environment: &ClientEnvironment,
) -> Result<Arc<dyn CredentialStore>, RpcError> {
Ok(session_environment(environment)?.credentials())
}
pub(super) fn repository() -> ConfigRepository {
ConfigRepository::new(None)
}
pub(super) async fn list(params: AuthListParams) -> Result<AuthListResponse, RpcError> {
let credentials = client_credentials(¶ms.environment)?;
let (_, signed_in) = config_and_auths(credentials).await?;
let auths = catalog::login_targets()
.into_iter()
.filter_map(|target| summary(target, &signed_in))
.collect();
Ok(AuthListResponse { auths })
}
pub(super) async fn config_and_auths(
credentials: Arc<dyn CredentialStore>,
) -> Result<(Config, Vec<String>), RpcError> {
off_workers(move || -> Result<_, CredentialWriteError> {
let config = credential_writes::load_config_and_store(&repository())?;
AppCredentialStore::reread_external_logins();
Ok((config, available_auth_modes(credentials.as_ref())))
})
.await?
.map_err(RpcError::from)
}
fn summary(target: LoginTarget, signed_in: &[String]) -> Option<AuthSummary> {
let kind = match ProviderAuthentication::method(&target.auth).ok()? {
AuthenticationMethod::None => return None,
AuthenticationMethod::ApiKey { .. } => AuthKind::ApiKey,
AuthenticationMethod::Interactive { .. } => AuthKind::Login,
};
let status = if signed_in.contains(&target.auth) {
AuthStatus::SignedIn
} else {
AuthStatus::SignedOut
};
let LoginTarget {
provider,
auth,
label,
} = target;
Some(AuthSummary {
auth,
provider,
label,
kind,
status,
})
}
pub(super) async fn credentials_changed(sessions: &Sessions) {
AppCredentialStore::reread_external_logins();
sessions.models_changed().await;
}
pub(super) async fn save_key(params: AuthKeyParams) -> Result<AuthKeyResponse, RpcError> {
let AuthKeyParams {
auth,
key,
environment,
} = params;
let credentials = client_credentials(&environment)?;
let asked = Arc::clone(&credentials);
let (config, login, key) = off_workers(move || -> Result<_, CredentialWriteError> {
let config = credential_writes::load_config_and_store(&repository())?;
let login = ApiKeyAuth::resolve(&auth, asked.as_ref())?;
let key = key.trim();
if key.is_empty() {
return Err(CredentialWriteError::BlankKey);
}
Ok((config, login, key.to_owned()))
})
.await??;
let check = login.check(&key, &config).await?;
let saved_to = Arc::clone(&credentials);
off_workers(move || {
login.save(&key, saved_to.as_ref())?;
login.record_login(&repository())
})
.await??;
tracing::info!(auth = %login.auth(), "saved an API key");
let refreshed =
super::models::refresh_after_sign_in(login.auth(), credentials.as_ref(), &config).await;
let unchecked = match check {
KeyCheck::Accepted => None,
KeyCheck::NoModelListing => Some(UncheckedKey {
reason: UncheckedReason::NoModelListing,
message: "rho lists no models for this provider, so it cannot ask about a key".into(),
}),
KeyCheck::Unreachable(message) => Some(UncheckedKey {
reason: UncheckedReason::Unreachable,
message,
}),
KeyCheck::Forbidden => Some(UncheckedKey {
reason: UncheckedReason::Forbidden,
message: "the key may not list the provider's models (HTTP 403 Forbidden), so rho could not ask about it".into(),
}),
};
Ok(AuthKeyResponse {
unchecked,
refreshed,
})
}
pub(super) async fn logout(params: AuthLogoutParams) -> Result<AuthLogoutResponse, RpcError> {
let AuthLogoutParams { auth, environment } = params;
let credentials = client_credentials(&environment)?;
let signed_out = auth.clone();
off_workers(move || {
credential_writes::sign_out_named(&auth, &repository(), credentials.as_ref())
})
.await??;
tracing::info!(auth = %signed_out, "signed out");
Ok(AuthLogoutResponse {})
}
pub(super) async fn off_workers<T: Send + 'static>(
operation: impl FnOnce() -> T + Send + 'static,
) -> Result<T, RpcError> {
tokio::task::spawn_blocking(operation)
.await
.map_err(|error| {
RpcError::new(
ErrorCode::InternalError,
format!("the credential write did not finish: {error}"),
)
})
}
impl From<CredentialWriteError> for RpcError {
fn from(error: CredentialWriteError) -> Self {
let code = match &error {
CredentialWriteError::UnknownAuth { .. }
| CredentialWriteError::NotAnApiKey { .. }
| CredentialWriteError::NoCredentials { .. }
| CredentialWriteError::BlankKey => ErrorCode::InvalidParams,
CredentialWriteError::EnvironmentOverride {
auth,
variable,
write,
} => {
let data = serde_json::to_value(rho_protocol::EnvironmentOverride {
variable: (*variable).to_owned(),
})
.expect("an environment override serializes");
return RpcError::new(
ErrorCode::EnvironmentOverride,
format!(
"'{auth}' reads its credential from {variable} in this client's environment, which wins over a saved one; unset it there to {write}"
),
)
.with_data(data);
}
CredentialWriteError::KeyRefused { .. } => ErrorCode::KeyRefused,
CredentialWriteError::Config(_) => ErrorCode::InternalError,
CredentialWriteError::Store(_) => ErrorCode::CredentialStoreUnavailable,
};
RpcError::new(code, error.to_string())
}
}