use std::{
collections::HashMap,
sync::{Arc, Mutex, MutexGuard, PoisonError},
};
use rho_protocol::{
login_relay, AuthLoginCancelParams, AuthLoginCancelResponse, AuthLoginParams,
AuthLoginResponse, ErrorCode, LoginFlow, LoginId, LoginOutcome, LoginRelay, LoginStream,
RpcError,
};
use rho_providers::{
auth::{
browser::BrowserAvailability,
login_dispatch::{AuthenticationError, AuthenticationMethod, ProviderAuthentication},
},
credentials::CredentialStore,
provider::{self, ProviderDescriptor},
};
use rho_sdk::CancellationToken;
use super::{
auth::{client_credentials, credentials_changed, off_workers, repository},
sessions::Sessions,
};
use crate::app::{
credential_writes::{self, CredentialWrite},
login::{
drive::{self, Approval},
relay_wire::{flow_from_wire, prompt_to_wire},
},
};
pub(super) struct Logins {
under_way: Mutex<HashMap<&'static str, UnderWay>>,
}
struct UnderWay {
login: LoginId,
cancel: CancellationToken,
}
impl Logins {
pub(super) fn new() -> Self {
Self {
under_way: Mutex::new(HashMap::new()),
}
}
pub(super) async fn start(
self: &Arc<Self>,
params: AuthLoginParams,
sessions: Arc<Sessions>,
) -> Result<(AuthLoginResponse, LoginStream), RpcError> {
let AuthLoginParams {
auth,
flow,
environment,
} = params;
let flow = flow.unwrap_or_default();
let credentials = client_credentials(&environment)?;
let target = off_workers(move || LoginAuth::resolve(&auth, credentials)).await??;
let login = LoginId::new(uuid::Uuid::new_v4().to_string());
let cancel = CancellationToken::new();
let slot = self.claim(target.auth, &login, &cancel)?;
let (relay, stream) = login_relay();
tracing::info!(auth = target.auth, "login started");
tokio::spawn(run(target, flow, cancel, relay, slot, sessions));
Ok((AuthLoginResponse { login }, stream))
}
pub(super) fn under_way(&self) -> usize {
self.lock().len()
}
pub(super) fn cancel(
&self,
params: AuthLoginCancelParams,
) -> Result<AuthLoginCancelResponse, RpcError> {
let under_way = self.lock();
let Some(found) = under_way
.values()
.find(|under_way| under_way.login == params.login)
else {
return Err(RpcError::new(
ErrorCode::LoginNotFound,
format!("no login under way has the id {}", params.login),
));
};
found.cancel.cancel();
Ok(AuthLoginCancelResponse {})
}
fn claim(
self: &Arc<Self>,
auth: &'static str,
login: &LoginId,
cancel: &CancellationToken,
) -> Result<Slot, RpcError> {
let mut under_way = self.lock();
if under_way.contains_key(auth) {
return Err(RpcError::new(
ErrorCode::LoginBusy,
format!(
"the daemon is already signing in to '{auth}'; wait for that login to finish"
),
));
}
under_way.insert(
auth,
UnderWay {
login: login.clone(),
cancel: cancel.clone(),
},
);
Ok(Slot {
logins: Arc::clone(self),
auth,
})
}
fn lock(&self) -> MutexGuard<'_, HashMap<&'static str, UnderWay>> {
self.under_way
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
}
struct Slot {
logins: Arc<Logins>,
auth: &'static str,
}
impl Drop for Slot {
fn drop(&mut self) {
self.logins.lock().remove(self.auth);
}
}
struct LoginAuth {
auth: &'static str,
provider_label: &'static str,
descriptor: &'static ProviderDescriptor,
credentials: Arc<dyn CredentialStore>,
}
impl LoginAuth {
fn resolve(auth: &str, credentials: Arc<dyn CredentialStore>) -> Result<Self, RpcError> {
credential_writes::load_config_and_store(&repository())?;
let invalid = |message: String| RpcError::new(ErrorCode::InvalidParams, message);
let Some((descriptor, mode)) = provider::resolve_auth_mode(auth) else {
return Err(invalid(format!("unknown auth profile '{auth}'")));
};
let method =
ProviderAuthentication::method(mode.id).map_err(|error| invalid(error.to_string()))?;
let provider_label = match method {
AuthenticationMethod::Interactive { provider_label } => provider_label,
AuthenticationMethod::ApiKey { .. } => {
return Err(invalid(format!(
"'{auth}' takes an API key; send it with rho/auth/key"
)));
}
AuthenticationMethod::None => {
return Err(invalid(format!("'{auth}' needs no sign-in")));
}
};
credential_writes::refuse_environment_override(
mode.id,
CredentialWrite::Login,
credentials.as_ref(),
)?;
credential_writes::refuse_unreachable_store(credentials.as_ref())?;
Ok(Self {
auth: mode.id,
provider_label,
descriptor,
credentials,
})
}
}
enum Ended {
Approved(Result<Approval, AuthenticationError>),
Cancelled,
ClientLeft,
}
async fn run(
target: LoginAuth,
flow: LoginFlow,
cancel: CancellationToken,
relay: LoginRelay,
slot: Slot,
sessions: Arc<Sessions>,
) {
let auth = target.auth;
let approved = drive::approve(
target.credentials.as_ref(),
auth,
flow_from_wire(flow),
BrowserAvailability::Headless,
|prompt| relay.prompt(prompt_to_wire(prompt)),
);
let ended = tokio::select! {
biased;
approved = approved => Ended::Approved(approved),
() = cancel.cancelled() => Ended::Cancelled,
() = relay.closed() => Ended::ClientLeft,
};
let outcome = match ended {
Ended::Approved(Ok(approval)) => save(&target, approval, &sessions).await,
Ended::Approved(Err(error)) => {
tracing::info!(auth, "login failed");
LoginOutcome::Failed {
message: format!("the {} login failed: {error}", target.provider_label),
}
}
Ended::Cancelled => {
tracing::info!(auth, "login cancelled");
LoginOutcome::Cancelled
}
Ended::ClientLeft => {
tracing::info!(auth, "login cancelled: the client that started it left");
return;
}
};
drop(slot);
relay.finish(outcome);
}
async fn save(target: &LoginAuth, approval: Approval, sessions: &Sessions) -> LoginOutcome {
let descriptor = *target.descriptor;
let credentials = Arc::clone(&target.credentials);
let saved = off_workers(move || -> anyhow::Result<()> {
credential_writes::load_config_and_store(&repository())?;
approval.save(descriptor, &repository(), credentials.as_ref())
})
.await;
credentials_changed(sessions).await;
let auth = target.auth;
match saved {
Ok(Ok(())) => {
tracing::info!(auth, "login saved");
LoginOutcome::Succeeded
}
Ok(Err(error)) => {
tracing::warn!(auth, "could not save a login: {error:#}");
LoginOutcome::Failed {
message: format!(
"could not save the {} credentials: {error:#}",
target.provider_label
),
}
}
Err(error) => LoginOutcome::Failed {
message: error.message,
},
}
}