use anyhow::anyhow;
use rho_protocol::{
methods::{AuthChooseStore, AuthKey, AuthLogin, Status},
AuthChooseStoreParams, AuthKeyParams, AuthLoginParams, Client, ClientEnvironment, ClientError,
CredentialStoreKind, DaemonNotification, ErrorCode, LoginOutcome, StatusParams,
StoreSelectedBy,
};
use rho_providers::{
auth::browser::{self, BrowserAvailability},
credentials::CredentialStoreBackend,
};
use super::{
drive,
relay_wire::{flow_to_wire, prompt_from_wire},
secret,
store_choice::{self, StoreOffers},
SignIn, Target,
};
use crate::{
app::{credential_writes, daemon_cli},
credential_store,
daemon::Connection,
login_prompt_print::eprint_login_prompt,
};
pub(super) async fn run(target: Target, device_auth: bool) -> anyhow::Result<()> {
let Target { auth, sign_in, .. } = target;
refuse_shell_override(&auth, |variable| std::env::var(variable).ok())?;
match sign_in {
SignIn::ApiKey { entry_label } => save_key(auth, entry_label).await,
SignIn::Interactive { provider_label } => log_in(auth, provider_label, device_auth).await,
}
}
fn refuse_shell_override(
auth: &str,
environment: impl Fn(&str) -> Option<String>,
) -> anyhow::Result<()> {
match credential_writes::environment_override(auth, environment) {
Some(variable) => anyhow::bail!(
"{variable} is set in this shell and overrides any credential saved for '{auth}', here and in a rho daemon started from here; unset it, then run rho login again"
),
None => Ok(()),
}
}
async fn save_key(auth: String, entry_label: &str) -> anyhow::Result<()> {
let key = secret::read(entry_label).await?;
let Connection { client, .. } = daemon_cli::connect().await?;
let os_store = ensure_store(&client).await?;
let saved = client
.request::<AuthKey>(&AuthKeyParams {
auth: auth.clone(),
key,
environment: ClientEnvironment::of_this_process(),
})
.await
.map_err(|error| {
store_refused(
error,
format!("could not save credentials for {auth}"),
os_store,
)
})?;
match saved.unchecked {
None => eprintln!("saved credentials for {auth}"),
Some(unchecked) => eprintln!(
"saved credentials for {auth} without checking them: {}",
unchecked.message
),
}
Ok(())
}
async fn log_in(auth: String, provider_label: &str, device_auth: bool) -> anyhow::Result<()> {
let availability = BrowserAvailability::from_process();
let flow = flow_to_wire(drive::mode(&auth, device_auth, availability));
let Connection {
client,
mut notifications,
..
} = daemon_cli::connect().await?;
let os_store = ensure_store(&client).await?;
let login = client
.request::<AuthLogin>(&AuthLoginParams {
auth: auth.clone(),
flow: Some(flow),
environment: ClientEnvironment::of_this_process(),
})
.await
.map_err(|error| {
store_refused(
error,
format!("could not start the {provider_label} login"),
os_store,
)
})?
.login;
loop {
let Some(notification) = notifications.recv().await else {
anyhow::bail!(
"lost the connection to the rho daemon during the {provider_label} login"
);
};
match notification {
DaemonNotification::LoginPrompt(params) if params.login == login => {
let prompt = prompt_from_wire(params.prompt);
let opened = browser::try_open(prompt.copyable_url(), availability);
eprint_login_prompt(provider_label, &prompt.with_browser(opened));
}
DaemonNotification::LoginFinished(params) if params.login == login => {
return finished(&auth, params.outcome);
}
_ => {}
}
}
}
async fn ensure_store(client: &Client) -> anyhow::Result<Option<OsStoreChosenBy>> {
match credential_store::environment_backend()? {
Some(CredentialStoreBackend::Os) => return Ok(Some(OsStoreChosenBy::Shell)),
Some(CredentialStoreBackend::File) => return Ok(None),
None => {}
}
let status = client
.request::<Status>(&StatusParams {})
.await
.map_err(|error| {
refused(
error,
"could not ask the rho daemon about its credential store".into(),
)
})?
.credential_store;
if status.selected_by != StoreSelectedBy::Default {
return Ok((status.store == CredentialStoreKind::Os).then_some(
if status.selected_by == StoreSelectedBy::Environment {
OsStoreChosenBy::DaemonEnvironment
} else {
OsStoreChosenBy::Config
},
));
}
let offers = StoreOffers {
os_unavailable: status.unreachable,
file_unavailable: None,
};
let unattended = "the rho daemon's credential store is unset; set it before non-interactive login with `rho credential-store set file` or behavior.credential_store in config.toml, which the daemon reads, or set RHO_CREDENTIAL_STORE=os|file in this shell";
let backend =
tokio::task::spawn_blocking(move || store_choice::ask(&offers, unattended)).await??;
client
.request::<AuthChooseStore>(&AuthChooseStoreParams {
store: credential_store::wire::kind(backend),
environment: ClientEnvironment::of_this_process(),
})
.await
.map_err(|error| {
refused(
error,
format!("could not choose the {} credential store", backend.as_str()),
)
})?;
eprintln!(
"credential store set to {} in the rho daemon's config",
backend.as_str()
);
Ok(match backend {
CredentialStoreBackend::Os => Some(OsStoreChosenBy::Config),
CredentialStoreBackend::File => None,
})
}
#[derive(Clone, Copy, Debug)]
enum OsStoreChosenBy {
Shell,
DaemonEnvironment,
Config,
}
fn store_refused(
error: ClientError,
doing: String,
os_store: Option<OsStoreChosenBy>,
) -> anyhow::Error {
let unreachable = error.error_code() == Some(ErrorCode::CredentialStoreUnavailable);
let advice = match os_store.filter(|_| unreachable) {
Some(OsStoreChosenBy::Shell) => "set RHO_CREDENTIAL_STORE=file in this shell",
Some(OsStoreChosenBy::DaemonEnvironment) => {
"restart the rho daemon with RHO_CREDENTIAL_STORE=file in its environment"
}
Some(OsStoreChosenBy::Config) => "run `rho credential-store set file`",
None => return refused(error, doing),
};
anyhow!(
"{doing}: {error}\nto keep credentials in a private file instead, {advice}, then run rho login again"
)
}
fn finished(auth: &str, outcome: LoginOutcome) -> anyhow::Result<()> {
match outcome {
LoginOutcome::Succeeded => {
eprintln!("Saved the {auth} credential");
Ok(())
}
LoginOutcome::Failed { message } => anyhow::bail!("{message}"),
LoginOutcome::Cancelled => anyhow::bail!("the login to {auth} was cancelled"),
_ => anyhow::bail!(
"the login to {auth} ended in a way this rho does not know; is the daemon newer than this rho?"
),
}
}
fn refused(error: ClientError, doing: String) -> anyhow::Error {
match error.error_code() {
Some(ErrorCode::MethodNotFound) => anyhow!(
"{doing}: the running rho daemon is older than this rho and cannot sign in; stop it with `rho daemon stop`, then run rho login again to start this rho's daemon"
),
_ => anyhow::Error::new(error).context(doing),
}
}
#[cfg(test)]
#[path = "daemon_client_tests.rs"]
mod tests;