💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add Paste commands to the new CLI
Manav Rathia172d3dbb134
diff --git a/.github/scripts/ci/paths.json b/.github/scripts/ci/paths.jsonindex 05ba516917..40df139811 100644--- a/.github/scripts/ci/paths.json+++ b/.github/scripts/ci/paths.json@@ -114,6 +114,7 @@"rust/crates/core/**","rust/crates/exif/**","rust/crates/location/**",+ "rust/crates/paste/**","rust/crates/photos/**","rust/crates/photos-export/**","rust/crates/test-support/**",diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 0f01d1006f..709cd6beb9 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2543,6 +2543,7 @@ dependencies = ["ente-auth","ente-collections","ente-core",+ "ente-paste","ente-photos","ente-photos-export","ente-test-support",diff --git a/rust/apps/cli-next/Cargo.toml b/rust/apps/cli-next/Cargo.tomlindex 5ff362fea9..18ec8c5b11 100644--- a/rust/apps/cli-next/Cargo.toml+++ b/rust/apps/cli-next/Cargo.toml@@ -17,6 +17,7 @@ ente-accounts.workspace = trueente-auth.workspace = trueente-collections.workspace = trueente-core.workspace = true+ente-paste.workspace = trueente-photos.workspace = trueente-photos-export.workspace = truekeyring = { workspace = true, features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] }diff --git a/rust/apps/cli-next/src/api.rs b/rust/apps/cli-next/src/api.rsindex dc154b3a51..c99840c05e 100644--- a/rust/apps/cli-next/src/api.rs+++ b/rust/apps/cli-next/src/api.rs@@ -23,6 +23,37 @@ use crate::{pub(crate) const USER_AGENT: &str = concat!("ente-cli-next/", env!("CARGO_PKG_VERSION"));+pub fn normalize_host(host: &str) -> Result<String> {+ let input = if host.contains("://") {+ host.to_owned()+ } else {+ format!("https://{host}")+ };+ let mut url = Url::parse(&input).context("invalid API host")?;+ if !host.contains("://")+ && url.host_str().is_some_and(|h| {+ h == "localhost"+ || h.trim_matches(['[', ']'])+ .parse::<std::net::IpAddr>()+ .is_ok_and(|ip| ip.is_loopback())+ })+ {+ ensure!(+ url.set_scheme("http").is_ok(),+ "host must be an HTTP or HTTPS origin"+ );+ }+ ensure!(+ matches!(url.scheme(), "http" | "https") && url.host_str().is_some(),+ "host must be an HTTP or HTTPS origin"+ );+ ensure!(+ url.username().is_empty() && url.password().is_none(),+ "host must not contain credentials"+ );+ Ok(url.origin().ascii_serialization())+}+pub fn http() -> Result<Client> {Ok(Client::builder().user_agent(USER_AGENT)diff --git a/rust/apps/cli-next/src/args.rs b/rust/apps/cli-next/src/args.rsindex 875258e688..58a1765e3c 100644--- a/rust/apps/cli-next/src/args.rs+++ b/rust/apps/cli-next/src/args.rs@@ -15,7 +15,10 @@ use serde::{Deserialize, Serialize};ente-cli-next photos export <DIR>Auth backups:ente-cli-next account login --app auth- ente-cli-next auth export <DIR>"+ ente-cli-next auth export <DIR>+Paste:+ ente-cli-next paste create --input <PATH>+ ente-cli-next paste consume <URL>")]pub struct Cli {#[command(flatten)]@@ -95,6 +98,11 @@ pub enum Command {#[command(subcommand)]command: AuthCommand,},+ #[command(about = "Share and consume one-time encrypted text without an account")]+ Paste {+ #[command(subcommand)]+ command: PasteCommand,+ },#[command(about = "Manage Ente accounts", alias = "accounts")]Account {#[command(subcommand)]@@ -114,6 +122,63 @@ Keep the same home and key across unattended invocations."},}+#[derive(Subcommand)]+pub enum PasteCommand {+ #[command(+ about = "Create a one-time encrypted paste",+ after_long_help = "Supply TEXT or --input PATH; --input - reads stdin verbatim.+With neither, reads piped stdin.+Text must be nonblank and at most 4,000 Unicode scalar values.+Pastes expire after 24 hours.+With --password, uses ENTE_CLI_PASSWORD when set; otherwise prompts for a paste password and confirmation.+With --password --no-input, ENTE_CLI_PASSWORD is required.+Prints the paste URL. With --json: {\"url\": \"...\"}. Requires network access."+ )]+ Create {+ #[arg(+ conflicts_with = "input",+ help = "Literal paste text; defaults to piped stdin"+ )]+ text: Option<String>,+ #[arg(+ long,+ value_name = "PATH|-",+ help = "Read plain UTF-8 text from a file, or stdin with -"+ )]+ input: Option<PathBuf>,+ #[arg(long, help = "Require a password to decrypt the paste")]+ password: bool,+ #[arg(long, help = "Ente API server; defaults to api.ente.com")]+ host: Option<String>,+ #[arg(+ long,+ default_value = "https://paste.ente.com",+ value_name = "URL",+ help = "Website used in the returned link"+ )]+ paste_origin: url::Url,+ },+ #[command(+ about = "Consume a paste and permanently remove its server copy",+ after_long_help = "Supply a URL including its #key fragment, or TOKEN --key KEY.+Protected pastes use ENTE_CLI_PASSWORD when set; otherwise prompt for the paste password.+Consumes the paste before decryption, even with a wrong password or key.+A wrong ENTE_CLI_PASSWORD fails immediately; prompted retries work only while this command stays running.+Prints the text without adding a newline. Terminal controls are escaped except tabs and newlines.+With --json: {\"text\": \"...\"}. --raw affects plain terminal output only. Requires network access."+ )]+ Consume {+ #[arg(value_name = "URL|TOKEN", help = "Paste URL or access token")]+ link_or_token: String,+ #[arg(long, help = "Decryption key when passing an access token")]+ key: Option<String>,+ #[arg(long, help = "Print text verbatim even on a terminal")]+ raw: bool,+ #[arg(long, help = "Ente API server; defaults to api.ente.com")]+ host: Option<String>,+ },+}+#[derive(Subcommand)]pub enum AuthCommand {#[command(about = "Make an authenticated API request", after_help = API_HELP)]@@ -121,16 +186,17 @@ pub enum AuthCommand {#[command(about = "Export your Auth codes; encrypted by default")]#[command(after_long_help = "Refreshes Auth data first; --offline uses previously synced data.-Set ENTE_CLI_EXPORT_PASSWORD for encrypted export with --no-input.+Encrypted export uses ENTE_CLI_PASSWORD when set; otherwise prompts for an export password.+With --no-input, encrypted export requires ENTE_CLI_PASSWORD.DIR receives dated backups. --output writes a new file, or backup bytes to stdout with -.--json formats file/directory summaries; stdout backups contain only the artifact.")]Export(AuthExportArgs),#[command(about = "Decrypt an Auth export without an account")]- #[command(- after_long_help = "Reads a backup without network access. Set ENTE_CLI_EXPORT_PASSWORD with --no-input.-Writes readable URI lines to stdout, or a new --output file. --json only formats the file summary."- )]+ #[command(after_long_help = "Reads a backup without network access.+Uses ENTE_CLI_PASSWORD as the export password when set; otherwise prompts.+With --no-input, ENTE_CLI_PASSWORD is required.+Writes readable URI lines to stdout, or a new --output file. --json only formats the file summary.")]Decrypt {#[arg(value_name = "PATH", help = "Encrypted Auth backup to decrypt")]input: PathBuf,diff --git a/rust/apps/cli-next/src/auth/mod.rs b/rust/apps/cli-next/src/auth/mod.rsindex dbbf07e7bc..ec086e8514 100644--- a/rust/apps/cli-next/src/auth/mod.rs+++ b/rust/apps/cli-next/src/auth/mod.rs@@ -1,10 +1,9 @@mod output;pub mod replica;-use std::{env, fs, path::PathBuf};+use std::{fs, path::PathBuf};-use anyhow::{Context, Result, bail, ensure};-use dialoguer::{Password, console::Term};+use anyhow::{Context, Result, bail};use ente_auth::backup;use serde_json::json;use zeroize::Zeroizing;@@ -12,7 +11,7 @@ use zeroize::Zeroizing;use crate::{api,args::{App, AuthCommand, AuthExportArgs, Options},- db, home,+ db, home, password,};use output::Destination;@@ -25,7 +24,7 @@ pub async fn run(command: AuthCommand, selected: Option<&str>, options: &Optionsdestination.prepare()?;let encrypted =fs::read(&input).with_context(|| format!("cannot read {}", input.display()))?;- let password = export_password(false, options)?;+ let password = password::read("Export password", false, options)?;let plaintext = backup::decrypt(&encrypted, &password).with_context(|| format!("cannot decrypt {}", input.display()))?;if let Some(path) = destination.publish(&plaintext)? {@@ -56,7 +55,7 @@ async fn export(args: AuthExportArgs, selected: Option<&str>, options: &Options)let password = if args.plaintext {None} else {- Some(export_password(true, options)?)+ Some(password::read("Export password", true, options)?)};let payload = {let (account, home) = home::open_account(selected, !options.offline)?;@@ -103,27 +102,3 @@ async fn export(args: AuthExportArgs, selected: Option<&str>, options: &Options)}Ok(())}--fn export_password(confirm: bool, options: &Options) -> Result<Zeroizing<String>> {- let password = match env::var("ENTE_CLI_EXPORT_PASSWORD") {- Ok(password) => Zeroizing::new(password),- Err(env::VarError::NotUnicode(_)) => bail!("ENTE_CLI_EXPORT_PASSWORD must be UTF-8"),- Err(env::VarError::NotPresent) => {- ensure!(- options.can_prompt(),- "set ENTE_CLI_EXPORT_PASSWORD for noninteractive encrypted export or decryption"- );- let mut prompt = Password::new().with_prompt("Export password");- if confirm {- prompt =- prompt.with_confirmation("Confirm export password", "Passwords do not match");- }- Zeroizing::new(prompt.interact_on(&Term::stderr())?)- }- };- ensure!(- !password.is_empty(),- "export password cannot be empty; set ENTE_CLI_EXPORT_PASSWORD to a nonempty value"- );- Ok(password)-}diff --git a/rust/apps/cli-next/src/login.rs b/rust/apps/cli-next/src/login.rsindex e7ff0b93b9..4ebb78247d 100644--- a/rust/apps/cli-next/src/login.rs+++ b/rust/apps/cli-next/src/login.rs@@ -8,7 +8,6 @@ use ente_accounts::{};use ente_core::http::{Api, ApiConfig, Http};use serde::Deserialize;-use url::Url;use uuid::Uuid;use zeroize::{ZeroizeOnDrop, Zeroizing};@@ -21,7 +20,7 @@ use crate::{pub async fn login(args: LoginArgs, options: &Options) -> Result<(State, usize)> {let app = args.app;- let host = args.host.as_deref().map(normalize_host).transpose()?;+ let host = args.host.as_deref().map(api::normalize_host).transpose()?;let credentials = args.input.as_deref().map(Credentials::read).transpose()?;let interactive = credentials.is_none() && options.can_prompt();ensure!(@@ -157,37 +156,6 @@ pub async fn login(args: LoginArgs, options: &Options) -> Result<(State, usize)>result}-fn normalize_host(host: &str) -> Result<String> {- let input = if host.contains("://") {- host.to_owned()- } else {- format!("https://{host}")- };- let mut url = Url::parse(&input).context("invalid API host")?;- if !host.contains("://")- && url.host_str().is_some_and(|h| {- h == "localhost"- || h.trim_matches(['[', ']'])- .parse::<std::net::IpAddr>()- .is_ok_and(|ip| ip.is_loopback())- })- {- ensure!(- url.set_scheme("http").is_ok(),- "host must be an HTTP or HTTPS origin"- );- }- ensure!(- matches!(url.scheme(), "http" | "https") && url.host_str().is_some(),- "host must be an HTTP or HTTPS origin"- );- ensure!(- url.username().is_empty() && url.password().is_none(),- "host must not contain credentials"- );- Ok(url.origin().ascii_serialization())-}-#[derive(Deserialize, ZeroizeOnDrop)]#[serde(deny_unknown_fields)]struct Credentials {diff --git a/rust/apps/cli-next/src/main.rs b/rust/apps/cli-next/src/main.rsindex 38ae6f3f0d..3cb1459124 100644--- a/rust/apps/cli-next/src/main.rs+++ b/rust/apps/cli-next/src/main.rs@@ -6,6 +6,8 @@ mod db;mod home;mod login;mod output;+mod password;+mod paste;mod photos;mod vault;@@ -81,6 +83,7 @@ async fn run(cli: Cli) -> Result<()> {Command::Auth { selector, command } => {auth::run(command, selector.account.as_deref(), &options).await}+ Command::Paste { command } => paste::run(command, &options).await,Command::Account { command } => account_command(command, &options).await,Command::Vault {command:diff --git a/rust/apps/cli-next/src/password.rs b/rust/apps/cli-next/src/password.rsnew file mode 100644index 0000000000..2424c8cc6b--- /dev/null+++ b/rust/apps/cli-next/src/password.rs@@ -0,0 +1,43 @@+use std::env;++use anyhow::{Result, bail, ensure};+use dialoguer::{Password, console::Term};+use zeroize::Zeroizing;++use crate::args::Options;++pub fn read(label: &str, confirm: bool, options: &Options) -> Result<Zeroizing<String>> {+ match supplied(label, options)? {+ Some(password) => Ok(password),+ None => prompt(label, confirm),+ }+}++pub fn supplied(label: &str, options: &Options) -> Result<Option<Zeroizing<String>>> {+ match env::var("ENTE_CLI_PASSWORD") {+ Ok(password) => {+ ensure!(!password.is_empty(), "ENTE_CLI_PASSWORD must be nonempty");+ Ok(Some(Zeroizing::new(password)))+ }+ Err(env::VarError::NotUnicode(_)) => bail!("ENTE_CLI_PASSWORD must be UTF-8"),+ Err(env::VarError::NotPresent) => {+ ensure!(+ options.can_prompt(),+ "set ENTE_CLI_PASSWORD to the {} when running without interactive prompts",+ label.to_lowercase()+ );+ Ok(None)+ }+ }+}++pub fn prompt(label: &str, confirm: bool) -> Result<Zeroizing<String>> {+ let mut prompt = Password::new().with_prompt(label);+ if confirm {+ prompt = prompt.with_confirmation(+ format!("Confirm {}", label.to_lowercase()),+ "Passwords do not match",+ );+ }+ Ok(Zeroizing::new(prompt.interact_on(&Term::stderr())?))+}diff --git a/rust/apps/cli-next/src/paste.rs b/rust/apps/cli-next/src/paste.rsnew file mode 100644index 0000000000..e5a9a1b40c--- /dev/null+++ b/rust/apps/cli-next/src/paste.rs@@ -0,0 +1,213 @@+use std::{+ io::{IsTerminal, Write},+ path::Path,+};++use anyhow::{Context, Result, ensure};+use ente_accounts::DEFAULT_API_ORIGIN;+use ente_paste::{Client, OpenPaste, PasteLink, PasteSession};+use serde_json::json;+use zeroize::Zeroizing;++use crate::{+ api,+ args::{Options, PasteCommand},+ output, password, read_input,+};++pub async fn run(command: PasteCommand, options: &Options) -> Result<()> {+ ensure!(!options.offline, "this command requires network access");+ match command {+ PasteCommand::Create {+ text,+ input,+ password: protected,+ host,+ paste_origin,+ } => {+ let text = Zeroizing::new(match text {+ Some(text) => text,+ None => {+ ensure!(+ input.is_some() || !std::io::stdin().is_terminal(),+ "provide TEXT, --input PATH|-, or piped stdin"+ );+ String::from_utf8(+ read_input(input.as_deref().unwrap_or(Path::new("-")))?.to_vec(),+ )+ .context("paste input must be UTF-8")?+ }+ });+ ente_paste::validate_text(&text)?;+ let paste_origin = api::normalize_host(paste_origin.as_str())?;+ let password = protected+ .then(|| password::read("Paste password", true, options))+ .transpose()?;+ let link = client(host)?+ .create(&text, password.as_deref().map(String::as_str))+ .await?;+ let url = link.url(&paste_origin);+ output::action(options.json, &json!({ "url": url }), &url)+ }+ PasteCommand::Consume {+ link_or_token,+ key,+ raw,+ host,+ } => {+ let link = PasteLink::parse(&link_or_token, key.as_deref())?;+ let password = if link.password_required() {+ password::supplied("Paste password", options)?+ } else {+ None+ };+ let text = Zeroizing::new(+ consume(&client(host)?, link, password, || {+ password::prompt("Paste password", false)+ })+ .await?,+ );+ if options.json {+ output::json(&json!({ "text": text.as_str() }))+ } else {+ let text = display_text(&text, raw, std::io::stdout().is_terminal());+ let mut stdout = std::io::stdout().lock();+ stdout.write_all(text.as_bytes())?;+ stdout.flush().map_err(Into::into)+ }+ }+ }+}++fn client(host: Option<String>) -> Result<Client> {+ Ok(Client::new(+ api::normalize_host(host.as_deref().unwrap_or(DEFAULT_API_ORIGIN))?,+ Some(api::USER_AGENT.into()),+ )?)+}++async fn consume(+ client: &Client,+ link: PasteLink,+ mut password: Option<Zeroizing<String>>,+ mut prompt: impl FnMut() -> Result<Zeroizing<String>>,+) -> Result<String> {+ let mut session = PasteSession::new(link);+ let result: Result<String> = async {+ if let OpenPaste::Text(text) = session.open(client).await? {+ return Ok(text);+ }+ let retry = password.is_none();+ if retry {+ password = Some(prompt()?);+ }+ loop {+ match session+ .consume(client, password.as_deref().map(String::as_str))+ .await+ {+ Err(error @ ente_paste::Error::IncorrectPassword) if retry => {+ eprintln!(+ "{error}. Paste already consumed; exiting will prevent further retries."+ );+ password = Some(prompt()?);+ }+ result => return result.map_err(Into::into),+ }+ }+ }+ .await;+ if session.has_payload() {+ result.context("paste has been consumed and cannot be read again")+ } else {+ result+ }+}++fn display_text(text: &str, raw: bool, terminal: bool) -> std::borrow::Cow<'_, str> {+ if raw || !terminal {+ return text.into();+ }+ let mut output = String::with_capacity(text.len());+ let mut chars = text.chars().peekable();+ while let Some(ch) = chars.next() {+ match ch {+ '\n' | '\t' => output.push(ch),+ '\r' if chars.peek() == Some(&'\n') => {+ chars.next();+ output.push_str("\r\n");+ }+ _ if ch.is_control() => output.extend(ch.escape_default()),+ _ => output.push(ch),+ }+ }+ output.into()+}++#[cfg(test)]+mod tests {+ use super::*;+ use mockito::Server;++ #[test]+ fn output_preserves_text_and_escapes_terminal_controls() {+ let text = "français 🔐\r\n\t\x1b]52;c;AAAA\x07\rhidden\u{85}";+ assert_eq!(display_text(text, false, false), text);+ assert_eq!(display_text(text, true, true), text);+ assert_eq!(+ display_text(text, false, true),+ "français 🔐\r\n\t\\u{1b}]52;c;AAAA\\u{7}\\rhidden\\u{85}"+ );+ }++ #[tokio::test]+ async fn password_retry_and_prompt_failure_never_consume_twice() {+ let (key, payload) = ente_paste::encrypt("protected text", Some("correct")).unwrap();+ let fragment = key.link_fragment();+ let mut server = Server::new_async().await;+ let client = Client::new(server.url(), None).unwrap();+ for cancel_at in [None, Some(1), Some(2)] {+ let guard = server+ .mock("POST", "/paste/guard")+ .with_header("set-cookie", "paste_guard=fixture")+ .expect(if cancel_at == Some(1) { 1 } else { 2 })+ .create_async()+ .await;+ let request = server+ .mock("POST", "/paste/consume")+ .with_body(serde_json::to_string(&payload).unwrap())+ .expect(if cancel_at == Some(1) { 0 } else { 1 })+ .create_async()+ .await;+ let mut prompts = 0;+ let link = PasteLink::parse("ABC123", Some(&fragment)).unwrap();+ let result = consume(&client, link, None, || {+ prompts += 1;+ if cancel_at == Some(prompts) {+ anyhow::bail!("prompt cancelled");+ }+ match prompts {+ 1 => Ok(Zeroizing::new("wrong".into())),+ 2 => Ok(Zeroizing::new("correct".into())),+ _ => panic!("unexpected prompt"),+ }+ })+ .await;+ if cancel_at.is_some() {+ let error = format!("{:#}", result.unwrap_err());+ assert!(error.contains("prompt cancelled"));+ assert_eq!(+ error.contains("paste has been consumed"),+ cancel_at == Some(2)+ );+ } else {+ assert_eq!(result.unwrap(), "protected text");+ }+ assert_eq!(prompts, cancel_at.unwrap_or(2));+ guard.assert_async().await;+ request.assert_async().await;+ guard.remove_async().await;+ request.remove_async().await;+ }+ }+}diff --git a/rust/apps/cli-next/tests/cli.rs b/rust/apps/cli-next/tests/cli.rsindex 549fc79c60..b09d75a939 100644--- a/rust/apps/cli-next/tests/cli.rs+++ b/rust/apps/cli-next/tests/cli.rs@@ -37,6 +37,8 @@ fn reads_do_not_initialize_storage() {assert!(help.contains(&format!("=== {binary} vault key generate ===")));assert!(help.contains("--hardlinks"));assert!(help.contains("Linked files share contents, timestamps and permissions."));+ assert!(help.contains(&format!("=== {binary} paste create ===")));+ assert!(help.contains(&format!("=== {binary} paste consume ===")));assert!(help.contains(&format!("=== {binary} account token ===")));for command in ["login", "token"] {let missing_app = home@@ -965,6 +967,9 @@ mod files;#[path = "support/auth.rs"]mod auth;+#[path = "support/paste.rs"]+mod paste;+#[cfg(feature = "museum")]#[path = "support/museum.rs"]mod museum;diff --git a/rust/apps/cli-next/tests/support/auth.rs b/rust/apps/cli-next/tests/support/auth.rsindex 927712f7db..44e2ba07e1 100644--- a/rust/apps/cli-next/tests/support/auth.rs+++ b/rust/apps/cli-next/tests/support/auth.rs@@ -272,7 +272,7 @@ fn encrypted_export_and_independent_decrypt_keep_artifacts_separate_from_summarilet plain = success(home.command(EXPORT).arg("--no-input")- .env("ENTE_CLI_EXPORT_PASSWORD", "")+ .env("ENTE_CLI_PASSWORD", "").output().unwrap(),)@@ -321,7 +321,7 @@ fn encrypted_export_and_independent_decrypt_keep_artifacts_separate_from_summari"--json",]).arg("--no-input")- .env("ENTE_CLI_EXPORT_PASSWORD", password)+ .env("ENTE_CLI_PASSWORD", password).output().unwrap(),);@@ -331,7 +331,7 @@ fn encrypted_export_and_independent_decrypt_keep_artifacts_separate_from_summarilet encoded = fs::read(&encrypted).unwrap();let stream = success(home.command(&["auth", "export", "--offline", "--output", "-", "--json"])- .env("ENTE_CLI_EXPORT_PASSWORD", password)+ .env("ENTE_CLI_PASSWORD", password).output().unwrap(),);@@ -348,7 +348,7 @@ fn encrypted_export_and_independent_decrypt_keep_artifacts_separate_from_summari.arg("--no-input").env_remove("ENTE_CLI_VAULT_KEY").env("ENTE_CLI_HOME", &absent_home)- .env("ENTE_CLI_EXPORT_PASSWORD", password);+ .env("ENTE_CLI_PASSWORD", password);command};assert_eq!(success(command().output().unwrap()).stdout, plain);@@ -380,7 +380,7 @@ fn encrypted_export_and_independent_decrypt_keep_artifacts_separate_from_summari);assert_eq!(fs::read(&encrypted).unwrap(), encoded);let wrong = command()- .env("ENTE_CLI_EXPORT_PASSWORD", "wrong")+ .env("ENTE_CLI_PASSWORD", "wrong").output().unwrap();assert!(failure(&wrong).contains(&format!("cannot decrypt {}: ", encrypted.display())));@@ -405,10 +405,10 @@ fn password_and_destination_errors_are_resolved_before_account_access() {let mut command = home.command(&["auth", "export", "--output", path.to_str().unwrap()]);command.arg("--no-input");if let Some(value) = value {- command.env("ENTE_CLI_EXPORT_PASSWORD", value);+ command.env("ENTE_CLI_PASSWORD", value);}let output = command.output().unwrap();- assert!(failure(&output).contains("ENTE_CLI_EXPORT_PASSWORD"));+ assert!(failure(&output).contains("ENTE_CLI_PASSWORD"));assert!(output.stdout.is_empty());assert!(!path.exists());}@@ -417,17 +417,14 @@ fn password_and_destination_errors_are_resolved_before_account_access() {use std::os::unix::ffi::OsStringExt;let output = home.command(&["auth", "export", "--output", path.to_str().unwrap()])- .env(- "ENTE_CLI_EXPORT_PASSWORD",- std::ffi::OsString::from_vec(vec![255]),- )+ .env("ENTE_CLI_PASSWORD", std::ffi::OsString::from_vec(vec![255])).output().unwrap();assert!(failure(&output).contains("must be UTF-8"));}let missing = home.run(&["auth", "decrypt", path.to_str().unwrap()]);assert!(failure(&missing).contains(&format!("cannot read {}", path.display())));- assert!(!failure(&missing).contains("ENTE_CLI_EXPORT_PASSWORD"));+ assert!(!failure(&missing).contains("ENTE_CLI_PASSWORD"));assert!(missing.stdout.is_empty());fs::write(&path, "existing").unwrap();let occupied = home.run(&["auth", "export", "--output", path.to_str().unwrap()]);diff --git a/rust/apps/cli-next/tests/support/paste.rs b/rust/apps/cli-next/tests/support/paste.rsnew file mode 100644index 0000000000..9c13839302--- /dev/null+++ b/rust/apps/cli-next/tests/support/paste.rs@@ -0,0 +1,289 @@+use super::*;+use std::sync::{Arc, Mutex};++use ente_paste::{PasteLink, PastePayload};+use mockito::{Matcher, Server};++fn command(home: &TestHome, server: &Server, args: &[&str]) -> Command {+ let mut command = home.command(args);+ command+ .args(["--host", server.url().trim_start_matches("http://")])+ .env("ENTE_CLI_HOME", home.dir.path().join("unused"))+ .env("ENTE_CLI_VAULT_KEY", "invalid");+ command+}++#[test]+fn create_and_consume_preserve_each_input_without_account_storage() {+ let home = TestHome::new();+ let mut server = Server::new();+ let file = home.dir.path().join("text.txt");+ fs::write(&file, "file\r\n\t🔐\n").unwrap();+ for (args, stdin, expected, protected, as_json) in [+ (+ vec!["literal text"],+ "ignored",+ "literal text",+ false,+ false,+ ),+ (+ vec!["--input", file.to_str().unwrap()],+ "ignored",+ "file\r\n\t🔐\n",+ false,+ true,+ ),+ (+ vec!["--input", "-"],+ " pipe\r\n\t\x1b]52;c;AAA\x07\n\n",+ " pipe\r\n\t\x1b]52;c;AAA\x07\n\n",+ false,+ false,+ ),+ (vec![], "hello\n", "hello\n", false, false),+ (+ vec!["protected", "--password"],+ "ignored",+ "protected",+ true,+ true,+ ),+ ] {+ let captured = Arc::new(Mutex::new(None));+ let body = captured.clone();+ let create = server+ .mock("POST", "/paste/create")+ .match_header(+ "user-agent",+ concat!("ente-cli-next/", env!("CARGO_PKG_VERSION")),+ )+ .with_body_from_request(move |request| {+ *body.lock().unwrap() =+ Some(serde_json::from_slice::<PastePayload>(request.body().unwrap()).unwrap());+ br#"{"accessToken":"ABC123"}"#.to_vec()+ })+ .expect(1)+ .create();+ let mut create_command = command(&home, &server, &["paste", "create"]);+ create_command+ .args(args)+ .args(["--paste-origin", "https://paste.example.test/?ignored=1"])+ .arg("--no-input")+ .env(+ "ENTE_CLI_PASSWORD",+ if protected { " password " } else { "" },+ );+ if as_json {+ create_command.arg("--json");+ }+ let mut child = create_command.stdin(Stdio::piped()).spawn().unwrap();+ child+ .stdin+ .take()+ .unwrap()+ .write_all(stdin.as_bytes())+ .unwrap();+ let output = success(child.wait_with_output().unwrap());+ assert!(output.stderr.is_empty());+ let url = if as_json {+ let value: Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(value.as_object().unwrap().len(), 1);+ value["url"].as_str().unwrap().to_owned()+ } else {+ String::from_utf8(output.stdout)+ .unwrap()+ .strip_suffix('\n')+ .unwrap()+ .to_owned()+ };+ assert!(url.starts_with("https://paste.example.test/ABC123#"));+ let link = PasteLink::parse(&url, None).unwrap();+ assert_eq!(link.password_required(), protected);+ create.assert();+ create.remove();+ let payload = captured.lock().unwrap().take().unwrap();+ let guard = server+ .mock("POST", "/paste/guard")+ .with_header("set-cookie", "paste_guard=fixture")+ .expect(if protected { 2 } else { 1 })+ .create();+ let consume = server+ .mock("POST", "/paste/consume")+ .with_body(serde_json::to_string(&payload).unwrap())+ .expect(1)+ .create();+ let mut consume_command = command(&home, &server, &["paste", "consume"]);+ if as_json {+ consume_command+ .arg(&link.access_token)+ .args(["--key", &link.key.link_fragment()]);+ } else {+ consume_command.arg(&url);+ }+ consume_command.arg("--no-input").env(+ "ENTE_CLI_PASSWORD",+ if protected { " password " } else { "" },+ );+ if as_json {+ consume_command.args(["--json", "--raw"]);+ }+ let output = success(consume_command.output().unwrap());+ assert!(output.stderr.is_empty());+ if as_json {+ assert_eq!(+ serde_json::from_slice::<Value>(&output.stdout).unwrap(),+ json!({"text": expected})+ );+ } else {+ assert_eq!(output.stdout, expected.as_bytes());+ }+ guard.assert();+ consume.assert();+ guard.remove();+ consume.remove();+ assert!(!home.dir.path().join("unused").exists());+ }+}++#[test]+fn invalid_input_and_unattended_passwords_fail_before_requests() {+ let home = TestHome::new();+ let mut server = Server::new();+ let requests = server.mock("POST", Matcher::Any).expect(0).create();+ let protected = "https://paste.example.test/ABC123#p-AbCd1234EfGh";+ for (args, error) in [+ (vec!["paste", "create"], "empty"),+ (vec!["paste", "consume", "ABC123"], "key is missing"),+ (+ vec!["paste", "consume", protected, "--key", "AbCd1234EfGh"],+ "keys do not match",+ ),+ (+ vec!["paste", "create", "text", "--input", "-"],+ "cannot be used",+ ),+ (vec!["paste", "create", " \n"], "empty"),+ (+ vec!["paste", "create", "hello", "--offline"],+ "network access",+ ),+ (+ vec!["paste", "consume", protected, "--offline"],+ "network access",+ ),+ (+ vec!["paste", "create", "text", "--password", "--no-input"],+ "ENTE_CLI_PASSWORD",+ ),+ (+ vec!["paste", "consume", protected, "--no-input"],+ "ENTE_CLI_PASSWORD",+ ),+ ] {+ let output = command(&home, &server, &args).output().unwrap();+ assert!(failure(&output).contains(error));+ assert!(output.stdout.is_empty());+ }+ for password in [std::ffi::OsString::from("")].into_iter().chain({+ #[cfg(unix)]+ {+ use std::os::unix::ffi::OsStringExt;+ vec![std::ffi::OsString::from_vec(vec![255])]+ }+ #[cfg(not(unix))]+ {+ vec![]+ }+ }) {+ let output = command(&home, &server, &["paste", "consume", protected])+ .env("ENTE_CLI_PASSWORD", password)+ .output()+ .unwrap();+ assert!(failure(&output).contains("ENTE_CLI_PASSWORD"));+ assert!(output.stdout.is_empty());+ }+ let missing = home.dir.path().join("missing.txt");+ let output = command(+ &home,+ &server,+ &[+ "paste",+ "create",+ "--input",+ missing.to_str().unwrap(),+ "--password",+ ],+ )+ .output()+ .unwrap();+ assert!(failure(&output).contains(missing.to_str().unwrap()));+ fs::write(&missing, [255]).unwrap();+ let output = command(+ &home,+ &server,+ &["paste", "create", "--input", missing.to_str().unwrap()],+ )+ .output()+ .unwrap();+ assert!(failure(&output).contains("UTF-8"));+ requests.assert();+ assert!(!home.dir.path().join("unused").exists());+}++#[test]+fn consume_failures_report_whether_payload_was_retrieved() {+ let home = TestHome::new();+ let mut server = Server::new();+ for protected in [false, true] {+ let (key, payload) = ente_paste::encrypt("text", protected.then_some("correct")).unwrap();+ let link = PasteLink {+ access_token: "ABC123".into(),+ key,+ };+ let mut url = link.url("https://paste.example.test");+ if !protected {+ let last = url.pop().unwrap();+ url.push(if last == 'A' { 'B' } else { 'A' });+ }+ let unavailable = server+ .mock("POST", "/paste/guard")+ .with_status(410)+ .create();+ let output = command(&home, &server, &["paste", "consume", &url])+ .env("ENTE_CLI_PASSWORD", "correct")+ .output()+ .unwrap();+ assert!(failure(&output).contains("paste is unavailable"));+ assert!(!failure(&output).contains("paste has been consumed"));+ assert!(output.stdout.is_empty());+ unavailable.assert();+ unavailable.remove();+ let guard = server+ .mock("POST", "/paste/guard")+ .with_header("set-cookie", "paste_guard=fixture")+ .expect(if protected { 2 } else { 1 })+ .create();+ let consume = server+ .mock("POST", "/paste/consume")+ .with_body(serde_json::to_string(&payload).unwrap())+ .expect(1)+ .create();+ let output = command(&home, &server, &["paste", "consume", &url, "--json"])+ .env("ENTE_CLI_PASSWORD", "wrong")+ .output()+ .unwrap();+ assert!(failure(&output).contains(if protected {+ "incorrect paste password"+ } else {+ "Decryption failed"+ }));+ assert!(failure(&output).contains("paste has been consumed and cannot be read again"));+ assert!(output.stdout.is_empty());+ guard.assert();+ consume.assert();+ guard.remove();+ consume.remove();+ }+ assert!(!home.dir.path().join("unused").exists());+}diff --git a/rust/crates/paste/src/lib.rs b/rust/crates/paste/src/lib.rsindex a14478167a..4a89f91fda 100644--- a/rust/crates/paste/src/lib.rs+++ b/rust/crates/paste/src/lib.rs@@ -24,7 +24,7 @@ pub enum Error {#[error("base64 decode error: {0}")]Base64Decode(#[from] b64::DecodeError),- #[error("incorrect paste password")]+ #[error("incorrect paste password or key")]IncorrectPassword,#[error("paste is unavailable")]@@ -236,11 +236,19 @@ pub struct PasteSession {}impl PasteSession {- pub fn parse(input: &str) -> Result<Self> {- Ok(Self {- link: PasteLink::parse(input, None)?,+ pub fn new(link: PasteLink) -> Self {+ Self {+ link,payload: None,- })+ }+ }++ pub fn parse(input: &str) -> Result<Self> {+ Ok(Self::new(PasteLink::parse(input, None)?))+ }++ pub fn has_payload(&self) -> bool {+ self.payload.is_some()}pub async fn open(&mut self, client: &Client) -> Result<OpenPaste> {@@ -758,13 +766,10 @@ mod tests {.await;let client = Client::new(server.url(), None).unwrap();- let mut session = PasteSession {- link: PasteLink {- access_token: access_token.to_string(),- key,- },- payload: None,- };+ let mut session = PasteSession::new(PasteLink {+ access_token: access_token.to_string(),+ key,+ });assert!(matches!(session.open(&client).await.unwrap(),