Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Add account creation and authenticator enrollment

Manav Rathi27b06648f303
diff --git a/rust/apps/cli-next/src/account.rs b/rust/apps/cli-next/src/account.rs
new file mode 100644
index 0000000000..ec2f10f99d
--- /dev/null
+++ b/rust/apps/cli-next/src/account.rs
@@ -0,0 +1,342 @@
+use std::{collections::BTreeMap, io::Write};
+
+use anyhow::{Context, Result, ensure};
+use dialoguer::{Confirm, Password, console::Term};
+use ente_accounts::{DEFAULT_API_ORIGIN, lifecycle::TwoFactorSetup, signup::Signup};
+use ente_core::{b64, crypto::Key};
+use serde::{Deserialize, Serialize};
+use serde_json::json;
+use uuid::Uuid;
+use zeroize::{ZeroizeOnDrop, Zeroizing};
+
+use crate::{
+ api,
+ args::{App, CreateArgs, Options, TotpCommand, VerificationPurpose},
+ login::{self, Credentials},
+ output, parse_json, read_input,
+ vault::{Account, DbKey, State, Vault},
+};
+
+#[derive(Clone, Serialize, Deserialize)]
+pub struct PendingCreation {
+ origin: String,
+ app: App,
+ name: Option<String>,
+ signup: Signup,
+}
+
+pub async fn request_otp(
+ email: Option<String>,
+ app: App,
+ host: Option<String>,
+ purpose: VerificationPurpose,
+ options: &Options,
+) -> Result<()> {
+ ensure!(
+ !options.offline,
+ "requesting verification requires network access"
+ );
+ let origin = origin(host.as_deref())?;
+ ensure!(
+ email.is_some() || options.can_prompt(),
+ "request-otp requires --email when prompts are disabled"
+ );
+ let email = login::email(email, None, options.can_prompt())?;
+ api::accounts_client(&origin, app)?
+ .send_otp(
+ &email,
+ match purpose {
+ VerificationPurpose::Create => "signup",
+ VerificationPurpose::Login => "login",
+ },
+ )
+ .await?;
+ output::action(
+ options.json,
+ &json!({"email": email, "host": origin, "app": app, "purpose": purpose, "verificationRequested": true}),
+ &format!(
+ "Verification requested for {}. Check your email.",
+ output::escape_controls(&email)
+ ),
+ )
+}
+
+pub async fn create(args: CreateArgs, options: &Options) -> Result<(State, usize)> {
+ ensure!(!options.offline, "account creation requires network access");
+ let origin = origin(args.host.as_deref())?;
+ let mut credentials = args.input.as_deref().map(Credentials::read).transpose()?;
+ let interactive = credentials.is_none() && options.can_prompt();
+ ensure!(
+ credentials.is_some() || interactive,
+ "creation requires password and otp; supply --input PATH or --input - and --accept-terms"
+ );
+ ensure!(
+ args.accept_terms || interactive,
+ "account creation requires --accept-terms"
+ );
+ let email = login::email(
+ args.email,
+ credentials
+ .as_ref()
+ .and_then(|input| input.email.as_deref()),
+ interactive,
+ )?;
+ if !args.accept_terms {
+ ensure!(
+ Confirm::new()
+ .with_prompt("Agree to Ente's terms and privacy policy?")
+ .default(false)
+ .interact_on(&Term::stderr())?,
+ "cancelled"
+ );
+ }
+ let vault = Vault::open()?;
+ let pending = vault
+ .state
+ .creations
+ .iter()
+ .find(|pending| pending.origin == origin && pending.signup.email == email)
+ .cloned();
+ if let Some(pending) = &pending {
+ ensure!(
+ pending.app == args.app,
+ "unfinished creation uses {}; resume with --app {}",
+ pending.app.display_name(),
+ pending.app.name()
+ );
+ }
+ let name = args
+ .name
+ .or_else(|| pending.as_ref().and_then(|pending| pending.name.clone()));
+ check_creation(
+ &vault.state,
+ &origin,
+ &email,
+ name.as_deref().unwrap_or(&email),
+ )?;
+ let access = vault.release();
+ let client = api::accounts_client(&origin, args.app)?;
+ let resuming = pending.is_some();
+ let signup = if let Some(pending) = pending {
+ pending.signup
+ } else {
+ if interactive {
+ client.send_otp(&email, "signup").await?;
+ eprintln!("Verification requested. Check your email.");
+ }
+ let mut supplied = credentials.as_mut().and_then(|input| input.otp.take());
+ let response = loop {
+ let code = Zeroizing::new(if interactive {
+ Password::new()
+ .with_prompt("Email verification code")
+ .interact_on(&Term::stderr())?
+ } else {
+ supplied.take().context("creation requires otp in --input; request it with account request-otp --email EMAIL")?
+ });
+ match client.verify_email(&email, &code, None).await {
+ Ok(response) => break response,
+ Err(ente_accounts::Error::IncorrectEmailVerificationCode) if interactive => {
+ eprintln!("Incorrect email verification code. Try again.")
+ }
+ Err(error) => return Err(error.into()),
+ }
+ };
+ Signup::verified(email.clone(), response)
+ .context("cannot create this account; use account login for an existing account")?
+ };
+ let password = Zeroizing::new(match credentials.as_mut() {
+ Some(input) => std::mem::take(&mut input.password),
+ None => {
+ let prompt = Password::new().with_prompt("Password");
+ if resuming {
+ prompt
+ } else {
+ prompt.with_confirmation("Confirm password", "Passwords do not match")
+ }
+ .interact_on(&Term::stderr())?
+ }
+ });
+ let signup = signup.prepare(&client, &password).await?;
+ let mut vault = access.open()?;
+ check_creation(
+ &vault.state,
+ &origin,
+ &email,
+ name.as_deref().unwrap_or(&email),
+ )?;
+ let current = vault
+ .state
+ .creations
+ .iter()
+ .position(|pending| pending.origin == origin && pending.signup.email == email);
+ if resuming {
+ let current =
+ current.context("unfinished creation changed; inspect account list and retry")?;
+ ensure!(
+ vault.state.creations[current].signup.user_id == signup.user_id
+ && vault.state.creations[current].app == args.app,
+ "unfinished creation changed; retry"
+ );
+ vault.state.creations[current].name = name.clone();
+ } else {
+ ensure!(
+ current.is_none(),
+ "another creation was saved for this email; retry to resume it"
+ );
+ vault.state.creations.push(PendingCreation {
+ origin: origin.clone(),
+ app: args.app,
+ name: name.clone(),
+ signup: signup.clone(),
+ });
+ }
+ vault.save()?;
+ let access = vault.release();
+ let mut authenticated = signup.finish(&client).await?;
+ let email = client.email().await?;
+ let (identity, session) = login::saved_keys(&mut authenticated)?;
+ let mut vault = access.open()?;
+ let pending = vault
+ .state
+ .creations
+ .iter()
+ .position(|pending| {
+ pending.origin == origin
+ && pending.signup.user_id == signup.user_id
+ && pending.app == args.app
+ })
+ .context("unfinished creation changed; inspect account list and retry")?;
+ let name = vault.state.creations[pending]
+ .name
+ .clone()
+ .unwrap_or_else(|| email.clone());
+ check_creation(&vault.state, &origin, &email, &name)?;
+ ensure!(
+ !vault
+ .state
+ .accounts
+ .iter()
+ .any(|account| account.origin == origin && account.user_id == authenticated.user_id),
+ "account already exists on this device; use account login"
+ );
+ let index = vault.state.accounts.len();
+ let storage_id = Uuid::new_v4();
+ vault.state.accounts.push(Account {
+ storage_id,
+ db_key: DbKey(*Key::generate().as_bytes()),
+ name,
+ email,
+ origin,
+ user_id: authenticated.user_id,
+ identity,
+ sessions: BTreeMap::from([(args.app, session)]),
+ });
+ vault.state.selected = Some(storage_id);
+ vault.state.creations.remove(pending);
+ vault.save()?;
+ Ok((vault.into_state(), index))
+}
+
+fn origin(host: Option<&str>) -> Result<String> {
+ host.map(api::normalize_host)
+ .transpose()
+ .map(|host| host.unwrap_or_else(|| DEFAULT_API_ORIGIN.to_owned()))
+}
+
+fn check_creation(state: &State, origin: &str, email: &str, name: &str) -> Result<()> {
+ ensure!(
+ !state
+ .accounts
+ .iter()
+ .any(|account| account.origin == origin && account.email == email),
+ "account already exists on this device; use account login"
+ );
+ state.check_name(name)
+}
+
+pub async fn totp(
+ command: TotpCommand,
+ selected: Option<&str>,
+ app: Option<App>,
+ options: &Options,
+) -> Result<()> {
+ ensure!(
+ !options.offline,
+ "authenticator setup and status require network access"
+ );
+ let input = match &command {
+ TotpCommand::Enable { input } => {
+ ensure!(
+ input.is_some() || options.can_prompt(),
+ "supply secret and totp in --input PATH or --input -"
+ );
+ input
+ .as_deref()
+ .map(|path| {
+ parse_json::<Confirmation>(&read_input(path, u64::MAX)?)
+ .context("input must contain secret and totp strings")
+ })
+ .transpose()?
+ }
+ _ => None,
+ };
+ if let Some(input) = &input {
+ ensure!(
+ !input.secret.is_empty(),
+ "supply a nonempty secret in --input"
+ );
+ ensure!(!input.totp.is_empty(), "supply a nonempty totp in --input");
+ }
+ let state = State::load()?;
+ let account = &state.accounts[state.resolve(selected)?];
+ let app = account.app(app)?;
+ let client = api::accounts_client(&account.origin, app)?;
+ client.set_auth_token(Some(b64::encode_url_safe(account.token(app)?)));
+ let enabled = client.get_two_factor_status().await?;
+ if matches!(command, TotpCommand::Status) {
+ return output::action(
+ options.json,
+ &json!({"enabled": enabled}),
+ if enabled {
+ "Authenticator protection is enabled."
+ } else {
+ "Authenticator protection is disabled."
+ },
+ );
+ }
+ ensure!(!enabled, "authenticator protection is already enabled");
+ let secret = Zeroizing::new(match &input {
+ Some(input) => input.secret.clone(),
+ None => client.setup_two_factor().await?.secret_code,
+ });
+ if matches!(command, TotpCommand::Setup) {
+ return if options.json {
+ output::json(&json!({"secret": secret.as_str()}))
+ } else {
+ writeln!(std::io::stdout(), "{}", secret.as_str()).map_err(Into::into)
+ };
+ }
+ let code = Zeroizing::new(match input {
+ Some(mut input) => std::mem::take(&mut input.totp),
+ None => {
+ eprintln!("Add this secret to your authenticator: {}", secret.as_str());
+ Password::new()
+ .with_prompt("Authenticator code")
+ .interact_on(&Term::stderr())?
+ }
+ });
+ let setup = TwoFactorSetup::from_secret(secret.to_string(), &account.identity.recovery_key);
+ setup.enable(&client, &code).await?;
+ output::action(
+ options.json,
+ &json!({"enabled": true}),
+ "Authenticator protection is enabled.",
+ )
+}
+
+#[derive(Deserialize, ZeroizeOnDrop)]
+#[serde(deny_unknown_fields)]
+struct Confirmation {
+ secret: String,
+ totp: String,
+}
diff --git a/rust/apps/cli-next/src/admin.rs b/rust/apps/cli-next/src/admin.rs
index 5ba729ee54..fcb2b72302 100644
--- a/rust/apps/cli-next/src/admin.rs
+++ b/rust/apps/cli-next/src/admin.rs
@@ -47,24 +47,14 @@ pub async fn run(
}
let state = State::load()?;
let account = &state.accounts[state.resolve(selected)?];
- let mut saved_apps = account.sessions.keys();
- let app = match (app, saved_apps.next(), saved_apps.next()) {
- (Some(app), _, _) | (None, Some(&app), None) => app,
- _ => {
- ensure!(
- account.sessions.contains_key(&App::Photos),
- "multiple apps are saved without Photos; select one with --app"
- );
- App::Photos
- }
- };
+ let app = account.app(app)?;
let client = api::accounts_client(&account.origin, app)?;
client.set_auth_token(Some(ente_core::b64::encode_url_safe(account.token(app)?)));
execute(command, &client, account, options).await.map_err(|error| {
if matches!(error.downcast_ref::<ente_accounts::Error>(),
Some(ente_accounts::Error::Http(ente_core::http::Error::Api { status: 400, message: Some(message), .. }))
if message == "Token is too old") {
- error.context(format!("administrator login is too old; run account login {:?} --app {} and retry", account.name, app.name()))
+ error.context(format!("administrator login is too old; run account login --account {:?} --app {} and retry", account.name, app.name()))
} else {
error
}
diff --git a/rust/apps/cli-next/src/args.rs b/rust/apps/cli-next/src/args.rs
index 6e1977a771..84b5078f7b 100644
--- a/rust/apps/cli-next/src/args.rs
+++ b/rust/apps/cli-next/src/args.rs
@@ -357,8 +357,14 @@ pub enum LockerCommand {
#[derive(Args)]
pub struct LoginArgs {
- #[arg(help = "Local account name; creates an entry if it does not exist")]
+ #[arg(
+ long = "account",
+ value_name = "NAME",
+ help = "Local account name; creates an entry if it does not exist"
+ )]
pub name: Option<String>,
+ #[arg(long, help = "Email address to log in with")]
+ pub email: Option<String>,
#[arg(long, value_enum, help = "App to log in to")]
pub app: App,
#[arg(
@@ -373,6 +379,37 @@ pub struct LoginArgs {
pub input: Option<PathBuf>,
}
+#[derive(Args)]
+pub struct CreateArgs {
+ #[arg(
+ long = "account",
+ value_name = "NAME",
+ help = "Local name for the new account; defaults to its email"
+ )]
+ pub name: Option<String>,
+ #[arg(long, help = "Email address for the new account")]
+ pub email: Option<String>,
+ #[arg(long, value_enum, default_value = "photos", help = "App to log in to")]
+ pub app: App,
+ #[arg(long, help = "Ente server; defaults to api.ente.com")]
+ pub host: Option<String>,
+ #[arg(
+ long,
+ value_name = "PATH|-",
+ help = "Read creation credentials as JSON from a file or stdin"
+ )]
+ pub input: Option<PathBuf>,
+ #[arg(long, help = "Accept Ente's terms and privacy policy")]
+ pub accept_terms: bool,
+}
+
+#[derive(Clone, Copy, ValueEnum, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum VerificationPurpose {
+ Create,
+ Login,
+}
+
const API_HELP: &str = "The response body is written unchanged, including when --json is set.";
#[derive(Args)]
@@ -456,32 +493,74 @@ pub enum AccountCommand {
#[command(
about = "Log an account into an app",
after_long_help = "An existing name requires matching credentials; a new name creates a local entry.
-Omit NAME to use the selected account, or the only saved account.
+Omit --account to use the selected account, or the only saved account.
With no saved accounts, creates an entry named after the authenticated email.
-With several accounts and none selected, supply NAME or use account switch.
+With several accounts and none selected, supply --account or use account switch.
A new entry becomes selected; logging into an existing entry keeps the selection.
Non-interactive login reads JSON from --input:
{\"email\": \"...\", \"password\": \"...\", \"otp\": \"123456\", \"totp\": \"654321\"}
-All fields are strings. otp is the email code; totp is the authenticator code. Supply them when required.
+All fields are strings. --email can supply the email instead. otp is the email code; totp is the authenticator code.
+Request an email code with account request-otp --email EMAIL --purpose login.
With --no-input, supply email and password through --input PATH or --input -.
For unattended vault access, set ENTE_CLI_VAULT_KEY (see vault --help)."
)]
Login(LoginArgs),
+ #[command(
+ about = "Request an email verification code",
+ after_long_help = "Requests one email and returns; success means the server accepted the request.
+Use the same email, app and server when completing creation or login.
+Defaults to creation; use --purpose login for an existing account."
+ )]
+ RequestOtp {
+ #[arg(long, help = "Email address to verify")]
+ email: Option<String>,
+ #[arg(
+ long,
+ value_enum,
+ default_value = "photos",
+ help = "App requesting verification"
+ )]
+ app: App,
+ #[arg(long, help = "Ente server; defaults to api.ente.com")]
+ host: Option<String>,
+ #[arg(
+ long,
+ value_enum,
+ default_value = "create",
+ help = "Reason for verification"
+ )]
+ purpose: VerificationPurpose,
+ },
+ #[command(
+ about = "Create an Ente account",
+ after_long_help = "Creates and selects a new account, named after its email unless --account is supplied.
+Prompts for email, consent, verification code and password.
+Unattended creation requires --accept-terms and --input with email, password and otp strings.
+--email can supply the email instead. Request the code first with account request-otp.
+Repeating an unfinished creation resumes with its saved keys and the same password.
+Terms: https://ente.io/terms Privacy: https://ente.io/privacy
+Print the recovery key later with account recovery-key."
+ )]
+ Create(CreateArgs),
#[command(about = "List accounts on this device")]
#[command(after_long_help = ACCOUNT_HELP)]
List,
#[command(about = "Show an account")]
#[command(after_long_help = ACCOUNT_HELP)]
View {
- #[arg(help = "Account name; defaults to the selected or only saved account")]
+ #[arg(
+ long = "account",
+ value_name = "NAME",
+ help = "Account name; defaults to the selected or only saved account"
+ )]
name: Option<String>,
},
#[command(about = "Print the saved API token for an account")]
#[command(
- after_long_help = "Uses NAME, otherwise the selected account, otherwise the only saved account.
-With several accounts and none selected, supply NAME or use account switch.
+ after_long_help = "Uses --account, otherwise the selected account, otherwise the only saved account.
+With several accounts and none selected, supply --account or use account switch.
--app is required and selects that account's saved login.
Reads the saved token from the local vault without contacting the server or refreshing it.
This prints a secret and does not check whether the server still accepts it.
@@ -489,7 +568,11 @@ Plain output is padded URL-safe Base64 followed by a newline.
With --json, returns {\"token\":\"...\"}."
)]
Token {
- #[arg(help = "Account name; defaults to the selected or only saved account")]
+ #[arg(
+ long = "account",
+ value_name = "NAME",
+ help = "Account name; defaults to the selected or only saved account"
+ )]
name: Option<String>,
#[arg(long, value_enum, help = "App whose token to print")]
app: App,
@@ -499,12 +582,18 @@ With --json, returns {\"token\":\"...\"}."
#[arg(help = "Account name")]
name: String,
},
- #[command(about = "Change an account's local name")]
+ #[command(
+ about = "Change an account's local name",
+ after_help = "With one name, renames the selected or only account. With two, renames OLD_NAME to NEW_NAME."
+ )]
Rename {
- #[arg(value_name = "OLD_NAME", help = "Current local name")]
+ #[arg(
+ value_name = "NAME",
+ help = "New name, or current name when supplying two names"
+ )]
name: String,
#[arg(value_name = "NEW_NAME", help = "New local name")]
- new_name: String,
+ new_name: Option<String>,
},
#[command(
about = "Log out of an app, or every app when --app is omitted",
@@ -513,7 +602,11 @@ Without --app, logs out of all this account's saved app logins on this device.
--local removes the account and its cached data without contacting the server."
)]
Logout {
- #[arg(help = "Account name; defaults to the selected or only saved account")]
+ #[arg(
+ long = "account",
+ value_name = "NAME",
+ help = "Account name; defaults to the selected or only saved account"
+ )]
name: Option<String>,
#[arg(
long,
@@ -528,6 +621,56 @@ Without --app, logs out of all this account's saved app logins on this device.
)]
local: bool,
},
+ #[command(
+ about = "Set up authenticator protection for your Ente account",
+ after_long_help = "Protects account login, separate from codes stored in Ente Auth.
+Use enable interactively, or setup then enable --input with secret and totp strings.
+Setup secrets expire after ten minutes. If confirmation is interrupted, check status.
+--app chooses a saved login: the only app, otherwise Photos. Requires network access."
+ )]
+ Totp {
+ #[command(flatten)]
+ selector: AccountSelector,
+ #[arg(
+ long,
+ global = true,
+ value_enum,
+ help = "Saved app login to authenticate with"
+ )]
+ app: Option<App>,
+ #[command(subcommand)]
+ command: TotpCommand,
+ },
+ #[command(
+ about = "Print the saved 24-word recovery key",
+ after_long_help = "Prints a secret from the local vault without network access.
+With --json, returns {\"recoveryKey\":\"...\"}."
+ )]
+ RecoveryKey {
+ #[arg(
+ long = "account",
+ value_name = "NAME",
+ help = "Account name; defaults to the selected or only saved account"
+ )]
+ name: Option<String>,
+ },
+}
+
+#[derive(Subcommand)]
+pub enum TotpCommand {
+ #[command(about = "Print a new authenticator setup secret")]
+ Setup,
+ #[command(about = "Confirm and enable authenticator protection")]
+ Enable {
+ #[arg(
+ long,
+ value_name = "PATH|-",
+ help = "Read secret and totp strings as JSON from a file or stdin"
+ )]
+ input: Option<PathBuf>,
+ },
+ #[command(about = "Show whether authenticator protection is enabled")]
+ Status,
}
#[derive(Subcommand)]
@@ -547,7 +690,7 @@ pub enum KeyCommand {
const ADMIN_HELP: &str =
"Uses the selected account's server and saved login; the server grants administrator access.
-Log in with: ente-cli-next account login NAME --app photos --host URL
+Log in with: ente-cli-next account login --account NAME --app photos --host URL
--account selects a saved account by name; otherwise uses the selected or sole account.
--app selects its session; otherwise uses the sole saved app, then Photos.
With multiple apps and no Photos login, supply --app.
diff --git a/rust/apps/cli-next/src/login.rs b/rust/apps/cli-next/src/login.rs
index 66603fd6a0..6cda4a1324 100644
--- a/rust/apps/cli-next/src/login.rs
+++ b/rust/apps/cli-next/src/login.rs
@@ -27,6 +27,13 @@ pub async fn login(args: LoginArgs, options: &Options) -> Result<(State, usize)>
credentials.is_some() || interactive,
"login requires email and password; supply --input <file> or --input -"
);
+ let email = email(
+ args.email,
+ credentials
+ .as_ref()
+ .and_then(|input| input.email.as_deref()),
+ interactive,
+ )?;
let vault = Vault::open()?;
let index = if let Some(name) = args.name.as_deref() {
vault
@@ -63,10 +70,17 @@ pub async fn login(args: LoginArgs, options: &Options) -> Result<(State, usize)>
.context("cannot reach the selected Ente server")?;
let mut credentials = match credentials {
Some(credentials) => credentials,
- None => Credentials::prompt()?,
+ None => Credentials {
+ email: None,
+ password: Password::new()
+ .with_prompt("Password")
+ .interact_on(&Term::stderr())?,
+ otp: None,
+ totp: None,
+ },
};
let client = api::accounts_client(&origin, app)?;
- let mut authenticated = authenticate(&client, &mut credentials, interactive).await?;
+ let mut authenticated = authenticate(&client, email, &mut credentials, interactive).await?;
client.set_auth_token(Some(ente_core::b64::encode_url_safe(
&authenticated.secrets.token,
)));
@@ -92,20 +106,7 @@ pub async fn login(args: LoginArgs, options: &Options) -> Result<(State, usize)>
"authenticated identity does not match the saved account"
);
}
- let recovery_key = Zeroizing::new(
- authenticated
- .recovery_key
- .take()
- .context("account has no recovery key")?,
- );
- let identity = AccountKeys {
- master_key: std::mem::take(&mut authenticated.secrets.master_key),
- recovery_key: auth::recovery_key_from_mnemonic_or_hex(&recovery_key)?.into_vec(),
- secret_key: std::mem::take(&mut authenticated.secrets.secret_key),
- };
- let session = StoredSession {
- token: std::mem::take(&mut authenticated.secrets.token),
- };
+ let (identity, session) = saved_keys(&mut authenticated)?;
let index = if let Some(index) = existing {
ensure!(
expected.is_some() || args.name.is_none(),
@@ -158,39 +159,89 @@ pub async fn login(args: LoginArgs, options: &Options) -> Result<(State, usize)>
#[derive(Deserialize, ZeroizeOnDrop)]
#[serde(deny_unknown_fields)]
-struct Credentials {
- email: String,
- password: String,
- otp: Option<String>,
- totp: Option<String>,
+pub(crate) struct Credentials {
+ pub email: Option<String>,
+ #[serde(default)]
+ pub password: String,
+ pub otp: Option<String>,
+ pub totp: Option<String>,
}
impl Credentials {
- fn read(path: &Path) -> Result<Self> {
- parse_json(&read_input(path, u64::MAX)?)
- .context("login input must contain email and password, with optional otp and totp")
+ pub fn read(path: &Path) -> Result<Self> {
+ let input: Self = parse_json(&read_input(path, u64::MAX)?)
+ .context("input must contain email and password strings, with optional otp and totp; --email can supply email")?;
+ ensure!(
+ !input.password.is_empty(),
+ "supply a nonempty password in --input"
+ );
+ Ok(input)
}
+}
- fn prompt() -> Result<Self> {
- Ok(Self {
- email: Input::new()
+pub(crate) fn email(
+ flag: Option<String>,
+ input: Option<&str>,
+ interactive: bool,
+) -> Result<String> {
+ ensure!(
+ flag.as_deref()
+ .zip(input)
+ .is_none_or(|(flag, input)| flag.trim().to_lowercase() == input.trim().to_lowercase()),
+ "--email differs from email in --input"
+ );
+ let email = match flag.or_else(|| input.map(str::to_owned)) {
+ Some(email) => email,
+ None => {
+ ensure!(interactive, "supply email through --email or --input");
+ Input::new()
.with_prompt("Email")
- .interact_on(&Term::stderr())?,
- password: Password::new()
- .with_prompt("Password")
- .interact_on(&Term::stderr())?,
- otp: None,
- totp: None,
- })
- }
+ .interact_on(&Term::stderr())?
+ }
+ };
+ let email = email.trim().to_lowercase();
+ ensure!(!email.is_empty(), "email cannot be empty");
+ Ok(email)
+}
+
+pub(crate) fn saved_keys(
+ authenticated: &mut AuthenticatedAccount,
+) -> Result<(AccountKeys, StoredSession)> {
+ let recovery_key = Zeroizing::new(
+ authenticated
+ .recovery_key
+ .take()
+ .context("account has no recovery key")?,
+ );
+ Ok((
+ AccountKeys {
+ master_key: std::mem::take(&mut authenticated.secrets.master_key),
+ recovery_key: auth::recovery_key_from_mnemonic_or_hex(&recovery_key)?.into_vec(),
+ secret_key: std::mem::take(&mut authenticated.secrets.secret_key),
+ },
+ StoredSession {
+ token: std::mem::take(&mut authenticated.secrets.token),
+ },
+ ))
}
async fn authenticate(
client: &AccountsClient,
+ email: String,
credentials: &mut Credentials,
interactive: bool,
) -> Result<AuthenticatedAccount> {
- let (mut flow, mut step) = LoginFlow::start(client, credentials.email.clone()).await?;
+ let (mut flow, mut step) = LoginFlow::prepare(client, email).await?;
+ if matches!(step, LoginStep::EmailCode) {
+ if interactive {
+ flow.resend_code(client).await?;
+ } else {
+ ensure!(
+ credentials.otp.is_some(),
+ "login requires otp in --input; request it with account request-otp --email EMAIL --purpose login"
+ );
+ }
+ }
loop {
step = match step {
LoginStep::EmailCode => loop {
diff --git a/rust/apps/cli-next/src/main.rs b/rust/apps/cli-next/src/main.rs
index d75f2c6d94..f5367fcea7 100644
--- a/rust/apps/cli-next/src/main.rs
+++ b/rust/apps/cli-next/src/main.rs
@@ -1,3 +1,4 @@
+mod account;
mod admin;
mod api;
mod args;
@@ -112,6 +113,43 @@ fn vault_key(json_output: bool) -> Result<()> {
async fn account_command(command: AccountCommand, options: &Options) -> Result<()> {
match command {
+ AccountCommand::RequestOtp {
+ email,
+ app,
+ host,
+ purpose,
+ } => account::request_otp(email, app, host, purpose, options).await,
+ AccountCommand::Create(args) => {
+ let app = args.app;
+ let (state, index) = account::create(args, options).await?;
+ let account = AccountView::new(&state.accounts[index], state.selected);
+ output::action(
+ options.json,
+ &json!({"account": account, "app": app, "created": true}),
+ &format!(
+ "Created {} and signed into {}.",
+ output::escape_controls(&state.accounts[index].name),
+ app.display_name()
+ ),
+ )
+ }
+ AccountCommand::Totp {
+ selector,
+ app,
+ command,
+ } => account::totp(command, selector.account.as_deref(), app, options).await,
+ AccountCommand::RecoveryKey { name } => {
+ let state = State::load()?;
+ let account = &state.accounts[state.resolve(name.as_deref())?];
+ let key = Zeroizing::new(ente_accounts::auth::recovery_key_to_mnemonic(
+ &account.identity.recovery_key,
+ )?);
+ if options.json {
+ output::json(&json!({"recoveryKey": key.as_str()}))
+ } else {
+ writeln!(std::io::stdout(), "{}", key.as_str()).map_err(Into::into)
+ }
+ }
AccountCommand::Login(args) => {
ensure!(!options.offline, "login requires network access");
let app = args.app;
@@ -165,8 +203,11 @@ async fn account_command(command: AccountCommand, options: &Options) -> Result<(
AccountCommand::Rename { name, new_name } => {
let mut vault = Vault::open()?;
let state = &mut vault.state;
- let index = state.named(&name)?;
- if name != new_name {
+ let (index, new_name) = match new_name {
+ Some(new_name) => (state.named(&name)?, new_name),
+ None => (state.resolve(None)?, name),
+ };
+ if state.accounts[index].name != new_name {
state.check_name(&new_name)?;
state.accounts[index].name = new_name;
vault.save()?;
diff --git a/rust/apps/cli-next/src/vault.rs b/rust/apps/cli-next/src/vault.rs
index f4c42da63a..5ba99bd0e1 100644
--- a/rust/apps/cli-next/src/vault.rs
+++ b/rust/apps/cli-next/src/vault.rs
@@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize};
use uuid::Uuid;
use zeroize::{ZeroizeOnDrop, Zeroizing};
-use crate::{args::App, home, parse_json};
+use crate::{account::PendingCreation, args::App, home, parse_json};
const SCHEMA_VERSION: u8 = 1;
const VAULT_FILE: &str = "vault.json";
@@ -36,6 +36,8 @@ pub(crate) struct VaultAccess {
pub struct State {
pub accounts: Vec<Account>,
pub selected: Option<Uuid>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub creations: Vec<PendingCreation>,
}
#[derive(Serialize, Deserialize)]
@@ -205,13 +207,27 @@ impl State {
}
impl Account {
+ pub fn app(&self, requested: Option<App>) -> Result<App> {
+ let mut apps = self.sessions.keys();
+ match (requested, apps.next(), apps.next()) {
+ (Some(app), _, _) | (None, Some(&app), None) => Ok(app),
+ _ => {
+ ensure!(
+ self.sessions.contains_key(&App::Photos),
+ "multiple apps are saved without Photos; select one with --app"
+ );
+ Ok(App::Photos)
+ }
+ }
+ }
+
pub fn token(&self, app: App) -> Result<&[u8]> {
self.sessions
.get(&app)
.map(|s| s.token.as_slice())
.with_context(|| {
format!(
- "account {:?} is not logged into {}; use account login {:?} --app {}",
+ "account {:?} is not logged into {}; use account login --account {:?} --app {}",
self.name,
app.display_name(),
self.name,
diff --git a/rust/apps/cli-next/tests/cli.rs b/rust/apps/cli-next/tests/cli.rs
index 3c7f5e44c8..bef8270015 100644
--- a/rust/apps/cli-next/tests/cli.rs
+++ b/rust/apps/cli-next/tests/cli.rs
@@ -91,7 +91,7 @@ fn reads_do_not_initialize_storage() {
assert_eq!(success(output).stdout, b"No accounts on this device.\n");
for args in [
vec!["accounts", "list", "--json"],
- vec!["accounts", "view", "missing"],
+ vec!["accounts", "view", "--account", "missing"],
vec!["account", "token", "--app", "photos"],
vec!["photos", "album", "list"],
vec!["photos", "album", "view", "missing"],
@@ -461,7 +461,7 @@ fn private_json_errors_do_not_echo_values() {
);
assert!(output.stdout.is_empty());
let error = failure(&output);
- assert!(error.contains("login input must contain"), "{error}");
+ assert!(error.contains("input must contain"), "{error}");
errors.push(error);
}
assert_eq!(fs::read_dir(home.dir.path()).unwrap().count(), 0);
@@ -523,7 +523,7 @@ fn logout_reconciles_remote_and_local_session_state() {
let home = TestHome::new();
home.seed(&server.url());
let mut state = home.read_vault();
- let mut account = home.json(&["account", "view", "fixture"]);
+ let mut account = home.json(&["account", "view", "--account", "fixture"]);
assert_eq!(
success(home.run(&["account", "logout", "--app", "photos"])).stdout,
b"Logged out of Ente Photos. Removed account \"fixture\" from this device.\n"
@@ -543,7 +543,10 @@ fn logout_reconciles_remote_and_local_session_state() {
home.json(&["account", "logout", "--app", "photos"]),
json!({"account": account, "app": "photos", "remoteLogout": true})
);
- assert_eq!(home.json(&["account", "view", "fixture"]), account);
+ assert_eq!(
+ home.json(&["account", "view", "--account", "fixture"]),
+ account
+ );
state["accounts"][0]["sessions"]
.as_object_mut()
.unwrap()
@@ -583,7 +586,7 @@ fn account_logout_revokes_every_app_before_removing_the_account() {
state["accounts"][0]["sessions"]["locker"] = json!({"token": [1]});
state["accounts"][0]["sessions"]["auth"] = json!({"token": [2]});
home.write_vault(&state);
- let mut account = home.json(&["account", "view", "fixture"]);
+ let mut account = home.json(&["account", "view", "--account", "fixture"]);
account["apps"] = json!([]);
account["selected"] = json!(false);
let photos = server
@@ -608,29 +611,36 @@ fn account_logout_revokes_every_app_before_removing_the_account() {
.create();
assert_eq!(
- success(home.run(&["account", "logout", "fixture"])).stdout,
+ success(home.run(&["account", "logout", "--account", "fixture"])).stdout,
b"Logged out of Ente Photos, Ente Locker, and Ente Auth. Removed account \"fixture\" from this device.\n"
);
assert_eq!(home.read_vault(), json!({"accounts": [], "selected": null}));
home.write_vault(&state);
assert_eq!(
- home.json(&["account", "logout", "fixture"]),
+ home.json(&["account", "logout", "--account", "fixture"]),
json!({"account": account, "apps": ["photos", "locker", "auth"], "remoteLogout": true})
);
home.write_vault(&state);
assert_eq!(
- home.json(&["account", "logout", "fixture", "--local", "--offline"]),
+ home.json(&[
+ "account",
+ "logout",
+ "--account",
+ "fixture",
+ "--local",
+ "--offline"
+ ]),
json!({"account": account, "apps": ["photos", "locker", "auth"], "remoteLogout": false})
);
state["accounts"][0]["sessions"] = json!({});
home.write_vault(&state);
assert_eq!(
- home.json(&["account", "logout", "fixture"]),
+ home.json(&["account", "logout", "--account", "fixture"]),
json!({"account": account, "apps": [], "remoteLogout": true})
);
home.write_vault(&state);
assert_eq!(
- success(home.run(&["account", "logout", "fixture", "--local"])).stdout,
+ success(home.run(&["account", "logout", "--account", "fixture", "--local"])).stdout,
b"Removed account \"fixture\" from this device.\n"
);
assert_eq!(home.read_vault(), json!({"accounts": [], "selected": null}));
@@ -663,7 +673,7 @@ fn account_logout_preserves_sessions_that_it_could_not_revoke() {
.expect(0)
.create();
- let output = home.run(&["account", "logout", "fixture"]);
+ let output = home.run(&["account", "logout", "--account", "fixture"]);
assert!(output.stdout.is_empty());
let error = failure(&output);
assert!(error.contains("cannot log out of Ente Locker for \"fixture\": HTTP 403"));
@@ -675,7 +685,7 @@ fn account_logout_preserves_sessions_that_it_could_not_revoke() {
assert!(sessions.get("auth").is_some());
assert_eq!(
- success(home.run(&["account", "logout", "fixture", "--local"])).stdout,
+ success(home.run(&["account", "logout", "--account", "fixture", "--local"])).stdout,
b"Removed account \"fixture\" from this device. Server logout was skipped.\n"
);
assert_eq!(home.read_vault(), json!({"accounts": [], "selected": null}));
@@ -689,7 +699,7 @@ fn account_updates_preserve_identity_and_selection() {
let home = TestHome::new();
home.seed("http://localhost:8080");
assert_eq!(
- success(home.run(&["account", "view", "fixture"])).stdout,
+ success(home.run(&["account", "view", "--account", "fixture"])).stdout,
b"Name fixture\nEmail [email protected]\nHost http://localhost:8080\nLogged in photos\nSelected yes\nID 9007199254740993\n"
);
let account = json!({
@@ -697,7 +707,10 @@ fn account_updates_preserve_identity_and_selection() {
"host": "http://localhost:8080", "apps": ["photos"], "selected": true
});
assert_eq!(home.json(&["account", "list"]), json!([account]));
- assert_eq!(home.json(&["accounts", "view", "fixture"]), account);
+ assert_eq!(
+ home.json(&["accounts", "view", "--account", "fixture"]),
+ account
+ );
assert_eq!(home.json(&["account", "view"]), account);
let mut state = home.read_vault();
let mut second = state["accounts"][0].clone();
@@ -707,7 +720,7 @@ fn account_updates_preserve_identity_and_selection() {
state["accounts"].as_array_mut().unwrap().push(second);
home.write_vault(&state);
- success(home.run(&["account", "rename", "fixture", "renamed"]));
+ success(home.run(&["account", "rename", "renamed"]));
success(home.run(&["account", "rename", "second", "other"]));
state["accounts"][0]["name"] = json!("renamed");
state["accounts"][1]["name"] = json!("other");
@@ -779,20 +792,31 @@ fn account_token_reads_the_requested_saved_login() {
json!({"token": "AQ=="})
);
assert_eq!(
- home.json(&["account", "token", "fixture", "--app", "auth"]),
+ home.json(&["account", "token", "--account", "fixture", "--app", "auth"]),
json!({"token": "_w=="})
);
let missing_login = home.run(&args);
assert!(failure(&missing_login).contains(
- "account \"other\" is not logged into Ente Photos; use account login \"other\" --app photos"
+ "account \"other\" is not logged into Ente Photos; use account login --account \"other\" --app photos"
));
assert!(missing_login.stdout.is_empty());
- let explicit_login = home.run(&["account", "token", "--app", "locker", "fixture"]);
+ let explicit_login = home.run(&[
+ "account",
+ "token",
+ "--app",
+ "locker",
+ "--account",
+ "fixture",
+ ]);
assert!(failure(&explicit_login).contains(
- "account \"fixture\" is not logged into Ente Locker; use account login \"fixture\" --app locker"
+ "account \"fixture\" is not logged into Ente Locker; use account login --account \"fixture\" --app locker"
));
assert!(explicit_login.stdout.is_empty());
- let missing_account = home.command(&args).arg("missing").output().unwrap();
+ let missing_account = home
+ .command(&args)
+ .args(["--account", "missing"])
+ .output()
+ .unwrap();
assert!(failure(&missing_account).contains("no account named \"missing\"; use account list"));
assert!(missing_account.stdout.is_empty());
assert_eq!(fs::read(&vault).unwrap(), before);
@@ -811,7 +835,7 @@ fn account_token_reads_the_requested_saved_login() {
drop(reader);
let write_failure = home
.command(&args)
- .arg("fixture")
+ .args(["--account", "fixture"])
.stdout(writer)
.output()
.unwrap();
@@ -873,7 +897,7 @@ fn native_keyring_survives_separate_processes() {
.unwrap(),
);
let output = success(
- home.command(&["account", "view", "native", "--json"])
+ home.command(&["account", "view", "--account", "native", "--json"])
.env_remove("ENTE_CLI_VAULT_KEY")
.output()
.unwrap(),
@@ -995,6 +1019,9 @@ fn failure(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).into_owned()
}
+#[path = "support/account.rs"]
+mod account;
+
#[path = "support/admin.rs"]
mod admin;
diff --git a/rust/apps/cli-next/tests/support/account.rs b/rust/apps/cli-next/tests/support/account.rs
new file mode 100644
index 0000000000..e153024edb
--- /dev/null
+++ b/rust/apps/cli-next/tests/support/account.rs
@@ -0,0 +1,423 @@
+use super::*;
+use ente_accounts::{AccountsClient, AccountsClientConfig, signup::Signup};
+use mockito::Matcher;
+
+#[test]
+fn request_otp_is_independent_of_the_vault_and_reports_request_acceptance() {
+ let mut server = mockito::Server::new();
+ let request = server
+ .mock("POST", "/users/ott")
+ .match_header("x-client-package", "io.ente.auth")
+ .match_body(Matcher::Json(
+ json!({"email": "[email protected]", "purpose": "signup"}),
+ ))
+ .create();
+ let home = TestHome::new();
+ let output = success(
+ home.command(&[
+ "account",
+ "request-otp",
+ "--email",
+ "--host",
+ &server.url(),
+ "--app",
+ "auth",
+ "--json",
+ "--no-input",
+ ])
+ .env("ENTE_CLI_VAULT_KEY", "invalid")
+ .output()
+ .unwrap(),
+ );
+ let value: Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(
+ value,
+ json!({"email": "[email protected]", "host": server.url(), "app": "auth", "purpose": "create", "verificationRequested": true})
+ );
+ assert_eq!(fs::read_dir(home.dir.path()).unwrap().count(), 0);
+ request.assert();
+}
+
+#[test]
+fn email_input_conflicts_and_incomplete_creation_preserve_accounts() {
+ let home = TestHome::new();
+ home.seed("http://localhost:1");
+ let before = home.read_encrypted_vault();
+ for operation in ["login", "create"] {
+ let mut args = vec![
+ "account",
+ operation,
+ "--email",
+ "--app",
+ "photos",
+ "--input",
+ "-",
+ ];
+ if operation == "create" {
+ args.push("--accept-terms");
+ }
+ assert!(
+ failure(&home.with_input(
+ &args,
+ br#"{"email":"[email protected]","password":" secret "}"#
+ ))
+ .contains("--email differs")
+ );
+ }
+ for (input, consent, expected) in [
+ (
+ br#"{"email":"[email protected]","password":" secret "}"#.as_slice(),
+ true,
+ "requires otp",
+ ),
+ (
+ br#"{"email":"[email protected]","password":" secret ","otp":"123456"}"#.as_slice(),
+ false,
+ "requires --accept-terms",
+ ),
+ (
+ br#"{"email":"[email protected]","otp":"123456"}"#.as_slice(),
+ true,
+ "nonempty password",
+ ),
+ ] {
+ let mut args = vec![
+ "account",
+ "create",
+ "--input",
+ "-",
+ "--host",
+ "http://localhost:1",
+ ];
+ if consent {
+ args.push("--accept-terms");
+ }
+ assert!(failure(&home.with_input(&args, input)).contains(expected));
+ }
+ assert_eq!(home.read_encrypted_vault(), before);
+}
+
+#[tokio::test]
+async fn supplied_email_codes_complete_login_without_another_request() {
+ let mut server = mockito::Server::new_async().await;
+ let home = TestHome::new();
+ let signup = prepared(&mut server).await;
+ let saved = serde_json::to_value(&signup).unwrap();
+ let attributes = &saved["keys"]["attributes"];
+ server
+ .mock("GET", "/ping")
+ .with_body(r#"{"message":"pong","id":"fixture"}"#)
+ .create_async()
+ .await;
+ let attrs = srp_attributes(&mut server, &saved, true).await;
+ let verify = server
+ .mock("POST", "/users/verify-email")
+ .match_body(Matcher::PartialJson(
+ json!({"email": "[email protected]", "ott": "654321"}),
+ ))
+ .with_body(
+ json!({"id": 42, "keyAttributes": attributes, "token": b64::encode_url_safe(b"token")})
+ .to_string(),
+ )
+ .create_async()
+ .await;
+ server
+ .mock("GET", "/users/details/v2?memoryCount=false")
+ .with_body(r#"{"email":"[email protected]"}"#)
+ .create_async()
+ .await;
+ let args = [
+ "account",
+ "login",
+ "--app",
+ "photos",
+ "--host",
+ &server.url(),
+ "--email",
+ "--input",
+ "-",
+ "--json",
+ ];
+ let missing = home.with_input(&args, br#"{"password":" secret \ud83d\ude42 "}"#);
+ let error = failure(&missing);
+ assert!(
+ error.contains("request-otp --email EMAIL --purpose login"),
+ "{error}"
+ );
+ let output = success(home.with_input(
+ &args,
+ br#"{"email":"[email protected]","password":" secret \ud83d\ude42 ","otp":"654321"}"#,
+ ));
+ let result: Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(result["account"]["id"], "42");
+ assert_eq!(
+ home.read_vault()["accounts"][0]["identity"]["master_key"],
+ saved["keys"]["master_key"]
+ );
+ verify.assert_async().await;
+ attrs.assert_async().await;
+}
+
+#[tokio::test]
+async fn creation_retry_preserves_keys_and_recovers_after_an_accepted_upload() {
+ let mut server = mockito::Server::new_async().await;
+ let home = TestHome::new();
+ let verify = server
+ .mock("POST", "/users/verify-email")
+ .with_body(json!({"id": 42, "token": b64::encode_url_safe(b"token")}).to_string())
+ .create_async()
+ .await;
+ let empty = server
+ .mock("GET", "/users/session-validity/v2")
+ .with_body(r#"{"hasSetKeys":false}"#)
+ .create_async()
+ .await;
+ let upload = server
+ .mock("PUT", "/users/attributes")
+ .with_status(403)
+ .create_async()
+ .await;
+ let args = [
+ "account",
+ "create",
+ "--host",
+ &server.url(),
+ "--input",
+ "-",
+ "--accept-terms",
+ "--json",
+ ];
+ failure(&home.with_input(
+ &args,
+ br#"{"email":" [email protected] ","password":" secret \ud83d\ude42 ","otp":"123456"}"#,
+ ));
+ let state = home.read_vault();
+ let signup = &state["creations"][0]["signup"];
+ assert!(state["accounts"].as_array().unwrap().is_empty());
+ assert!(!state.to_string().contains(" secret πŸ™‚ "));
+ let bytes = home.read_encrypted_vault();
+ assert!(
+ failure(&home.with_input(&args, br#"{"email":"[email protected]","password":"wrong"}"#))
+ .contains("Incorrect password")
+ );
+ assert_eq!(home.read_encrypted_vault(), bytes);
+ empty.remove_async().await;
+ upload.remove_async().await;
+ server
+ .mock("GET", "/users/session-validity/v2")
+ .with_body(
+ json!({"hasSetKeys": true, "keyAttributes": signup["keys"]["attributes"]}).to_string(),
+ )
+ .create_async()
+ .await;
+ server
+ .mock("POST", "/users/srp/setup")
+ .with_status(400)
+ .create_async()
+ .await;
+ let attrs = srp_attributes(&mut server, signup, false).await;
+ server
+ .mock("GET", "/users/details/v2?memoryCount=false")
+ .with_body(r#"{"email":"[email protected]"}"#)
+ .create_async()
+ .await;
+ let mut retry = args.to_vec();
+ retry.extend(["--account", "personal"]);
+ let output = success(home.with_input(
+ &retry,
+ br#"{"email":"[email protected]","password":" secret \ud83d\ude42 "}"#,
+ ));
+ let result: Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(result["account"]["name"], "personal");
+ assert_eq!(result["created"], true);
+ let complete = home.read_vault();
+ assert_eq!(
+ complete["accounts"][0]["identity"]["master_key"],
+ signup["keys"]["master_key"]
+ );
+ assert_eq!(
+ complete["accounts"][0]["identity"]["secret_key"],
+ signup["keys"]["secret_key"]
+ );
+ assert!(complete.get("creations").is_none());
+ let recovery = home.json(&["account", "recovery-key", "--offline"]);
+ let recovery = ente_accounts::auth::recovery_key_from_mnemonic_or_hex(
+ recovery["recoveryKey"].as_str().unwrap(),
+ )
+ .unwrap();
+ assert_eq!(
+ serde_json::to_value(recovery.to_vec()).unwrap(),
+ complete["accounts"][0]["identity"]["recovery_key"]
+ );
+ verify.assert_async().await;
+ attrs.assert_async().await;
+}
+
+async fn prepared(server: &mut mockito::ServerGuard) -> Signup {
+ let client =
+ AccountsClient::new(AccountsClientConfig::new("io.ente.photos").with_origin(server.url()))
+ .unwrap();
+ let empty = server
+ .mock("GET", "/users/session-validity/v2")
+ .with_body(r#"{"hasSetKeys":false}"#)
+ .create_async()
+ .await;
+ let signup = Signup::verified(
+ "[email protected]".into(),
+ serde_json::from_value(json!({"id":42,"token": b64::encode_url_safe(b"token")})).unwrap(),
+ )
+ .unwrap()
+ .prepare(&client, " secret πŸ™‚ ")
+ .await
+ .unwrap();
+ empty.remove_async().await;
+ signup
+}
+
+async fn srp_attributes(
+ server: &mut mockito::ServerGuard,
+ signup: &Value,
+ email_mfa: bool,
+) -> mockito::Mock {
+ let keys = &signup["keys"];
+ let salt: Vec<u8> = serde_json::from_value(keys["srp_salt"].clone()).unwrap();
+ server.mock("GET", "/users/srp/attributes?email=new%40example.org").with_body(json!({"attributes": {
+ "srpUserID": keys["srp_user_id"], "srpSalt": b64::encode(&salt), "kekSalt": keys["attributes"]["kekSalt"],
+ "memLimit": keys["attributes"]["memLimit"], "opsLimit": keys["attributes"]["opsLimit"], "isEmailMFAEnabled": email_mfa
+ }}).to_string()).expect_at_least(1).create_async().await
+}
+
+#[cfg(feature = "museum")]
+#[test]
+fn creation_enrollment_and_login_across_processes() -> ente_test_support::TestResult {
+ use ente_test_support::{Museum, account_fixture::current_totp};
+ Museum::run_async(|origin| async move {
+ let home = TestHome::new();
+ let email = format!("cli-create-{}@example.org", uuid::Uuid::new_v4());
+ home.json(&[
+ "account",
+ "request-otp",
+ "--email",
+ &email,
+ "--host",
+ &origin,
+ "--app",
+ "auth",
+ ]);
+ let input = json!({"password": " secret πŸ™‚ ", "otp": "123456"});
+ let output = success(home.with_input(
+ &[
+ "account",
+ "create",
+ "--email",
+ &email,
+ "--host",
+ &origin,
+ "--app",
+ "auth",
+ "--input",
+ "-",
+ "--accept-terms",
+ "--json",
+ ],
+ &serde_json::to_vec(&input)?,
+ ));
+ let created: Value = serde_json::from_slice(&output.stdout)?;
+ assert_eq!(created["account"]["name"], email);
+ assert_eq!(created["account"]["apps"], json!(["auth"]));
+ assert_eq!(created["account"]["selected"], true);
+ assert_eq!(
+ home.json(&["auth", "api", "/users/details/v2"])["email"],
+ email
+ );
+ let setup = home.json(&["account", "totp", "setup"]);
+ let secret = setup["secret"].as_str().unwrap();
+ assert_eq!(
+ home.json(&["account", "totp", "status"]),
+ json!({"enabled": false})
+ );
+ failure(&home.with_input(
+ &["account", "totp", "enable", "--input", "-"],
+ &serde_json::to_vec(&json!({"secret": secret, "totp": "invalid"}))?,
+ ));
+ let output = success(home.with_input(
+ &["account", "totp", "enable", "--input", "-", "--json"],
+ &serde_json::to_vec(&json!({"secret": secret, "totp": current_totp(secret)?}))?,
+ ));
+ assert_eq!(
+ serde_json::from_slice::<Value>(&output.stdout)?,
+ json!({"enabled": true})
+ );
+ assert_eq!(
+ home.json(&["account", "totp", "status"]),
+ json!({"enabled": true})
+ );
+ assert!(failure(&home.run(&["account", "totp", "setup"])).contains("already enabled"));
+ let second = TestHome::new();
+ let login =
+ json!({"password": " secret πŸ™‚ ", "otp": "123456", "totp": current_totp(secret)?});
+ success(second.with_input(
+ &[
+ "account",
+ "login",
+ "--email",
+ &email,
+ "--account",
+ "personal",
+ "--app",
+ "auth",
+ "--host",
+ &origin,
+ "--input",
+ "-",
+ ],
+ &serde_json::to_vec(&login)?,
+ ));
+ assert_eq!(
+ home.json(&["account", "recovery-key"]),
+ second.json(&["account", "recovery-key", "--account", "personal"])
+ );
+ assert_eq!(
+ second.json(&["auth", "api", "/users/details/v2"])["email"],
+ email
+ );
+ Ok(())
+ })
+}
+
+#[cfg(all(unix, feature = "museum"))]
+#[test]
+fn interactive_creation_and_enrollment() -> ente_test_support::TestResult {
+ ente_test_support::Museum::run_async(|origin| async move {
+ let home = TestHome::new();
+ let email = format!("cli-interactive-{}@example.org", uuid::Uuid::new_v4());
+ success(
+ Command::new("python3")
+ .args([
+ concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/tests/support/account_prompt.py"
+ ),
+ env!("CARGO_BIN_EXE_ente-cli-next"),
+ &origin,
+ &email,
+ ])
+ .env("ENTE_CLI_HOME", home.dir.path())
+ .env("ENTE_CLI_VAULT_KEY", b64::encode(home.key.as_bytes()))
+ .output()?,
+ );
+ assert_eq!(home.json(&["account", "view"])["name"], email);
+ assert_eq!(
+ home.json(&["account", "totp", "status"]),
+ json!({"enabled": true})
+ );
+ assert_eq!(
+ home.json(&["photos", "api", "/users/details/v2"])["email"],
+ email
+ );
+ Ok(())
+ })
+}
diff --git a/rust/apps/cli-next/tests/support/account_prompt.py b/rust/apps/cli-next/tests/support/account_prompt.py
new file mode 100644
index 0000000000..d799753327
--- /dev/null
+++ b/rust/apps/cli-next/tests/support/account_prompt.py
@@ -0,0 +1,84 @@
+import base64
+import hashlib
+import hmac
+import os
+import pty
+import re
+import select
+import signal
+import sys
+import termios
+import time
+
+binary, origin, email = sys.argv[1:]
+
+
+def run(args, replies):
+ pid, fd = pty.fork()
+ if pid == 0:
+ os.execv(binary, args)
+ output = b""
+ deadline = time.monotonic() + 90
+
+ def expect(text):
+ nonlocal output
+ while text not in output:
+ assert time.monotonic() < deadline, output.decode(errors="replace")
+ if select.select([fd], [], [], 0.1)[0]:
+ output += os.read(fd, 65536)
+ before, output = output.split(text, 1)
+ return before
+
+ def send(value, secure=False):
+ while secure and termios.tcgetattr(fd)[3] & termios.ECHO:
+ assert time.monotonic() < deadline, output.decode(errors="replace")
+ time.sleep(0.01)
+ os.write(fd, value + b"\r")
+
+ try:
+ replies(expect, send)
+ while time.monotonic() < deadline:
+ done, status = os.waitpid(pid, os.WNOHANG)
+ if done:
+ assert os.waitstatus_to_exitcode(status) == 0, output.decode(errors="replace")
+ return
+ if select.select([fd], [], [], 0.1)[0]:
+ try:
+ output += os.read(fd, 65536)
+ except OSError:
+ pass
+ raise AssertionError(output.decode(errors="replace"))
+ finally:
+ os.close(fd)
+ try:
+ os.kill(pid, signal.SIGKILL)
+ os.waitpid(pid, 0)
+ except ProcessLookupError:
+ pass
+
+
+def create(expect, send):
+ for prompt, answer, secure in [
+ (b"Email:", email.encode(), False),
+ (b"privacy policy?", b"y", False),
+ (b"Email verification code:", b"123456", True),
+ (b"Password:", b"disposable-password", True),
+ (b"Confirm password:", b"disposable-password", True),
+ ]:
+ expect(prompt)
+ send(answer, secure)
+ expect(b"Created ")
+
+
+def enable(expect, send):
+ text = expect(b"Authenticator code:")
+ secret = re.search(rb"authenticator: ([A-Z2-7]+)", text)[1]
+ key = base64.b32decode(secret + b"=" * (-len(secret) % 8))
+ digest = hmac.new(key, (int(time.time()) // 30).to_bytes(8, "big"), hashlib.sha1).digest()
+ offset = digest[-1] & 15
+ code = (int.from_bytes(digest[offset:offset + 4], "big") & 0x7fffffff) % 1000000
+ send(f"{code:06d}".encode(), True)
+
+
+run([binary, "account", "create", "--host", origin], create)
+run([binary, "account", "totp", "enable"], enable)
diff --git a/rust/apps/cli-next/tests/support/admin.rs b/rust/apps/cli-next/tests/support/admin.rs
index 38c31dc16f..c295740555 100644
--- a/rust/apps/cli-next/tests/support/admin.rs
+++ b/rust/apps/cli-next/tests/support/admin.rs
@@ -277,7 +277,7 @@ fn admin_failures_do_not_all_recommend_login() {
let output = home.run(&["admin", "user", "list", "--json", "--no-input"]);
let error = failure(&output);
assert_eq!(
- error.contains("account login \"fixture\" --app photos"),
+ error.contains("account login --account \"fixture\" --app photos"),
stale,
"{error}"
);
diff --git a/rust/apps/cli-next/tests/support/auth.rs b/rust/apps/cli-next/tests/support/auth.rs
index 44e2ba07e1..0fa29670ad 100644
--- a/rust/apps/cli-next/tests/support/auth.rs
+++ b/rust/apps/cli-next/tests/support/auth.rs
@@ -454,7 +454,14 @@ fn slow_stdout_releases_account_storage_before_publication() {
let mut stdout = child.stdout.take().unwrap();
let mut first = [0];
stdout.read_exact(&mut first).unwrap();
- success(home.run(&["accounts", "logout", "fixture", "--local", "--offline"]));
+ success(home.run(&[
+ "accounts",
+ "logout",
+ "--account",
+ "fixture",
+ "--local",
+ "--offline",
+ ]));
let mut rest = Vec::new();
stdout.read_to_end(&mut rest).unwrap();
success(child.wait_with_output().unwrap());
diff --git a/rust/apps/cli-next/tests/support/export_maintenance.rs b/rust/apps/cli-next/tests/support/export_maintenance.rs
index 786cc015d1..f286ad9c33 100644
--- a/rust/apps/cli-next/tests/support/export_maintenance.rs
+++ b/rust/apps/cli-next/tests/support/export_maintenance.rs
@@ -2525,8 +2525,8 @@ fn export_reports_progress_and_keeps_account_storage_while_workers_run() {
.join(state["accounts"][0]["storage_id"].as_str().unwrap());
let revoke = server.mock("POST", "/users/logout").expect(0).create();
for args in [
- vec!["account", "logout", "fixture", "--local"],
- vec!["account", "logout", "fixture"],
+ vec!["account", "logout", "--account", "fixture", "--local"],
+ vec!["account", "logout", "--account", "fixture"],
vec!["account", "logout", "--app", "photos"],
] {
let output = ExportChild::spawn(&mut home.command(&args))
@@ -2586,15 +2586,20 @@ fn export_reports_progress_and_keeps_account_storage_while_workers_run() {
.open(account.with_extension("lock"))
.unwrap();
lock.lock().unwrap();
- let output =
- ExportChild::spawn(&mut home.command(&["account", "logout", "fixture", "--local"]))
- .unwrap()
- .wait_with_output()
- .unwrap();
+ let output = ExportChild::spawn(&mut home.command(&[
+ "account",
+ "logout",
+ "--account",
+ "fixture",
+ "--local",
+ ]))
+ .unwrap()
+ .wait_with_output()
+ .unwrap();
assert!(failure(&output).contains("account is in use"));
assert!(home.read_vault()["accounts"][0]["sessions"]["locker"].is_object());
drop(lock);
- success(home.run(&["account", "logout", "fixture", "--local"]));
+ success(home.run(&["account", "logout", "--account", "fixture", "--local"]));
assert!(!account.exists());
assert_eq!(
fs::read_dir(home.dir.path().join("accounts"))
diff --git a/rust/apps/cli-next/tests/support/files.rs b/rust/apps/cli-next/tests/support/files.rs
index 1dbf0c11cc..62f0c655cb 100644
--- a/rust/apps/cli-next/tests/support/files.rs
+++ b/rust/apps/cli-next/tests/support/files.rs
@@ -399,7 +399,14 @@ fn account_replica_is_encrypted_and_available_offline() {
.contains("unable to open database file")
);
assert!(!other_directory.join("data.db").exists());
- home.json(&["accounts", "logout", "renamed", "--local", "--offline"]);
+ home.json(&[
+ "accounts",
+ "logout",
+ "--account",
+ "renamed",
+ "--local",
+ "--offline",
+ ]);
assert!(!directory.exists());
assert!(!lock_path.exists());
}
diff --git a/rust/apps/cli-next/tests/support/museum.rs b/rust/apps/cli-next/tests/support/museum.rs
index 3d7ad36bad..4b1e0b1cf4 100644
--- a/rust/apps/cli-next/tests/support/museum.rs
+++ b/rust/apps/cli-next/tests/support/museum.rs
@@ -387,16 +387,21 @@ async fn exercise(origin: String) -> TestResult {
&home,
"photos",
&alice_email,
- &["other-server", "--host", &alias_origin],
+ &["--account", "other-server", "--host", &alias_origin],
);
success(home.run(&["account", "rename", &alice_email, "work"]));
assert_eq!(home.read_vault()["accounts"][0]["storage_id"], first_id);
- login(&home, "auth", &bob_email, &[&bob_email, "--host", &origin]);
+ login(
+ &home,
+ "auth",
+ &bob_email,
+ &["--account", &bob_email, "--host", &origin],
+ );
assert!(
failure(&home.run(&["photos", "album", "list"])).contains("is not logged into Ente Photos")
);
- login(&home, "locker", &alice_email, &["work"]);
+ login(&home, "locker", &alice_email, &["--account", "work"]);
let accounts = home.json(&["account", "list"]);
assert!(
accounts
@@ -579,7 +584,7 @@ async fn exercise(origin: String) -> TestResult {
0
);
- login(&home, "photos", &alice_email, &["work"]);
+ login(&home, "photos", &alice_email, &["--account", "work"]);
success(home.run(&["account", "switch", "work"]));
let added_original = b"added after the first sync";
let added_file = upload_file(&origin, &alice, album, &key, added_original, None)
@@ -648,7 +653,9 @@ async fn exercise(origin: String) -> TestResult {
let before = fs::read(home.dir.path().join("vault.json")).unwrap();
for name in [Some("work"), None] {
let mut args = vec!["account", "login", "--app", "photos", "--input", "-"];
- args.extend(name);
+ if let Some(name) = name {
+ args.extend(["--account", name]);
+ }
assert!(
failure(&home.with_input(&args, &credentials(&bob_email)))
.contains("identity does not match")
@@ -676,7 +683,7 @@ async fn exercise(origin: String) -> TestResult {
assert_eq!(response.status(), reqwest::StatusCode::UNAUTHORIZED);
failure(&home.run(&["photos", "album", "list"]));
assert_eq!(
- home.json(&["account", "view", "work"])["apps"],
+ home.json(&["account", "view", "--account", "work"])["apps"],
json!(["locker"])
);
let account_dir = home
@@ -685,7 +692,7 @@ async fn exercise(origin: String) -> TestResult {
.join("accounts")
.join(first_id.as_str().unwrap());
assert!(account_dir.join("data.db").is_file());
- success(home.run(&["account", "logout", "work", "--local"]));
+ success(home.run(&["account", "logout", "--account", "work", "--local"]));
assert!(!account_dir.exists());
assert!(!account_dir.with_extension("lock").exists());
@@ -725,6 +732,7 @@ pub(super) fn login(home: &TestHome, app: &str, email: &str, options: &[&str]) {
home.json(&[
"account",
"view",
+ "--account",
result["account"]["name"].as_str().unwrap()
])
);
diff --git a/rust/crates/accounts/src/client.rs b/rust/crates/accounts/src/client.rs
index 2eda4e19e2..cdfd10e32e 100644
--- a/rust/crates/accounts/src/client.rs
+++ b/rust/crates/accounts/src/client.rs
@@ -183,17 +183,14 @@ impl AccountsClient {
email: email.to_string(),
purpose: purpose.to_string(),
};
- Ok(http::retry(|| async {
- self.api
- .post("/users/ott")
- .json(&request)
- .send()
- .await?
- .error_for_code()
- .await?;
- Ok(())
- })
- .await?)
+ self.api
+ .post("/users/ott")
+ .json(&request)
+ .send()
+ .await?
+ .error_for_code()
+ .await?;
+ Ok(())
}
pub async fn verify_email(
@@ -564,7 +561,7 @@ mod tests {
}
#[tokio::test]
- async fn send_otp_retries_on_server_error() {
+ async fn email_request_surfaces_server_failure() {
let mut server = Server::new_async().await;
let first = server
.mock("POST", "/users/ott")
@@ -573,18 +570,14 @@ mod tests {
.expect(1)
.create_async()
.await;
- let second = server
- .mock("POST", "/users/ott")
- .with_status(200)
- .expect(1)
- .create_async()
- .await;
-
let client = make_client(server.url());
- client.send_otp("[email protected]", "login").await.unwrap();
+ let error = client
+ .send_otp("[email protected]", "login")
+ .await
+ .unwrap_err();
+ assert!(matches!(error, Error::Http(error) if error.status_code() == Some(500)));
first.assert_async().await;
- second.assert_async().await;
}
#[tokio::test]
diff --git a/rust/crates/accounts/src/lifecycle.rs b/rust/crates/accounts/src/lifecycle.rs
index 2320f99de6..d20181e9b4 100644
--- a/rust/crates/accounts/src/lifecycle.rs
+++ b/rust/crates/accounts/src/lifecycle.rs
@@ -89,6 +89,14 @@ pub struct TwoFactorSetup {
}
impl TwoFactorSetup {
+ pub fn from_secret(secret_code: String, recovery_key: &[u8]) -> Self {
+ Self {
+ secret_code,
+ qr_code: String::new(),
+ recovery_key: hex::encode(recovery_key),
+ }
+ }
+
pub async fn start(
client: &AccountsClient,
master_key: &[u8],
diff --git a/rust/crates/accounts/src/login.rs b/rust/crates/accounts/src/login.rs
index 5fd064010f..bf2671ff34 100644
--- a/rust/crates/accounts/src/login.rs
+++ b/rust/crates/accounts/src/login.rs
@@ -31,9 +31,16 @@ pub struct LoginFlow {
impl LoginFlow {
pub async fn start(client: &AccountsClient, email: String) -> Result<(Self, LoginStep)> {
+ let (flow, step) = Self::prepare(client, email).await?;
+ if matches!(step, LoginStep::EmailCode) {
+ flow.resend_code(client).await?;
+ }
+ Ok((flow, step))
+ }
+
+ pub async fn prepare(client: &AccountsClient, email: String) -> Result<(Self, LoginStep)> {
let attributes = client.get_srp_attributes(&email).await?;
let (state, step) = if attributes.is_email_mfa_enabled {
- client.send_otp(&email, "login").await?;
(State::EmailCode, LoginStep::EmailCode)
} else {
(State::Password(None), LoginStep::Password)
diff --git a/rust/crates/accounts/src/signup.rs b/rust/crates/accounts/src/signup.rs
index ad0f64139b..7d0318f917 100644
--- a/rust/crates/accounts/src/signup.rs
+++ b/rust/crates/accounts/src/signup.rs
@@ -6,8 +6,8 @@ use zeroize::ZeroizeOnDrop;
use crate::{
AccountSecrets, AccountsClient, AuthenticatedAccount, Error, KeyAttributes, Result,
auth::{
- KeyDerivationStrength, SrpSession, generate_keys_with_strength,
- generate_srp_setup_with_login_key, get_recovery_key,
+ KeyDerivationStrength, SrpSession, decrypt_keys_only, derive_kek,
+ generate_keys_with_strength, generate_srp_setup_with_login_key, get_recovery_key,
},
models::{AuthResponse, SetupSrpRequest},
};
@@ -67,7 +67,15 @@ impl Signup {
password: &str,
strength: KeyDerivationStrength,
) -> Result<Self> {
- if self.keys.is_some() {
+ if let Some(keys) = &self.keys {
+ let attributes = &keys.attributes;
+ let kek = derive_kek(
+ password,
+ &attributes.kek_salt,
+ attributes.mem_limit,
+ attributes.ops_limit,
+ )?;
+ decrypt_keys_only(&kek, attributes)?;
return Ok(self.clone());
}
self.authorize(client);
diff --git a/rust/crates/accounts/src/signup/tests.rs b/rust/crates/accounts/src/signup/tests.rs
index 331181dcbb..e077514cd2 100644
--- a/rust/crates/accounts/src/signup/tests.rs
+++ b/rust/crates/accounts/src/signup/tests.rs
@@ -58,10 +58,11 @@ async fn checkpoints_preserve_keys_and_reconcile_an_accepted_upload() {
prepared.recovery_key().unwrap(),
recovered.recovery_key().unwrap()
);
- let retried = recovered
- .prepare(&client, "different-password")
- .await
- .unwrap();
+ assert!(matches!(
+ recovered.prepare(&client, "different-password").await,
+ Err(Error::IncorrectPassword)
+ ));
+ let retried = recovered.prepare(&client, "signup-password").await.unwrap();
assert!(serde_json::to_vec(&retried).unwrap() == serde_json::to_vec(&recovered).unwrap());
let keys = recovered.keys.as_ref().unwrap();
empty.assert_async().await;