π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Extract paste into a crate, drop the CLI error remapping
Manav Rathi13b929f3e707
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 43e5a11a1e..78b36c4d1b 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2420,6 +2420,19 @@ dependencies = ["tiff 0.10.3",]+[[package]]+name = "ente-paste"+version = "0.0.0"+dependencies = [+ "ente-core",+ "mockito",+ "serde",+ "serde_json",+ "thiserror 2.0.18",+ "tokio",+ "url",+]+[[package]]name = "ente-photos"version = "0.0.0"@@ -2459,6 +2472,7 @@ dependencies = ["dirs 5.0.1","ente-accounts","ente-core",+ "ente-paste","ente-test-support","env_logger 0.11.10","futures",@@ -2466,7 +2480,6 @@ dependencies = ["log","mockito","open",- "reqwest 0.12.28","rusqlite","serde","serde_json",@@ -2474,6 +2487,7 @@ dependencies = ["srp","thiserror 2.0.18","tokio",+ "url","urlencoding","uuid","zeroize",diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex 1266e3fb60..584110964b 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -14,6 +14,7 @@ members = ["crates/contacts","crates/core","crates/ensu",+ "crates/paste","crates/image","crates/photos","crates/test-support",@@ -26,6 +27,7 @@ ente-accounts = { path = "crates/accounts" }ente-contacts = { path = "crates/contacts" }ente-core = { path = "crates/core" }ente-image = { path = "crates/image" }+ente-paste = { path = "crates/paste" }ente-photos = { path = "crates/photos" }ente-rs = { path = "apps/cli" }ente-test-support = { path = "crates/test-support" }diff --git a/rust/apps/cli/Cargo.toml b/rust/apps/cli/Cargo.tomlindex dfb3041566..be7cf49b07 100644--- a/rust/apps/cli/Cargo.toml+++ b/rust/apps/cli/Cargo.toml@@ -23,12 +23,12 @@ required-features = ["museum"]clap = { version = "4.5", features = ["derive", "env"] }ente-accounts.workspace = trueente-core = { workspace = true, features = ["srp"] }+ente-paste.workspace = trueserde.workspace = trueserde_json = "1.0"# Async runtime and networkingtokio = { version = "1.41", features = ["full"] }-reqwest = { version = "0.12", features = ["json", "stream"] }futures = "0.3"# Cryptography - using ente-core pure Rust implementation@@ -56,5 +56,6 @@ zip = "2.2"[dev-dependencies]ente-test-support.workspace = truemockito = "1.6"+url = "2.5.8"sha2 = "0.11"srp = { version = "0.7.0-rc.3", default-features = false }diff --git a/rust/apps/cli/src/auth_flow.rs b/rust/apps/cli/src/auth_flow.rsindex b2b7e7105e..e4719dbbdf 100644--- a/rust/apps/cli/src/auth_flow.rs+++ b/rust/apps/cli/src/auth_flow.rs@@ -37,7 +37,6 @@ fn shared_client(fn to_shared_error(error: Error) -> shared::Error {match error {Error::Io(source) => shared::Error::Generic(source.to_string()),- Error::Network(source) => shared::Error::Generic(source.to_string()),Error::Serialization(source) => shared::Error::Serialization(source),Error::Database(source) => shared::Error::Generic(source.to_string()),Error::Crypto(message) => shared::Error::Crypto(message),@@ -48,21 +47,7 @@ fn to_shared_error(error: Error) -> shared::Error {Error::Srp(message) => shared::Error::Srp(message),Error::Base64Decode(source) => shared::Error::Base64Decode(source),Error::Zip(source) => shared::Error::Generic(source.to_string()),- Error::ApiError {- status,- code,- message: _,- } => shared::Error::from(match code {- Some(code) => ente_core::http::Error::Api {- status,- path: String::new(),- code,- },- None => ente_core::http::Error::Http {- status,- path: String::new(),- },- }),+ Error::Http(source) => shared::Error::Http(source),Error::Generic(message) => shared::Error::Generic(message),}}diff --git a/rust/apps/cli/src/commands/paste.rs b/rust/apps/cli/src/commands/paste.rsindex 00d43c59f8..f94510d661 100644--- a/rust/apps/cli/src/commands/paste.rs+++ b/rust/apps/cli/src/commands/paste.rs@@ -3,24 +3,13 @@ use crate::{cli::paste::{PasteCommand, PasteSubcommands},models::error::{Error, Result},};-use base64::Engine;-use base64::engine::general_purpose::STANDARD as BASE64;use dialoguer::Password;-use ente_core::crypto::{self, Key, argon, blob, secretbox};-use reqwest::{Client, StatusCode, header};-use serde::{Deserialize, Serialize};+use ente_paste::{PasteKey, PastePayload};use std::ffi::OsStr;use std::io::{self, IsTerminal, Read};use std::path::PathBuf;-const MAX_PASTE_CHARS: usize = 4000;-const FRAGMENT_SECRET_LENGTH: usize = 12;-const FRAGMENT_SECRET_ALPHABET: &[u8] =- b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";-const PASTE_GUARD_COOKIE: &str = "paste_guard";const PASTE_PASSWORD_ENV: &str = "ENTE_PASTE_PASSWORD";-const PASSWORD_FRAGMENT_PREFIX: &str = "p-";-const PASSWORD_KDF_CONTEXT: &str = "ente-paste-password-v1";pub async fn handle_paste_command(cmd: PasteCommand) -> Result<()> {match cmd.command {@@ -37,8 +26,12 @@ pub async fn handle_paste_command(cmd: PasteCommand) -> Result<()> {} else {None};- let link = create_paste(&endpoint, &paste_origin, &text, password.as_deref()).await?;- println!("{link}");+ let client = paste_client(endpoint)?;+ let (access_token, paste_key) = client.create(&text, password.as_deref()).await?;+ println!(+ "{}",+ ente_paste::paste_link(&paste_origin, &access_token, &paste_key)+ );Ok(())}PasteSubcommands::Consume {@@ -47,14 +40,100 @@ pub async fn handle_paste_command(cmd: PasteCommand) -> Result<()> {key,endpoint,} => {- let (access_token, paste_key) = parse_paste_reference(&link_or_token, key)?;- let text = consume_paste(&endpoint, &access_token, &paste_key).await?;+ let (access_token, paste_key) =+ ente_paste::parse_reference(&link_or_token, key.as_deref())?;+ let text = consume_paste(endpoint, &access_token, &paste_key).await?;print_consumed_paste(&text, raw);Ok(())}}}+fn paste_client(endpoint: String) -> Result<ente_paste::Client> {+ Ok(ente_paste::Client::new(+ endpoint,+ Some(USER_AGENT.to_string()),+ )?)+}++async fn consume_paste(+ endpoint: String,+ access_token: &str,+ paste_key: &PasteKey,+) -> Result<String> {+ consume_paste_with_password_resolver(+ endpoint,+ access_token,+ paste_key,+ resolve_paste_password_attempt,+ )+ .await+}++async fn consume_paste_with_password_resolver<F>(+ endpoint: String,+ access_token: &str,+ paste_key: &PasteKey,+ resolve_password: F,+) -> Result<String>+where+ F: FnOnce() -> Result<PastePasswordAttempt>,+{+ let client = paste_client(endpoint)?;+ let password = if paste_key.password_required {+ client.check(access_token).await?;+ Some(resolve_password()?)+ } else {+ None+ };+ let payload = client.consume(access_token).await?;++ match password {+ Some(password) => decrypt_password_protected_paste(paste_key, &payload, password),+ None => Ok(ente_paste::decrypt(&payload, paste_key, None)?),+ }+}++fn decrypt_password_protected_paste(+ paste_key: &PasteKey,+ payload: &PastePayload,+ password: PastePasswordAttempt,+) -> Result<String> {+ decrypt_password_protected_paste_with_prompt(+ paste_key,+ payload,+ password,+ prompt_raw_paste_password,+ )+}++fn decrypt_password_protected_paste_with_prompt<F>(+ paste_key: &PasteKey,+ payload: &PastePayload,+ mut password: PastePasswordAttempt,+ mut prompt_password: F,+) -> Result<String>+where+ F: FnMut() -> Result<String>,+{+ loop {+ match ente_paste::decrypt(payload, paste_key, Some(password.value())) {+ Err(ente_paste::Error::IncorrectPassword) if password.can_retry() => {+ eprintln!("Incorrect paste password. Try again.");+ password = PastePasswordAttempt::Prompted(prompt_valid_paste_password(+ &mut prompt_password,+ )?);+ }+ Err(ente_paste::Error::IncorrectPassword) => {+ return Err(Error::AuthenticationFailed(+ "Incorrect paste password".to_string(),+ ));+ }+ result => return Ok(result?),+ }+ }+}+fn print_consumed_paste(text: &str, raw: bool) {if !raw && io::stdout().is_terminal() {print!("{}", terminal_safe_paste_text(text));@@ -100,9 +179,10 @@ fn read_paste_text(text: Option<String>, file: Option<PathBuf>) -> Result<String"Paste text cannot be empty".to_string(),));}- if text.chars().count() > MAX_PASTE_CHARS {+ if text.chars().count() > ente_paste::MAX_PASTE_CHARS {return Err(Error::InvalidInput(format!(- "Paste is limited to {MAX_PASTE_CHARS} characters"+ "Paste is limited to {} characters",+ ente_paste::MAX_PASTE_CHARS)));}Ok(text)@@ -208,534 +288,9 @@ impl PastePasswordAttempt {}}-async fn create_paste(- endpoint: &str,- paste_origin: &str,- text: &str,- password: Option<&str>,-) -> Result<String> {- let client = paste_http_client()?;- let (paste_key, payload) = encrypt_paste_for_create(text, password)?;- let response: CreatePasteResponse =- post_json(&client, endpoint, "/paste/create", &payload, None, None).await?;- Ok(build_paste_link(- paste_origin,- &response.access_token,- &paste_key.link_fragment(),- ))-}--async fn consume_paste(endpoint: &str, access_token: &str, paste_key: &PasteKey) -> Result<String> {- consume_paste_with_password_resolver(- endpoint,- access_token,- paste_key,- resolve_paste_password_attempt,- )- .await-}--async fn consume_paste_with_password_resolver<F>(- endpoint: &str,- access_token: &str,- paste_key: &PasteKey,- resolve_password: F,-) -> Result<String>-where- F: FnOnce() -> Result<PastePasswordAttempt>,-{- let client = paste_http_client()?;- let request = PasteTokenRequest {- access_token: access_token.to_string(),- };- let password = if paste_key.password_required {- guard_cookie(&client, endpoint, &request).await?;- Some(resolve_password()?)- } else {- None- };- let cookie = guard_cookie(&client, endpoint, &request).await?;- let payload = consume_paste_payload(&client, endpoint, &request, &cookie).await?;-- match password {- Some(password) => decrypt_password_protected_paste(paste_key, &payload, password),- None => decrypt_consumed_paste(paste_key, None, &payload),- }-}--async fn consume_paste_payload(- client: &Client,- endpoint: &str,- request: &PasteTokenRequest,- cookie: &str,-) -> Result<PastePayload> {- post_json(- client,- endpoint,- "/paste/consume",- &request,- Some(("X-Paste-Consume", "1")),- Some(cookie),- )- .await-}--fn decrypt_password_protected_paste(- paste_key: &PasteKey,- payload: &PastePayload,- password: PastePasswordAttempt,-) -> Result<String> {- decrypt_password_protected_paste_with_prompt(- paste_key,- payload,- password,- prompt_raw_paste_password,- )-}--fn decrypt_password_protected_paste_with_prompt<F>(- paste_key: &PasteKey,- payload: &PastePayload,- mut password: PastePasswordAttempt,- mut prompt_password: F,-) -> Result<String>-where- F: FnMut() -> Result<String>,-{- loop {- let key_encryption_key =- derive_paste_key_encryption_key(paste_key, Some(password.value()), payload)?;- let paste_key = match decrypt_paste_key_for_password(payload, &key_encryption_key) {- Ok(paste_key) => paste_key,- Err(Error::AuthenticationFailed(_)) if password.can_retry() => {- eprintln!("Incorrect paste password. Try again.");- password = PastePasswordAttempt::Prompted(prompt_valid_paste_password(- &mut prompt_password,- )?);- continue;- }- Err(error) => return Err(error),- };- return decrypt_consumed_text(&paste_key, payload);- }-}--fn paste_http_client() -> Result<Client> {- Ok(Client::builder().user_agent(USER_AGENT).build()?)-}--async fn guard_cookie(- client: &Client,- endpoint: &str,- request: &PasteTokenRequest,-) -> Result<String> {- let url = api_url(endpoint, "/paste/guard");- let response = client.post(url).json(request).send().await?;- if !response.status().is_success() {- return Err(api_error(response).await);- }-- let cookie_prefix = format!("{PASTE_GUARD_COOKIE}=");- response- .headers()- .get_all(header::SET_COOKIE)- .iter()- .filter_map(|value| value.to_str().ok())- .filter_map(|value| value.split(';').next())- .find(|value| value.starts_with(&cookie_prefix))- .map(str::to_string)- .ok_or_else(|| Error::Generic("Paste guard cookie was not returned".to_string()))-}--async fn post_json<T, B>(- client: &Client,- endpoint: &str,- path: &str,- body: &B,- header_pair: Option<(&str, &str)>,- cookie: Option<&str>,-) -> Result<T>-where- T: for<'de> Deserialize<'de>,- B: Serialize,-{- let mut request = client.post(api_url(endpoint, path)).json(body);- if let Some((name, value)) = header_pair {- request = request.header(name, value);- }- if let Some(cookie) = cookie {- request = request.header(header::COOKIE, cookie);- }-- let response = request.send().await?;- if !response.status().is_success() {- return Err(api_error(response).await);- }-- Ok(response.json().await?)-}--async fn api_error(response: reqwest::Response) -> Error {- let status = response.status();- let body = response.text().await.unwrap_or_default();- let parsed = serde_json::from_str::<ApiErrorBody>(&body).ok();- let message = parsed- .as_ref()- .and_then(|body| body.message.clone().or_else(|| body.code.clone()))- .unwrap_or_else(|| status_message(status, &body));-- Error::ApiError {- status: status.as_u16(),- code: parsed.and_then(|body| body.code),- message,- }-}--fn status_message(status: StatusCode, body: &str) -> String {- if body.trim().is_empty() {- status.to_string()- } else {- body.to_string()- }-}--fn api_url(endpoint: &str, path: &str) -> String {- format!("{}{}", endpoint.trim_end_matches('/'), path)-}--fn build_paste_link(paste_origin: &str, access_token: &str, fragment_secret: &str) -> String {- format!(- "{}/{}#{}",- paste_origin.trim_end_matches('/'),- access_token,- fragment_secret- )-}--fn encrypt_paste_for_create(- text: &str,- password: Option<&str>,-) -> Result<(PasteKey, PastePayload)> {- let paste_key = Key::generate();- let fragment_secret = create_fragment_secret();- let paste_key_reference = PasteKey {- fragment_secret,- password_required: password.is_some(),- };- let encrypted = blob::encrypt_json(- &PasteText {- text: text.to_string(),- },- &paste_key,- )?;- let kdf_secret = paste_key_reference.kdf_secret(password)?;- let key_encryption_key = if password.is_some() {- argon::derive_moderate_key(&kdf_secret)?- } else {- argon::derive_interactive_key(&kdf_secret)?- };- let encrypted_paste_key = secretbox::encrypt(paste_key.as_bytes(), &key_encryption_key.key);-- Ok((- paste_key_reference,- PastePayload {- encrypted_data: crypto::encode_b64(&encrypted.encrypted_data),- decryption_header: crypto::encode_b64(encrypted.decryption_header.as_bytes()),- encrypted_paste_key: crypto::encode_b64(&encrypted_paste_key.encrypted_data),- encrypted_paste_key_nonce: crypto::encode_b64(encrypted_paste_key.nonce.as_bytes()),- kdf_nonce: crypto::encode_b64(key_encryption_key.salt.as_bytes()),- kdf_mem_limit: key_encryption_key.params.mem_limit,- kdf_ops_limit: key_encryption_key.params.ops_limit,- },- ))-}--fn decrypt_consumed_paste(- paste_key: &PasteKey,- password: Option<&str>,- payload: &PastePayload,-) -> Result<String> {- let key_encryption_key = derive_paste_key_encryption_key(paste_key, password, payload)?;- let paste_key = decrypt_wrapped_paste_key(payload, &key_encryption_key)?;- decrypt_consumed_text(&paste_key, payload)-}--fn derive_paste_key_encryption_key(- paste_key: &PasteKey,- password: Option<&str>,- payload: &PastePayload,-) -> Result<crypto::Key> {- let salt = crypto::Salt::try_from_slice(&BASE64.decode(&payload.kdf_nonce)?)?;- let kdf_secret = paste_key.kdf_secret(password)?;- Ok(argon::derive_key(- &kdf_secret,- &salt,- argon::Params {- mem_limit: payload.kdf_mem_limit,- ops_limit: payload.kdf_ops_limit,- },- )?)-}--fn decrypt_paste_key_for_password(- payload: &PastePayload,- key_encryption_key: &Key,-) -> Result<Vec<u8>> {- let (encrypted_paste_key, nonce) = decode_wrapped_paste_key(payload)?;- secretbox::decrypt(&encrypted_paste_key, &nonce, key_encryption_key)- .map_err(|_| Error::AuthenticationFailed("Incorrect paste password".to_string()))-}--fn decrypt_wrapped_paste_key(payload: &PastePayload, key_encryption_key: &Key) -> Result<Vec<u8>> {- let (encrypted_paste_key, nonce) = decode_wrapped_paste_key(payload)?;- Ok(secretbox::decrypt(- &encrypted_paste_key,- &nonce,- key_encryption_key,- )?)-}--fn decode_wrapped_paste_key(payload: &PastePayload) -> Result<(Vec<u8>, crypto::Nonce)> {- let encrypted_paste_key = BASE64.decode(&payload.encrypted_paste_key)?;- let encrypted_paste_key_nonce = BASE64.decode(&payload.encrypted_paste_key_nonce)?;- if encrypted_paste_key.len() < secretbox::MAC_BYTES {- return Err(invalid_paste_payload());- }- let nonce = crypto::Nonce::try_from_slice(&encrypted_paste_key_nonce)- .map_err(|_| invalid_paste_payload())?;- Ok((encrypted_paste_key, nonce))-}--fn decrypt_consumed_text(paste_key: &[u8], payload: &PastePayload) -> Result<String> {- let encrypted_data = BASE64.decode(&payload.encrypted_data)?;- let decryption_header = BASE64.decode(&payload.decryption_header)?;- let text: PasteText = blob::decrypt_json(- &blob::EncryptedBlob {- encrypted_data,- decryption_header: crypto::Header::try_from_slice(&decryption_header)?,- },- &Key::try_from_slice(paste_key)?,- )?;- Ok(text.text)-}--fn invalid_paste_payload() -> Error {- Error::Crypto("The paste data is malformed or corrupted".to_string())-}--fn create_fragment_secret() -> String {- let mut secret = String::with_capacity(FRAGMENT_SECRET_LENGTH);- let threshold = 256 - (256 % FRAGMENT_SECRET_ALPHABET.len());-- while secret.len() < FRAGMENT_SECRET_LENGTH {- for byte in crypto::random_bytes(FRAGMENT_SECRET_LENGTH) {- let byte = usize::from(byte);- if byte >= threshold {- continue;- }- let index = byte % FRAGMENT_SECRET_ALPHABET.len();- secret.push(char::from(FRAGMENT_SECRET_ALPHABET[index]));- if secret.len() == FRAGMENT_SECRET_LENGTH {- break;- }- }- }-- secret-}--fn parse_paste_reference(input: &str, key: Option<String>) -> Result<(String, PasteKey)> {- let input = input.trim();- if input.is_empty() {- return Err(Error::InvalidInput(- "Paste URL or access token is empty".to_string(),- ));- }-- let (access_token, embedded_secret) = match reqwest::Url::parse(input) {- Ok(url) => {- let token = url- .path_segments()- .and_then(|mut segments| segments.rfind(|segment| !segment.is_empty()))- .ok_or_else(|| {- Error::InvalidInput("Paste URL is missing an access token".into())- })?;- (token.to_string(), url.fragment().map(str::to_string))- }- Err(_) => match input.split_once('#') {- Some((token, secret)) => (token.trim().to_string(), Some(secret.trim().to_string())),- None => (input.to_string(), None),- },- };-- if access_token.trim().is_empty() {- return Err(Error::InvalidInput(- "Paste access token is empty".to_string(),- ));- }-- let paste_key = match (embedded_secret, key) {- (Some(embedded), Some(key)) if embedded != key => {- return Err(Error::InvalidInput(- "Paste URL fragment and --key do not match".to_string(),- ));- }- (Some(embedded), _) => PasteKey::parse(&embedded)?,- (None, Some(key)) => PasteKey::parse(&key)?,- (None, None) => {- return Err(Error::InvalidInput(- "Paste key missing. Pass a full paste URL or --key".to_string(),- ));- }- };-- Ok((access_token, paste_key))-}--fn validate_fragment_secret(fragment_secret: &str) -> Result<()> {- if fragment_secret.len() == FRAGMENT_SECRET_LENGTH- && fragment_secret- .bytes()- .all(|byte| byte.is_ascii_alphanumeric())- {- return Ok(());- }-- Err(Error::InvalidInput("Invalid paste key".to_string()))-}--#[derive(Debug, Eq, PartialEq)]-struct PasteKey {- fragment_secret: String,- password_required: bool,-}--impl PasteKey {- fn parse(raw: &str) -> Result<Self> {- let (password_required, fragment_secret) = match raw.strip_prefix(PASSWORD_FRAGMENT_PREFIX)- {- Some(fragment_secret) => (true, fragment_secret),- None => (false, raw),- };- validate_fragment_secret(fragment_secret)?;- Ok(Self {- fragment_secret: fragment_secret.to_string(),- password_required,- })- }-- fn link_fragment(&self) -> String {- if self.password_required {- format!("{PASSWORD_FRAGMENT_PREFIX}{}", self.fragment_secret)- } else {- self.fragment_secret.clone()- }- }-- fn kdf_secret(&self, password: Option<&str>) -> Result<String> {- if self.password_required {- let password = password- .ok_or_else(|| Error::InvalidInput("Paste password is required".to_string()))?;- validate_password(password)?;- Ok(format!(- "{PASSWORD_KDF_CONTEXT}\n{}\n{password}",- self.fragment_secret- ))- } else {- Ok(self.fragment_secret.clone())- }- }-}--#[derive(Debug, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-struct PastePayload {- encrypted_data: String,- decryption_header: String,- encrypted_paste_key: String,- encrypted_paste_key_nonce: String,- kdf_nonce: String,- kdf_mem_limit: u32,- kdf_ops_limit: u32,-}--#[derive(Serialize, Deserialize)]-struct PasteText {- text: String,-}--#[derive(Deserialize)]-struct CreatePasteResponse {- #[serde(rename = "accessToken")]- access_token: String,-}--#[derive(Serialize)]-#[serde(rename_all = "camelCase")]-struct PasteTokenRequest {- access_token: String,-}--#[derive(Deserialize)]-struct ApiErrorBody {- code: Option<String>,- message: Option<String>,-}-#[cfg(test)]mod tests {use super::*;- use mockito::{Matcher, Server};-- #[test]- fn encrypt_then_decrypt_paste_payload() {- let (paste_key, payload) = encrypt_paste_for_create("hello paste", None).unwrap();- let text = decrypt_consumed_paste(&paste_key, None, &payload).unwrap();-- assert_eq!(text, "hello paste");- assert_eq!(payload.kdf_mem_limit, argon::Params::INTERACTIVE.mem_limit);- assert_eq!(payload.kdf_ops_limit, argon::Params::INTERACTIVE.ops_limit);- }-- #[test]- fn encrypt_then_decrypt_password_protected_paste_payload() {- let (paste_key, payload) =- encrypt_paste_for_create("protected paste", Some("correct horse")).unwrap();- let text = decrypt_consumed_paste(&paste_key, Some("correct horse"), &payload).unwrap();-- assert_eq!(text, "protected paste");- assert!(paste_key.password_required);- assert!(- paste_key- .link_fragment()- .starts_with(PASSWORD_FRAGMENT_PREFIX)- );- assert_eq!(payload.kdf_mem_limit, argon::Params::MODERATE.mem_limit);- assert_eq!(payload.kdf_ops_limit, argon::Params::MODERATE.ops_limit);- }-- #[test]- fn reject_wrong_paste_password() {- let (paste_key, payload) =- encrypt_paste_for_create("protected paste", Some("correct horse")).unwrap();- let error = decrypt_consumed_paste(&paste_key, Some("wrong horse"), &payload).unwrap_err();-- assert!(matches!(error, Error::Crypto(_)));- }-- #[test]- fn reject_wrong_env_paste_password() {- let (paste_key, payload) =- encrypt_paste_for_create("protected paste", Some("correct horse")).unwrap();- let error = decrypt_password_protected_paste(- &paste_key,- &payload,- PastePasswordAttempt::Env("wrong horse".to_string()),- )- .unwrap_err();-- assert!(matches!(error, Error::AuthenticationFailed(_)));- }#[test]fn default_tty_output_escapes_controls() {@@ -762,7 +317,7 @@ mod tests {#[test]fn prompted_password_retry_can_recover() {let (paste_key, payload) =- encrypt_paste_for_create("protected paste", Some("correct horse")).unwrap();+ ente_paste::encrypt("protected paste", Some("correct horse")).unwrap();let mut retry_passwords = ["correct horse"].into_iter();let text = decrypt_password_protected_paste_with_prompt(&paste_key,@@ -779,7 +334,7 @@ mod tests {#[test]fn prompted_password_retry_ignores_empty_password() {let (paste_key, payload) =- encrypt_paste_for_create("protected paste", Some("correct horse")).unwrap();+ ente_paste::encrypt("protected paste", Some("correct horse")).unwrap();let mut retry_passwords = ["", "correct horse"].into_iter();let text = decrypt_password_protected_paste_with_prompt(&paste_key,@@ -794,238 +349,16 @@ mod tests {}#[test]- fn prompted_password_retry_does_not_hide_structural_payload_errors() {- let (paste_key, mut payload) =- encrypt_paste_for_create("protected paste", Some("correct horse")).unwrap();- payload.kdf_nonce = "not base64".to_string();- let mut prompts = 0;- let error = decrypt_password_protected_paste_with_prompt(- &paste_key,- &payload,- PastePasswordAttempt::Prompted("correct horse".to_string()),- || {- prompts += 1;- Ok::<_, Error>("correct horse".to_string())- },- )- .unwrap_err();-- assert!(matches!(error, Error::Base64Decode(_)));- assert_eq!(prompts, 0);- }-- #[test]- fn prompted_password_retry_does_not_hide_wrapped_key_payload_errors() {- let (paste_key, mut payload) =- encrypt_paste_for_create("protected paste", Some("correct horse")).unwrap();- payload.encrypted_paste_key = "not base64".to_string();- let mut prompts = 0;- let error = decrypt_password_protected_paste_with_prompt(+ fn wrong_env_password_fails_without_retry() {+ let (paste_key, payload) =+ ente_paste::encrypt("protected paste", Some("correct horse")).unwrap();+ let error = decrypt_password_protected_paste(&paste_key,&payload,- PastePasswordAttempt::Prompted("correct horse".to_string()),- || {- prompts += 1;- Ok::<_, Error>("correct horse".to_string())- },- )- .unwrap_err();-- assert!(matches!(error, Error::Base64Decode(_)));- assert_eq!(prompts, 0);- }-- #[test]- fn parse_full_paste_link() {- let (token, paste_key) =- parse_paste_reference("https://paste.ente.com/ABC123#AbCd1234EfGh", None).unwrap();-- assert_eq!(token, "ABC123");- assert_eq!(- paste_key,- PasteKey {- fragment_secret: "AbCd1234EfGh".to_string(),- password_required: false,- }- );- }-- #[test]- fn parse_password_protected_paste_link() {- let (token, paste_key) =- parse_paste_reference("https://paste.ente.com/ABC123#p-AbCd1234EfGh", None).unwrap();-- assert_eq!(token, "ABC123");- assert_eq!(- paste_key,- PasteKey {- fragment_secret: "AbCd1234EfGh".to_string(),- password_required: true,- }- );- }-- #[test]- fn parse_token_with_key() {- let (token, paste_key) =- parse_paste_reference("ABC123", Some("AbCd1234EfGh".to_string())).unwrap();-- assert_eq!(token, "ABC123");- assert_eq!(- paste_key,- PasteKey {- fragment_secret: "AbCd1234EfGh".to_string(),- password_required: false,- }- );- }-- #[test]- fn parse_token_with_password_key() {- let (token, paste_key) =- parse_paste_reference("ABC123", Some("p-AbCd1234EfGh".to_string())).unwrap();-- assert_eq!(token, "ABC123");- assert_eq!(- paste_key,- PasteKey {- fragment_secret: "AbCd1234EfGh".to_string(),- password_required: true,- }- );- }-- #[test]- fn reject_mismatched_fragment_and_key() {- let error = parse_paste_reference(- "https://paste.ente.com/ABC123#AbCd1234EfGh",- Some("123456789012".to_string()),+ PastePasswordAttempt::Env("wrong horse".to_string()),).unwrap_err();- assert!(matches!(error, Error::InvalidInput(_)));- }-- #[tokio::test]- async fn consume_paste_uses_guard_cookie_and_decrypts_payload() {- let access_token = "ABC123";- let paste_key = PasteKey::parse("AbCd1234EfGh").unwrap();- let payload = test_payload("guarded paste", &paste_key, None);- let mut server = Server::new_async().await;-- let guard = server- .mock("POST", "/paste/guard")- .match_body(Matcher::PartialJson(serde_json::json!({- "accessToken": access_token,- })))- .with_status(200)- .with_header("set-cookie", "paste_guard=test-cookie; Path=/; HttpOnly")- .with_body("{}")- .create_async()- .await;-- let consume = server- .mock("POST", "/paste/consume")- .match_header("x-paste-consume", "1")- .match_header("cookie", "paste_guard=test-cookie")- .match_body(Matcher::PartialJson(serde_json::json!({- "accessToken": access_token,- })))- .with_status(200)- .with_body(serde_json::to_string(&payload).unwrap())- .create_async()- .await;-- let text = consume_paste(&server.url(), access_token, &paste_key)- .await- .unwrap();-- assert_eq!(text, "guarded paste");- guard.assert_async().await;- consume.assert_async().await;- }-- #[tokio::test]- async fn password_paste_refreshes_guard_after_password_resolution() {- let access_token = "ABC123";- let paste_key = PasteKey::parse("p-AbCd1234EfGh").unwrap();- let payload = test_payload("guarded paste", &paste_key, Some("correct horse"));- let mut server = Server::new_async().await;-- let availability_guard = server- .mock("POST", "/paste/guard")- .match_body(Matcher::PartialJson(serde_json::json!({- "accessToken": access_token,- })))- .with_status(200)- .with_header(- "set-cookie",- "paste_guard=availability-cookie; Path=/; HttpOnly",- )- .with_body("{}")- .expect(1)- .create_async()- .await;-- let consume_guard = server- .mock("POST", "/paste/guard")- .match_body(Matcher::PartialJson(serde_json::json!({- "accessToken": access_token,- })))- .with_status(200)- .with_header("set-cookie", "paste_guard=consume-cookie; Path=/; HttpOnly")- .with_body("{}")- .expect(1)- .create_async()- .await;-- let consume = server- .mock("POST", "/paste/consume")- .match_header("x-paste-consume", "1")- .match_header("cookie", "paste_guard=consume-cookie")- .match_body(Matcher::PartialJson(serde_json::json!({- "accessToken": access_token,- })))- .with_status(200)- .with_body(serde_json::to_string(&payload).unwrap())- .create_async()- .await;-- let text =- consume_paste_with_password_resolver(&server.url(), access_token, &paste_key, || {- Ok(PastePasswordAttempt::Env("correct horse".to_string()))- })- .await- .unwrap();-- assert_eq!(text, "guarded paste");- availability_guard.assert_async().await;- consume_guard.assert_async().await;- consume.assert_async().await;- }-- fn test_payload(text: &str, key_reference: &PasteKey, password: Option<&str>) -> PastePayload {- let paste_key = Key::from_bytes([7u8; Key::BYTES]);- let encrypted = blob::encrypt_json(- &PasteText {- text: text.to_string(),- },- &paste_key,- )- .unwrap();- let salt = crypto::Salt::from_bytes([9u8; crypto::Salt::BYTES]);- let kdf_secret = key_reference.kdf_secret(password).unwrap();- let key_encryption_key = argon::derive_key(&kdf_secret, &salt, argon::Params::MIN).unwrap();- let encrypted_paste_key = secretbox::encrypt(paste_key.as_bytes(), &key_encryption_key);-- PastePayload {- encrypted_data: crypto::encode_b64(&encrypted.encrypted_data),- decryption_header: crypto::encode_b64(encrypted.decryption_header.as_bytes()),- encrypted_paste_key: crypto::encode_b64(&encrypted_paste_key.encrypted_data),- encrypted_paste_key_nonce: crypto::encode_b64(encrypted_paste_key.nonce.as_bytes()),- kdf_nonce: crypto::encode_b64(salt.as_bytes()),- kdf_mem_limit: argon::Params::MIN.mem_limit,- kdf_ops_limit: argon::Params::MIN.ops_limit,- }+ assert!(matches!(error, Error::AuthenticationFailed(_)));}}diff --git a/rust/apps/cli/src/main.rs b/rust/apps/cli/src/main.rsindex 305ac7c881..70198a484c 100644--- a/rust/apps/cli/src/main.rs+++ b/rust/apps/cli/src/main.rs@@ -9,7 +9,7 @@ use ente_rs::{#[tokio::main]async fn main() {if let Err(e) = run().await {- eprintln!("{e}");+ eprintln!("{}", ente_core::error::chain(&e));std::process::exit(1);}}diff --git a/rust/apps/cli/src/models/error.rs b/rust/apps/cli/src/models/error.rsindex b456c060e4..33a5860960 100644--- a/rust/apps/cli/src/models/error.rs+++ b/rust/apps/cli/src/models/error.rs@@ -7,9 +7,6 @@ pub enum Error {#[error("IO error: {0}")]Io(#[from] std::io::Error),- #[error("Network error: {0}")]- Network(#[from] reqwest::Error),-#[error("Serialization error: {0}")]Serialization(#[from] serde_json::Error),@@ -40,37 +37,24 @@ pub enum Error {#[error("ZIP error: {0}")]Zip(#[from] zip::result::ZipError),- #[error("API error ({status}): {message}")]- ApiError {- status: u16,- code: Option<String>,- message: String,- },+ #[error(transparent)]+ Http(#[from] ente_core::http::Error),#[error("{0}")]Generic(String),}-impl From<ente_core::http::Error> for Error {- fn from(error: ente_core::http::Error) -> Self {- let message = ente_core::error::chain(&error);- match error {- ente_core::http::Error::Http { status, .. } => Error::ApiError {- status,- code: None,- message,- },- ente_core::http::Error::Api { status, code, .. } => Error::ApiError {- status,- code: Some(code),- message,- },- ente_core::http::Error::Network(_) => {- Error::Generic(format!("Network error: {message}"))- }- ente_core::http::Error::Parse(_) => {- Error::Generic(format!("JSON parse error: {message}"))+impl From<ente_paste::Error> for Error {+ fn from(err: ente_paste::Error) -> Self {+ use ente_paste::Error as E;+ match err {+ E::Http(source) => Error::Http(source),+ E::Crypto(source) => Error::from(source),+ E::IncorrectPassword => {+ Error::AuthenticationFailed("Incorrect paste password".to_string())}+ E::InvalidInput(message) => Error::InvalidInput(message),+ other => Error::Generic(other.to_string()),}}}diff --git a/rust/apps/cli/tests/paste.rs b/rust/apps/cli/tests/paste.rsindex ba4576e431..274823a0d2 100644--- a/rust/apps/cli/tests/paste.rs+++ b/rust/apps/cli/tests/paste.rs@@ -1,7 +1,7 @@mod support;-use reqwest::Url;use support::{Cli, Museum, TestResult};+use url::Url;use uuid::Uuid;const PASTE_PASSWORD_ENV: &str = "ENTE_PASTE_PASSWORD";@@ -46,7 +46,7 @@ fn full_link_roundtrip(museum: &Museum) -> TestResult {String::from_utf8_lossy(&second_consume.stdout),);assert!(- String::from_utf8_lossy(&second_consume.stderr).contains("API error (410)"),+ String::from_utf8_lossy(&second_consume.stderr).contains("HTTP 410"),"second consume should fail with 410, got stderr: {}",String::from_utf8_lossy(&second_consume.stderr),);@@ -171,7 +171,7 @@ fn wrong_password_consumes_password_protected_paste(museum: &Museum) -> TestResuString::from_utf8_lossy(&second.stdout),);assert!(- String::from_utf8_lossy(&second.stderr).contains("API error (410)"),+ String::from_utf8_lossy(&second.stderr).contains("HTTP 410"),"second consume should fail with 410, got stderr: {}",String::from_utf8_lossy(&second.stderr),);@@ -214,7 +214,7 @@ fn consumed_password_paste_checks_availability_before_password(museum: &Museum)"second consume unexpectedly succeeded");assert!(- String::from_utf8_lossy(&second.stderr).contains("API error (410)"),+ String::from_utf8_lossy(&second.stderr).contains("HTTP 410"),"consumed paste should fail before password validation, got stderr: {}",String::from_utf8_lossy(&second.stderr),);diff --git a/rust/crates/core/src/http.rs b/rust/crates/core/src/http.rsindex 92a6f3891d..110a4cc1a4 100644--- a/rust/crates/core/src/http.rs+++ b/rust/crates/core/src/http.rs@@ -418,6 +418,11 @@ impl Response {self.0.headers().get(name).and_then(|v| v.to_str().ok())}+ /// All the response headers.+ pub fn headers(&self) -> &reqwest::header::HeaderMap {+ self.0.headers()+ }+/// Return an [`Error::Http`] if the status is not 2xx, otherwise the response.pub fn error_for_status(self) -> Result<Self, Error> {if self.0.status().is_success() {diff --git a/rust/crates/paste/Cargo.toml b/rust/crates/paste/Cargo.tomlnew file mode 100644index 0000000000..f53a3898a8--- /dev/null+++ b/rust/crates/paste/Cargo.toml@@ -0,0 +1,14 @@+[package]+name = "ente-paste"+edition = "2024"++[dependencies]+ente-core.workspace = true+serde.workspace = true+thiserror.workspace = true+url = "2.5.8"++[dev-dependencies]+mockito = "1.6"+serde_json = "1"+tokio = { version = "1", features = ["macros", "rt-multi-thread"] }diff --git a/rust/crates/paste/src/lib.rs b/rust/crates/paste/src/lib.rsnew file mode 100644index 0000000000..934d668084--- /dev/null+++ b/rust/crates/paste/src/lib.rs@@ -0,0 +1,568 @@+//! Encrypted pastes: create, consume, and decrypt them.++use ente_core::crypto::{self, Key, argon, blob, secretbox};+use ente_core::http::{self, Api, ApiConfig, Http};+use serde::{Deserialize, Serialize};+use thiserror::Error as ThisError;++pub const MAX_PASTE_CHARS: usize = 4000;++const FRAGMENT_SECRET_LENGTH: usize = 12;+const FRAGMENT_SECRET_ALPHABET: &[u8] =+ b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";+const PASTE_GUARD_COOKIE: &str = "paste_guard";+const PASSWORD_FRAGMENT_PREFIX: &str = "p-";+const PASSWORD_KDF_CONTEXT: &str = "ente-paste-password-v1";++#[derive(Debug, ThisError)]+pub enum Error {+ #[error(transparent)]+ Http(#[from] http::Error),++ #[error(transparent)]+ Crypto(#[from] crypto::Error),++ #[error("incorrect paste password")]+ IncorrectPassword,++ #[error("invalid input: {0}")]+ InvalidInput(String),++ #[error("the paste data is malformed or corrupted")]+ MalformedPayload,++ #[error("paste guard cookie was not returned")]+ MissingGuardCookie,+}++pub type Result<T> = std::result::Result<T, Error>;++#[derive(Debug, Eq, PartialEq)]+pub struct PasteKey {+ fragment_secret: String,+ pub password_required: bool,+}++impl PasteKey {+ pub fn parse(raw: &str) -> Result<Self> {+ let (password_required, fragment_secret) = match raw.strip_prefix(PASSWORD_FRAGMENT_PREFIX)+ {+ Some(fragment_secret) => (true, fragment_secret),+ None => (false, raw),+ };+ validate_fragment_secret(fragment_secret)?;+ Ok(Self {+ fragment_secret: fragment_secret.to_string(),+ password_required,+ })+ }++ pub fn link_fragment(&self) -> String {+ if self.password_required {+ format!("{PASSWORD_FRAGMENT_PREFIX}{}", self.fragment_secret)+ } else {+ self.fragment_secret.clone()+ }+ }++ fn kdf_secret(&self, password: Option<&str>) -> Result<String> {+ if self.password_required {+ let password = password+ .filter(|password| !password.is_empty())+ .ok_or_else(|| Error::InvalidInput("Paste password is required".to_string()))?;+ Ok(format!(+ "{PASSWORD_KDF_CONTEXT}\n{}\n{password}",+ self.fragment_secret+ ))+ } else {+ Ok(self.fragment_secret.clone())+ }+ }+}++fn validate_fragment_secret(fragment_secret: &str) -> Result<()> {+ if fragment_secret.len() == FRAGMENT_SECRET_LENGTH+ && fragment_secret+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric())+ {+ return Ok(());+ }++ Err(Error::InvalidInput("Invalid paste key".to_string()))+}++pub fn parse_reference(input: &str, key: Option<&str>) -> Result<(String, PasteKey)> {+ let input = input.trim();+ if input.is_empty() {+ return Err(Error::InvalidInput(+ "Paste URL or access token is empty".to_string(),+ ));+ }++ let (access_token, embedded_secret) = match url::Url::parse(input) {+ Ok(url) => {+ let token = url+ .path_segments()+ .and_then(|mut segments| segments.rfind(|segment| !segment.is_empty()))+ .ok_or_else(|| {+ Error::InvalidInput("Paste URL is missing an access token".into())+ })?;+ (token.to_string(), url.fragment().map(str::to_string))+ }+ Err(_) => match input.split_once('#') {+ Some((token, secret)) => (token.trim().to_string(), Some(secret.trim().to_string())),+ None => (input.to_string(), None),+ },+ };++ if access_token.trim().is_empty() {+ return Err(Error::InvalidInput(+ "Paste access token is empty".to_string(),+ ));+ }++ let paste_key = match (embedded_secret, key) {+ (Some(embedded), Some(key)) if embedded != key => {+ return Err(Error::InvalidInput(+ "Paste URL fragment and --key do not match".to_string(),+ ));+ }+ (Some(embedded), _) => PasteKey::parse(&embedded)?,+ (None, Some(key)) => PasteKey::parse(key)?,+ (None, None) => {+ return Err(Error::InvalidInput(+ "Paste key missing. Pass a full paste URL or --key".to_string(),+ ));+ }+ };++ Ok((access_token, paste_key))+}++pub fn paste_link(paste_origin: &str, access_token: &str, key: &PasteKey) -> String {+ format!(+ "{}/{}#{}",+ paste_origin.trim_end_matches('/'),+ access_token,+ key.link_fragment()+ )+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PastePayload {+ encrypted_data: String,+ decryption_header: String,+ encrypted_paste_key: String,+ encrypted_paste_key_nonce: String,+ kdf_nonce: String,+ kdf_mem_limit: u32,+ kdf_ops_limit: u32,+}++#[derive(Serialize, Deserialize)]+struct PasteText {+ text: String,+}++#[derive(Deserialize)]+struct CreatePasteResponse {+ #[serde(rename = "accessToken")]+ access_token: String,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct PasteTokenRequest {+ access_token: String,+}++pub struct Client {+ api: Api,+}++impl Client {+ pub fn new(origin: String, user_agent: Option<String>) -> Result<Self> {+ Ok(Self {+ api: Api::new(+ Http::new()?,+ ApiConfig {+ origin,+ client_package: None,+ client_version: None,+ user_agent,+ auth: None,+ },+ ),+ })+ }++ pub async fn create(&self, text: &str, password: Option<&str>) -> Result<(String, PasteKey)> {+ let (paste_key, payload) = encrypt(text, password)?;+ let response: CreatePasteResponse = self+ .api+ .post("/paste/create")+ .json(&payload)+ .send()+ .await?+ .error_for_code()+ .await?+ .json()+ .await?;+ Ok((response.access_token, paste_key))+ }++ /// Check that the paste is still available, without consuming it.+ pub async fn check(&self, access_token: &str) -> Result<()> {+ self.guard(access_token).await?;+ Ok(())+ }++ /// Consume the paste, returning its encrypted payload.+ pub async fn consume(&self, access_token: &str) -> Result<PastePayload> {+ let cookie = self.guard(access_token).await?;+ Ok(self+ .api+ .post("/paste/consume")+ .json(&PasteTokenRequest {+ access_token: access_token.to_string(),+ })+ .header("X-Paste-Consume", "1")+ .header("Cookie", &cookie)+ .send()+ .await?+ .error_for_code()+ .await?+ .json()+ .await?)+ }++ async fn guard(&self, access_token: &str) -> Result<String> {+ let response = self+ .api+ .post("/paste/guard")+ .json(&PasteTokenRequest {+ access_token: access_token.to_string(),+ })+ .send()+ .await?+ .error_for_code()+ .await?;++ let cookie_prefix = format!("{PASTE_GUARD_COOKIE}=");+ response+ .headers()+ .get_all("Set-Cookie")+ .iter()+ .filter_map(|value| value.to_str().ok())+ .filter_map(|value| value.split(';').next())+ .find(|value| value.starts_with(&cookie_prefix))+ .map(str::to_string)+ .ok_or(Error::MissingGuardCookie)+ }+}++pub fn decrypt(payload: &PastePayload, key: &PasteKey, password: Option<&str>) -> Result<String> {+ let key_encryption_key = derive_key_encryption_key(key, password, payload)?;+ let (encrypted_paste_key, nonce) = decode_wrapped_paste_key(payload)?;+ let paste_key = match secretbox::decrypt(&encrypted_paste_key, &nonce, &key_encryption_key) {+ Ok(paste_key) => paste_key,+ Err(_) if key.password_required => return Err(Error::IncorrectPassword),+ Err(error) => return Err(error.into()),+ };+ decrypt_text(&paste_key, payload)+}++pub fn encrypt(text: &str, password: Option<&str>) -> Result<(PasteKey, PastePayload)> {+ let paste_key = Key::generate();+ let key_reference = PasteKey {+ fragment_secret: fragment_secret(),+ password_required: password.is_some(),+ };+ let encrypted = blob::encrypt_json(+ &PasteText {+ text: text.to_string(),+ },+ &paste_key,+ )?;+ let kdf_secret = key_reference.kdf_secret(password)?;+ let key_encryption_key = if password.is_some() {+ argon::derive_moderate_key(&kdf_secret)?+ } else {+ argon::derive_interactive_key(&kdf_secret)?+ };+ let encrypted_paste_key = secretbox::encrypt(paste_key.as_bytes(), &key_encryption_key.key);++ Ok((+ key_reference,+ PastePayload {+ encrypted_data: crypto::encode_b64(&encrypted.encrypted_data),+ decryption_header: crypto::encode_b64(encrypted.decryption_header.as_bytes()),+ encrypted_paste_key: crypto::encode_b64(&encrypted_paste_key.encrypted_data),+ encrypted_paste_key_nonce: crypto::encode_b64(encrypted_paste_key.nonce.as_bytes()),+ kdf_nonce: crypto::encode_b64(key_encryption_key.salt.as_bytes()),+ kdf_mem_limit: key_encryption_key.params.mem_limit,+ kdf_ops_limit: key_encryption_key.params.ops_limit,+ },+ ))+}++fn derive_key_encryption_key(+ key: &PasteKey,+ password: Option<&str>,+ payload: &PastePayload,+) -> Result<Key> {+ let salt = crypto::Salt::try_from_slice(&crypto::decode_b64(&payload.kdf_nonce)?)?;+ let kdf_secret = key.kdf_secret(password)?;+ Ok(argon::derive_key(+ &kdf_secret,+ &salt,+ argon::Params {+ mem_limit: payload.kdf_mem_limit,+ ops_limit: payload.kdf_ops_limit,+ },+ )?)+}++fn decode_wrapped_paste_key(payload: &PastePayload) -> Result<(Vec<u8>, crypto::Nonce)> {+ let encrypted_paste_key = crypto::decode_b64(&payload.encrypted_paste_key)?;+ let encrypted_paste_key_nonce = crypto::decode_b64(&payload.encrypted_paste_key_nonce)?;+ if encrypted_paste_key.len() < secretbox::MAC_BYTES {+ return Err(Error::MalformedPayload);+ }+ let nonce = crypto::Nonce::try_from_slice(&encrypted_paste_key_nonce)+ .map_err(|_| Error::MalformedPayload)?;+ Ok((encrypted_paste_key, nonce))+}++fn decrypt_text(paste_key: &[u8], payload: &PastePayload) -> Result<String> {+ let encrypted_data = crypto::decode_b64(&payload.encrypted_data)?;+ let decryption_header = crypto::decode_b64(&payload.decryption_header)?;+ let text: PasteText = blob::decrypt_json(+ &blob::EncryptedBlob {+ encrypted_data,+ decryption_header: crypto::Header::try_from_slice(&decryption_header)?,+ },+ &Key::try_from_slice(paste_key)?,+ )?;+ Ok(text.text)+}++fn fragment_secret() -> String {+ let mut secret = String::with_capacity(FRAGMENT_SECRET_LENGTH);+ let threshold = 256 - (256 % FRAGMENT_SECRET_ALPHABET.len());++ while secret.len() < FRAGMENT_SECRET_LENGTH {+ for byte in crypto::random_bytes(FRAGMENT_SECRET_LENGTH) {+ let byte = usize::from(byte);+ if byte >= threshold {+ continue;+ }+ let index = byte % FRAGMENT_SECRET_ALPHABET.len();+ secret.push(char::from(FRAGMENT_SECRET_ALPHABET[index]));+ if secret.len() == FRAGMENT_SECRET_LENGTH {+ break;+ }+ }+ }++ secret+}++#[cfg(test)]+mod tests {+ use super::*;+ use mockito::{Matcher, Server};++ #[test]+ fn encrypt_then_decrypt_paste_payload() {+ let (paste_key, payload) = encrypt("hello paste", None).unwrap();+ let text = decrypt(&payload, &paste_key, None).unwrap();++ assert_eq!(text, "hello paste");+ assert_eq!(payload.kdf_mem_limit, argon::Params::INTERACTIVE.mem_limit);+ assert_eq!(payload.kdf_ops_limit, argon::Params::INTERACTIVE.ops_limit);+ }++ #[test]+ fn encrypt_then_decrypt_password_protected_paste_payload() {+ let (paste_key, payload) = encrypt("protected paste", Some("correct horse")).unwrap();+ let text = decrypt(&payload, &paste_key, Some("correct horse")).unwrap();++ assert_eq!(text, "protected paste");+ assert!(paste_key.password_required);+ assert!(+ paste_key+ .link_fragment()+ .starts_with(PASSWORD_FRAGMENT_PREFIX)+ );+ assert_eq!(payload.kdf_mem_limit, argon::Params::MODERATE.mem_limit);+ assert_eq!(payload.kdf_ops_limit, argon::Params::MODERATE.ops_limit);+ }++ #[test]+ fn reject_wrong_paste_password() {+ let (paste_key, payload) = encrypt("protected paste", Some("correct horse")).unwrap();+ let error = decrypt(&payload, &paste_key, Some("wrong horse")).unwrap_err();++ assert!(matches!(error, Error::IncorrectPassword));+ }++ #[test]+ fn structural_payload_errors_are_not_incorrect_password() {+ let (paste_key, mut payload) = encrypt("protected paste", Some("correct horse")).unwrap();+ payload.kdf_nonce = "not base64".to_string();+ let error = decrypt(&payload, &paste_key, Some("correct horse")).unwrap_err();++ assert!(matches!(+ error,+ Error::Crypto(crypto::Error::Base64Decode(_))+ ));+ }++ #[test]+ fn wrapped_key_payload_errors_are_not_incorrect_password() {+ let (paste_key, mut payload) = encrypt("protected paste", Some("correct horse")).unwrap();+ payload.encrypted_paste_key = "not base64".to_string();+ let error = decrypt(&payload, &paste_key, Some("correct horse")).unwrap_err();++ assert!(matches!(+ error,+ Error::Crypto(crypto::Error::Base64Decode(_))+ ));+ }++ #[test]+ fn parse_full_paste_link() {+ let (token, paste_key) =+ parse_reference("https://paste.ente.com/ABC123#AbCd1234EfGh", None).unwrap();++ assert_eq!(token, "ABC123");+ assert_eq!(+ paste_key,+ PasteKey {+ fragment_secret: "AbCd1234EfGh".to_string(),+ password_required: false,+ }+ );+ }++ #[test]+ fn parse_password_protected_paste_link() {+ let (token, paste_key) =+ parse_reference("https://paste.ente.com/ABC123#p-AbCd1234EfGh", None).unwrap();++ assert_eq!(token, "ABC123");+ assert_eq!(+ paste_key,+ PasteKey {+ fragment_secret: "AbCd1234EfGh".to_string(),+ password_required: true,+ }+ );+ }++ #[test]+ fn parse_token_with_key() {+ let (token, paste_key) = parse_reference("ABC123", Some("AbCd1234EfGh")).unwrap();++ assert_eq!(token, "ABC123");+ assert_eq!(+ paste_key,+ PasteKey {+ fragment_secret: "AbCd1234EfGh".to_string(),+ password_required: false,+ }+ );+ }++ #[test]+ fn parse_token_with_password_key() {+ let (token, paste_key) = parse_reference("ABC123", Some("p-AbCd1234EfGh")).unwrap();++ assert_eq!(token, "ABC123");+ assert_eq!(+ paste_key,+ PasteKey {+ fragment_secret: "AbCd1234EfGh".to_string(),+ password_required: true,+ }+ );+ }++ #[test]+ fn reject_mismatched_fragment_and_key() {+ let error = parse_reference(+ "https://paste.ente.com/ABC123#AbCd1234EfGh",+ Some("123456789012"),+ )+ .unwrap_err();++ assert!(matches!(error, Error::InvalidInput(_)));+ }++ #[tokio::test]+ async fn consume_uses_guard_cookie() {+ let access_token = "ABC123";+ let paste_key = PasteKey::parse("AbCd1234EfGh").unwrap();+ let payload = test_payload("guarded paste", &paste_key, None);+ let mut server = Server::new_async().await;++ let guard = server+ .mock("POST", "/paste/guard")+ .match_body(Matcher::PartialJson(serde_json::json!({+ "accessToken": access_token,+ })))+ .with_status(200)+ .with_header("set-cookie", "paste_guard=test-cookie; Path=/; HttpOnly")+ .with_body("{}")+ .create_async()+ .await;++ let consume = server+ .mock("POST", "/paste/consume")+ .match_header("x-paste-consume", "1")+ .match_header("cookie", "paste_guard=test-cookie")+ .match_body(Matcher::PartialJson(serde_json::json!({+ "accessToken": access_token,+ })))+ .with_status(200)+ .with_body(serde_json::to_string(&payload).unwrap())+ .create_async()+ .await;++ let client = Client::new(server.url(), None).unwrap();+ let payload = client.consume(access_token).await.unwrap();+ let text = decrypt(&payload, &paste_key, None).unwrap();++ assert_eq!(text, "guarded paste");+ guard.assert_async().await;+ consume.assert_async().await;+ }++ fn test_payload(text: &str, key_reference: &PasteKey, password: Option<&str>) -> PastePayload {+ let paste_key = Key::from_bytes([7u8; Key::BYTES]);+ let encrypted = blob::encrypt_json(+ &PasteText {+ text: text.to_string(),+ },+ &paste_key,+ )+ .unwrap();+ let salt = crypto::Salt::from_bytes([9u8; crypto::Salt::BYTES]);+ let kdf_secret = key_reference.kdf_secret(password).unwrap();+ let key_encryption_key = argon::derive_key(&kdf_secret, &salt, argon::Params::MIN).unwrap();+ let encrypted_paste_key = secretbox::encrypt(paste_key.as_bytes(), &key_encryption_key);++ PastePayload {+ encrypted_data: crypto::encode_b64(&encrypted.encrypted_data),+ decryption_header: crypto::encode_b64(encrypted.decryption_header.as_bytes()),+ encrypted_paste_key: crypto::encode_b64(&encrypted_paste_key.encrypted_data),+ encrypted_paste_key_nonce: crypto::encode_b64(encrypted_paste_key.nonce.as_bytes()),+ kdf_nonce: crypto::encode_b64(salt.as_bytes()),+ kdf_mem_limit: argon::Params::MIN.mem_limit,+ kdf_ops_limit: argon::Params::MIN.ops_limit,+ }+ }+}