Skip to content

armgit / ente

Public Imported from GitHub
0

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

Complete CLI account logout

Manav Rathi86ca965bb542
diff --git a/rust/apps/cli-next/README.md b/rust/apps/cli-next/README.md
new file mode 100644
index 0000000000..7b2b39bd43
--- /dev/null
+++ b/rust/apps/cli-next/README.md
@@ -0,0 +1,7 @@
+WIP replacement Ente Rust CLI.
+
+## Development
+
+```sh
+cargo run -p ente-cli-next -- --help
+```
diff --git a/rust/apps/cli-next/src/api.rs b/rust/apps/cli-next/src/api.rs
index d6dc3f7923..d1f228a596 100644
--- a/rust/apps/cli-next/src/api.rs
+++ b/rust/apps/cli-next/src/api.rs
@@ -38,6 +38,16 @@ pub fn accounts_client(origin: &str, product: Product) -> Result<AccountsClient>
)?)
}
+pub async fn logout(account: &Account, product: Product) -> Result<()> {
+ let client = accounts_client(&account.origin, product)?;
+ client.set_auth_token(Some(b64::encode_url_safe(account.token(product)?)));
+ match client.logout().await {
+ Ok(()) => Ok(()),
+ Err(ente_accounts::Error::Http(error)) if error.status_code() == Some(401) => Ok(()),
+ Err(error) => Err(error.into()),
+ }
+}
+
pub fn session(account: &Account, product: Product) -> Result<Session> {
let mut config = ApiConfig::new(account.origin.clone());
config.client_package = Some(product.client_package().into());
diff --git a/rust/apps/cli-next/src/args.rs b/rust/apps/cli-next/src/args.rs
index 35afa63865..2575748681 100644
--- a/rust/apps/cli-next/src/args.rs
+++ b/rust/apps/cli-next/src/args.rs
@@ -12,6 +12,12 @@ use serde::{Deserialize, Serialize};
pub struct Cli {
#[arg(long, global = true, help = "Print the result as JSON")]
pub json: bool,
+ #[command(subcommand)]
+ pub command: Command,
+}
+
+#[derive(Args)]
+pub struct AccountSelector {
#[arg(
long,
global = true,
@@ -19,24 +25,28 @@ pub struct Cli {
help = "Use this account instead of the selected one"
)]
pub account: Option<String>,
- #[command(subcommand)]
- pub command: Command,
}
#[derive(Subcommand)]
pub enum Command {
#[command(about = "Manage Ente Photos")]
Photos {
+ #[command(flatten)]
+ selector: AccountSelector,
#[command(subcommand)]
command: PhotosCommand,
},
#[command(about = "Manage Ente Locker")]
Locker {
+ #[command(flatten)]
+ selector: AccountSelector,
#[command(subcommand)]
command: SessionCommand,
},
#[command(about = "Manage Ente Auth")]
Auth {
+ #[command(flatten)]
+ selector: AccountSelector,
#[command(subcommand)]
command: SessionCommand,
},
@@ -161,10 +171,15 @@ pub enum AccountCommand {
#[arg(help = "New local name")]
new_name: String,
},
- #[command(about = "Forget an account on this device; remote sessions stay valid")]
- Remove {
+ #[command(about = "Log out of every product and remove the account from this device")]
+ Logout {
#[arg(help = "Account name")]
name: String,
+ #[arg(
+ long,
+ help = "Forget the account on this device without logging out on the server"
+ )]
+ local: bool,
},
}
diff --git a/rust/apps/cli-next/src/main.rs b/rust/apps/cli-next/src/main.rs
index 15c898b76e..b81b115187 100644
--- a/rust/apps/cli-next/src/main.rs
+++ b/rust/apps/cli-next/src/main.rs
@@ -9,7 +9,7 @@ use std::{
path::Path,
};
-use anyhow::{Context, Result};
+use anyhow::{Context, Result, bail};
use clap::Parser;
use ente_core::{b64, crypto::Key};
use ente_photos::collections;
@@ -33,28 +33,26 @@ async fn main() {
}
async fn run(cli: Cli) -> Result<()> {
- let Cli {
- json,
- account,
- command,
- } = cli;
+ let Cli { json, command } = cli;
match command {
Command::Photos {
+ selector,
command: PhotosCommand::Session(command),
- } => session(Product::Photos, command, account.as_deref(), json).await,
- Command::Locker { command } => {
- session(Product::Locker, command, account.as_deref(), json).await
+ } => session(Product::Photos, command, selector.account.as_deref(), json).await,
+ Command::Locker { selector, command } => {
+ session(Product::Locker, command, selector.account.as_deref(), json).await
}
- Command::Auth { command } => {
- session(Product::Auth, command, account.as_deref(), json).await
+ Command::Auth { selector, command } => {
+ session(Product::Auth, command, selector.account.as_deref(), json).await
}
Command::Photos {
+ selector,
command:
PhotosCommand::Album {
command: AlbumCommand::List,
},
- } => album_list(account.as_deref(), json).await,
- Command::Account { command } => account_command(command, json),
+ } => album_list(selector.account.as_deref(), json).await,
+ Command::Account { command } => account_command(command, json).await,
Command::Vault {
command:
VaultCommand::Key {
@@ -113,17 +111,12 @@ async fn session(
SessionCommand::Logout => {
let mut vault = Vault::open()?;
let index = vault.state.resolve(selected)?;
- let account = &vault.state.accounts[index];
- let client = api::accounts_client(&account.origin, product)?;
- client.set_auth_token(Some(b64::encode_url_safe(account.token(product)?)));
- if let Err(error) = client.logout().await {
- match &error {
- ente_accounts::Error::Http(error) if error.status_code() == Some(401) => (),
- _ => return Err(error.into()),
- }
- }
- let name = account.name.clone();
+ let name = vault.state.accounts[index].name.clone();
+ api::logout(&vault.state.accounts[index], product).await?;
vault.state.accounts[index].sessions.remove(&product);
+ if vault.state.accounts[index].sessions.is_empty() {
+ remove_account(&mut vault.state, index);
+ }
vault.save()?;
drop(vault);
output::action(
@@ -135,7 +128,7 @@ async fn session(
}
}
-fn account_command(command: AccountCommand, json_output: bool) -> Result<()> {
+async fn account_command(command: AccountCommand, json_output: bool) -> Result<()> {
match command {
AccountCommand::List => {
let state = State::load()?;
@@ -178,25 +171,82 @@ fn account_command(command: AccountCommand, json_output: bool) -> Result<()> {
}
output_account(vault.into_state(), index, json_output)
}
- AccountCommand::Remove { name } => {
+ AccountCommand::Logout { name, local } => {
let mut vault = Vault::open()?;
- let state = &mut vault.state;
- let index = state.named(&name)?;
- let removed = state.accounts.remove(index);
- if state.selected == Some(removed.storage_id) {
- state.selected = None;
+ let index = vault.state.named(&name)?;
+ let products = vault.state.accounts[index]
+ .sessions
+ .keys()
+ .copied()
+ .collect::<Vec<_>>();
+ if !local {
+ for product in &products {
+ if let Err(error) = api::logout(&vault.state.accounts[index], *product).await {
+ if vault.state.accounts[index].sessions.len() < products.len() {
+ vault.save()?;
+ }
+ let remaining = vault.state.accounts[index]
+ .sessions
+ .keys()
+ .copied()
+ .collect::<Vec<_>>();
+ bail!(
+ "cannot log out of {} for {name:?}: {error:#}. Still logged in: {}. Retry when the server is reachable, or use --local to forget the account on this device.",
+ product.display_name(),
+ product_names(&remaining),
+ );
+ }
+ vault.state.accounts[index].sessions.remove(product);
+ }
}
+ remove_account(&mut vault.state, index);
vault.save()?;
drop(vault);
+ let message = if local && !products.is_empty() {
+ format!(
+ "Logged out of {name:?} on this device only. Still logged in on the server: {}.",
+ product_names(&products)
+ )
+ } else if products.is_empty() {
+ format!("Removed account {name:?} from this device.")
+ } else {
+ format!("Logged out of {} for {name:?}.", product_names(&products))
+ };
output::action(
json_output,
- &json!({ "removed": name }),
- &format!("Forgot local account {name:?}; remote sessions were not revoked."),
+ &json!({
+ "account": name,
+ "products": products,
+ "sessions": if local { "active" } else { "revoked" },
+ }),
+ &message,
)
}
}
}
+fn remove_account(state: &mut State, index: usize) {
+ let storage_id = state.accounts.remove(index).storage_id;
+ if state.selected == Some(storage_id) {
+ state.selected = None;
+ }
+}
+
+fn product_names(products: &[Product]) -> String {
+ let names = products
+ .iter()
+ .map(|product| product.display_name())
+ .collect::<Vec<_>>();
+ match names.as_slice() {
+ [] => String::new(),
+ [name] => (*name).to_owned(),
+ [first, second] => format!("{first} and {second}"),
+ [first, middle @ .., last] => {
+ format!("{first}, {}, and {last}", middle.join(", "))
+ }
+ }
+}
+
fn output_account(state: State, index: usize, json_output: bool) -> Result<()> {
let account = AccountView::new(&state.accounts[index], state.selected);
if json_output {
diff --git a/rust/apps/cli-next/tests/cli.rs b/rust/apps/cli-next/tests/cli.rs
index 2075cb4fae..97d928b24c 100644
--- a/rust/apps/cli-next/tests/cli.rs
+++ b/rust/apps/cli-next/tests/cli.rs
@@ -406,20 +406,8 @@ fn logout_reconciles_remote_and_local_session_state() {
success(home.run(&["photos", "logout"])).stdout,
b"Logged out of Ente Photos for \"fixture\".\n"
);
- assert_eq!(
- home.json(&["account", "view", "fixture"])["products"],
- json!([])
- );
- let origin = server.url();
- assert_eq!(
- success(home.run(&["account", "list"])).stdout,
- format!(
- "SELECTED NAME EMAIL {host:<width$} LOGGED IN ID\n* fixture [email protected] {origin} none 9007199254740993\n",
- host = "HOST",
- width = origin.len()
- )
- .as_bytes()
- );
+ assert_eq!(home.json(&["account", "list"]), json!([]));
+ assert_eq!(home.read_vault(), json!({"accounts": [], "selected": null}));
revoked.assert();
let unavailable = server
@@ -438,6 +426,88 @@ fn logout_reconciles_remote_and_local_session_state() {
unavailable.assert();
}
+#[test]
+fn account_logout_revokes_every_product_before_removing_the_account() {
+ let mut server = mockito::Server::new();
+ let home = TestHome::new();
+ home.seed(&server.url());
+ let mut state = home.read_vault();
+ state["accounts"][0]["sessions"]["locker"] = json!({"token": [1]});
+ state["accounts"][0]["sessions"]["auth"] = json!({"token": [2]});
+ home.write_vault(&state);
+ let photos = server
+ .mock("POST", "/users/logout")
+ .match_header("x-auth-token", "--8=")
+ .match_header("x-client-package", "io.ente.photos")
+ .create();
+ let locker_token = b64::encode_url_safe(&[1]);
+ let locker = server
+ .mock("POST", "/users/logout")
+ .match_header("x-auth-token", locker_token.as_str())
+ .match_header("x-client-package", "io.ente.locker")
+ .create();
+ let auth_token = b64::encode_url_safe(&[2]);
+ let auth = server
+ .mock("POST", "/users/logout")
+ .match_header("x-auth-token", auth_token.as_str())
+ .match_header("x-client-package", "io.ente.auth")
+ .create();
+
+ assert_eq!(
+ success(home.run(&["account", "logout", "fixture"])).stdout,
+ b"Logged out of Ente Photos, Ente Locker, and Ente Auth for \"fixture\".\n"
+ );
+ assert_eq!(home.read_vault(), json!({"accounts": [], "selected": null}));
+ photos.assert();
+ locker.assert();
+ auth.assert();
+}
+
+#[test]
+fn account_logout_preserves_sessions_that_it_could_not_revoke() {
+ let mut server = mockito::Server::new();
+ let home = TestHome::new();
+ home.seed(&server.url());
+ let mut state = home.read_vault();
+ state["accounts"][0]["sessions"]["locker"] = json!({"token": [1]});
+ state["accounts"][0]["sessions"]["auth"] = json!({"token": [2]});
+ home.write_vault(&state);
+ let photos = server
+ .mock("POST", "/users/logout")
+ .match_header("x-client-package", "io.ente.photos")
+ .create();
+ let locker = server
+ .mock("POST", "/users/logout")
+ .match_header("x-client-package", "io.ente.locker")
+ .with_status(403)
+ .create();
+ let auth = server
+ .mock("POST", "/users/logout")
+ .match_header("x-client-package", "io.ente.auth")
+ .expect(0)
+ .create();
+
+ let output = home.run(&["account", "logout", "fixture"]);
+ assert!(output.stdout.is_empty());
+ let error = failure(&output);
+ assert!(error.contains("cannot log out of Ente Locker for \"fixture\": HTTP 403"));
+ assert!(error.contains("Still logged in: Ente Locker and Ente Auth."));
+ let state = home.read_vault();
+ let sessions = &state["accounts"][0]["sessions"];
+ assert!(sessions.get("photos").is_none());
+ assert!(sessions.get("locker").is_some());
+ assert!(sessions.get("auth").is_some());
+
+ assert_eq!(
+ success(home.run(&["account", "logout", "fixture", "--local"])).stdout,
+ b"Logged out of \"fixture\" on this device only. Still logged in on the server: Ente Locker and Ente Auth.\n"
+ );
+ assert_eq!(home.read_vault(), json!({"accounts": [], "selected": null}));
+ photos.assert();
+ locker.assert();
+ auth.assert();
+}
+
#[test]
fn account_updates_preserve_identity_and_selection() {
let home = TestHome::new();
@@ -457,7 +527,7 @@ fn account_updates_preserve_identity_and_selection() {
let mut second = state["accounts"][0].clone();
second["storage_id"] = json!("f6579aae-83ef-4f28-965e-8d34883d3fe5");
second["name"] = json!("second");
- second["sessions"] = json!({});
+ second["sessions"] = json!({"locker": {"token": [1]}});
state["accounts"].as_array_mut().unwrap().push(second);
home.write_vault(&state);