π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Remove Auth backup retention
Manav Rathi3ef553d5bbab
diff --git a/rust/apps/cli-next/src/args.rs b/rust/apps/cli-next/src/args.rsindex 64e52131b3..ccad86918b 100644--- a/rust/apps/cli-next/src/args.rs+++ b/rust/apps/cli-next/src/args.rs@@ -134,13 +134,6 @@ pub struct AuthExportArgs {pub output: Option<PathBuf>,#[arg(long, help = "Export readable URI lines without encryption")]pub plaintext: bool,- #[arg(- long,- value_name = "N",- requires = "directory",- help = "Keep the N newest backups in this format"- )]- pub keep: Option<NonZeroUsize>,}#[derive(Subcommand)]diff --git a/rust/apps/cli-next/src/auth/mod.rs b/rust/apps/cli-next/src/auth/mod.rsindex b86c756012..885ea71a76 100644--- a/rust/apps/cli-next/src/auth/mod.rs+++ b/rust/apps/cli-next/src/auth/mod.rs@@ -33,8 +33,7 @@ pub async fn run(command: AuthCommand, selected: Option<&str>, options: &Optionsfs::read(&input).with_context(|| format!("cannot read {}", input.display()))?;let password = export_password(false)?;let plaintext = backup::decrypt(&encrypted, &password)?;- let published = destination.publish(&plaintext)?;- if let Some(path) = published.path {+ if let Some(path) = destination.publish(&plaintext)? {crate::output::action(options.json,&json!({"output": path.to_string_lossy()}),@@ -51,7 +50,6 @@ async fn export(args: AuthExportArgs, selected: Option<&str>, options: &Options)Destination::Directory {path,extension: if args.plaintext { "txt" } else { "json" },- keep: args.keep,}} else {Destination::file(@@ -79,7 +77,7 @@ async fn export(args: AuthExportArgs, selected: Option<&str>, options: &Options)if !matches!(destination, Destination::Stdout) {crate::output::action(options.json,- &json!({"output": null, "records": 0, "pruned": 0, "failed": payload.failed}),+ &json!({"output": null, "records": 0, "failed": payload.failed}),&format!("{} unreadable Auth record{plural}; no new backup was written.",payload.failed@@ -96,30 +94,18 @@ async fn export(args: AuthExportArgs, selected: Option<&str>, options: &Options)Some(password) => Zeroizing::new(backup::encrypt(&payload.bytes, &password)?),None => payload.bytes,};- let published = destination.publish(&artifact)?;- if let Some(path) = published.path {- let mut summary = format!(- "Exported {} code{} to {}.",- payload.records,- if payload.records == 1 { "" } else { "s" },- path.display(),- );- if published.pruned > 0 {- summary.push_str(&format!(- " Pruned {} backup{}.",- published.pruned,- if published.pruned == 1 { "" } else { "s" },- ));- }+ if let Some(path) = destination.publish(&artifact)? {crate::output::action(options.json,- &json!({"output": path.to_string_lossy(), "records": payload.records, "pruned": published.pruned, "failed": 0}),- &summary,+ &json!({"output": path.to_string_lossy(), "records": payload.records, "failed": 0}),+ &format!(+ "Exported {} code{} to {}.",+ payload.records,+ if payload.records == 1 { "" } else { "s" },+ path.display(),+ ),)?;}- if let Some(error) = published.prune_error {- return Err(error);- }Ok(())}diff --git a/rust/apps/cli-next/src/auth/output.rs b/rust/apps/cli-next/src/auth/output.rsindex 0197bb232d..bf6df2469a 100644--- a/rust/apps/cli-next/src/auth/output.rs+++ b/rust/apps/cli-next/src/auth/output.rs@@ -1,7 +1,6 @@use std::{fs,io::{self, Write},- num::NonZeroUsize,path::{Path, PathBuf},};@@ -14,16 +13,9 @@ pub enum Destination {Directory {path: PathBuf,extension: &'static str,- keep: Option<NonZeroUsize>,},}-pub struct Published {- pub path: Option<PathBuf>,- pub pruned: usize,- pub prune_error: Option<anyhow::Error>,-}-impl Destination {pub fn file(path: PathBuf) -> Self {if path == Path::new("-") {@@ -81,17 +73,13 @@ impl Destination {}}- pub fn publish(&self, bytes: &[u8]) -> Result<Published> {+ pub fn publish(&self, bytes: &[u8]) -> Result<Option<PathBuf>> {match self {Self::Stdout => {let mut stdout = io::stdout().lock();stdout.write_all(bytes)?;stdout.flush()?;- Ok(Published {- path: None,- pruned: 0,- prune_error: None,- })+ Ok(None)}Self::File(path) => {stage(parent(path), bytes)?@@ -104,17 +92,11 @@ impl Destination {path.display())})?;- Ok(Published {- path: Some(path.clone()),- pruned: 0,- prune_error: None,- })+ Ok(Some(path.clone()))+ }+ Self::Directory { path, extension } => {+ publish_directory(path, extension, bytes, Local::now().date_naive()).map(Some)}- Self::Directory {- path,- extension,- keep,- } => publish_directory(path, extension, *keep, bytes, Local::now().date_naive()),}}}@@ -138,52 +120,35 @@ fn sync_directory(_directory: &Path) -> io::Result<()> {Ok(())}-fn backup_name(name: &str, extension: &str) -> Option<(NaiveDate, u64)> {- let stem = name- .strip_prefix("ente-auth-")?- .strip_suffix(&format!(".{extension}"))?;- let date_text = stem.get(..10)?;- let date = NaiveDate::parse_from_str(date_text, "%Y-%m-%d").ok()?;- if date.format("%Y-%m-%d").to_string() != date_text {- return None;- }- let suffix = stem.get(10..)?;- let sequence = if suffix.is_empty() {- 1+fn backup_sequence(name: &str, stem: &str, extension: &str) -> Option<u64> {+ let suffix = name.strip_prefix(stem)?.strip_suffix(extension)?;+ if suffix.is_empty() {+ Some(1)} else {let digits = suffix.strip_prefix('-')?;let sequence: u64 = digits.parse().ok()?;- if sequence < 2 || sequence.to_string() != digits {- return None;- }- sequence- };- Some((date, sequence))+ (sequence >= 2 && sequence.to_string() == digits).then_some(sequence)+ }}fn publish_directory(directory: &Path,extension: &str,- keep: Option<NonZeroUsize>,bytes: &[u8],today: NaiveDate,-) -> Result<Published> {- let mut candidates = Vec::new();+) -> Result<PathBuf> {+ let stem = format!("ente-auth-{today}");+ let extension = format!(".{extension}");let mut sequence = 0;for entry in fs::read_dir(directory)? {let entry = entry?;- if !entry.file_type()?.is_file() {- continue;- }let name = entry.file_name();- let Some((date, number)) = name.to_str().and_then(|name| backup_name(name, extension))- else {- continue;- };- if date == today {+ if let Some(number) = name+ .to_str()+ .and_then(|name| backup_sequence(name, &stem, &extension))+ {sequence = sequence.max(number);}- candidates.push(((date, number), entry.path()));}let mut temporary = stage(directory, bytes)?;let path = loop {@@ -195,7 +160,7 @@ fn publish_directory(} else {format!("-{sequence}")};- let path = directory.join(format!("ente-auth-{today}{suffix}.{extension}"));+ let path = directory.join(format!("{stem}{suffix}{extension}"));match temporary.persist_noclobber(&path) {Ok(_) => break path,Err(error) if error.error.kind() == io::ErrorKind::AlreadyExists => {@@ -204,40 +169,8 @@ fn publish_directory(Err(error) => return Err(error.error).context("cannot publish Auth backup"),}};- sync_directory(directory)- .context("backup published, but cannot sync its directory; older backups were kept")?;- let mut result = Published {- path: Some(path),- pruned: 0,- prune_error: None,- };- if let Some(keep) = keep {- candidates.sort_unstable_by_key(|candidate| std::cmp::Reverse(candidate.0));- prune(- candidates- .into_iter()- .skip(keep.get() - 1)- .map(|(_, path)| path),- &mut result,- );- }- Ok(result)-}--fn prune(paths: impl Iterator<Item = PathBuf>, result: &mut Published) {- for path in paths {- match fs::remove_file(&path) {- Ok(()) => result.pruned += 1,- Err(error) if error.kind() == io::ErrorKind::NotFound => {}- Err(error) => {- result.prune_error = Some(- anyhow::Error::new(error)- .context(format!("backup saved, but cannot prune {}", path.display())),- );- break;- }- }- }+ sync_directory(directory).context("backup published, but cannot sync its directory")?;+ Ok(path)}#[cfg(test)]@@ -245,67 +178,38 @@ mod tests {use super::*;#[test]- fn publication_allocates_dates_and_prunes_only_its_format() {+ fn publication_allocates_dates_and_preserves_earlier_files() {let directory = tempfile::tempdir().unwrap();let today = NaiveDate::from_ymd_opt(2026, 10, 8).unwrap();- let publish = |day, extension, keep| {- publish_directory(- directory.path(),- extension,- NonZeroUsize::new(keep),- b"complete",- day,- )- .unwrap()+ let publish = |day, extension| {+ publish_directory(directory.path(), extension, b"complete", day).unwrap()};for suffix in ["", "-2", "-3"] {- let result = publish(today, "json", 0);+ let path = publish(today, "json");assert_eq!(- result.path.unwrap().file_name().unwrap(),+ path.file_name().unwrap(),format!("ente-auth-2026-10-08{suffix}.json").as_str());- assert_eq!(result.pruned, 0);- }- for name in [- "unrelated.json",- "ente-auth-2026-10-08-01.json",- "ente-auth-2026-10-08-1.json",- "ente-auth-2026-02-30.json",- ] {- fs::write(directory.path().join(name), b"untouched").unwrap();+ assert_eq!(fs::read(path).unwrap(), b"complete");}- let text = publish(today, "txt", 1).path.unwrap();- assert_eq!(fs::read_dir(directory.path()).unwrap().count(), 8);- let next_day = today.succ_opt().unwrap();- let result = publish(next_day, "json", 2);- assert_eq!(result.pruned, 2);+ let earlier = directory.path().join("ente-auth-2026-10-08-9.json");+ fs::write(&earlier, b"earlier").unwrap();assert_eq!(- result.path.unwrap().file_name().unwrap(),- "ente-auth-2026-10-09.json"+ publish(today, "json").file_name().unwrap(),+ "ente-auth-2026-10-08-10.json");- assert!(- directory- .path()- .join("ente-auth-2026-10-08-3.json")- .exists()+ assert_eq!(+ publish(today, "txt").file_name().unwrap(),+ "ente-auth-2026-10-08.txt");- assert!(text.exists());- let result = publish(today, "txt", 1);- assert_eq!(result.pruned, 1);- assert!(!text.exists());- assert!(directory.path().join("ente-auth-2026-10-09.json").exists());- let earlier_day = NaiveDate::from_ymd_opt(2026, 1, 1).unwrap();- let result = publish(earlier_day, "json", 1);- assert_eq!(result.pruned, 2);- assert!(result.path.unwrap().exists());- for name in [- "unrelated.json",- "ente-auth-2026-10-08-01.json",- "ente-auth-2026-10-08-1.json",- "ente-auth-2026-02-30.json",- ] {- assert_eq!(fs::read(directory.path().join(name)).unwrap(), b"untouched");- }+ assert_eq!(+ publish(today.succ_opt().unwrap(), "json")+ .file_name()+ .unwrap(),+ "ente-auth-2026-10-09.json"+ );+ assert_eq!(fs::read(earlier).unwrap(), b"earlier");+ assert_eq!(fs::read_dir(directory.path()).unwrap().count(), 7);}#[test]@@ -324,36 +228,23 @@ mod tests {assert!(Destination::File(link).prepare().is_err());}fs::create_dir(directory.path().join("ente-auth-2026-10-08.json")).unwrap();- let result = publish_directory(+ let path = publish_directory(directory.path(),"json",- None,b"new",NaiveDate::from_ymd_opt(2026, 10, 8).unwrap(),).unwrap();- assert_eq!(- result.path.unwrap().file_name().unwrap(),- "ente-auth-2026-10-08-2.json"- );+ assert_eq!(path.file_name().unwrap(), "ente-auth-2026-10-08-2.json");}#[test]- fn write_and_prune_failures_preserve_complete_backups() {+ fn write_failure_preserves_earlier_backup() {let directory = tempfile::tempdir().unwrap();let old = directory.path().join("old");fs::write(&old, b"old").unwrap();let missing = Destination::File(directory.path().join("missing/new"));assert!(missing.publish(b"new").is_err());assert_eq!(fs::read(&old).unwrap(), b"old");- let new = directory.path().join("new");- let mut result = Destination::File(new.clone()).publish(b"new").unwrap();- let replaced_candidate = directory.path().join("replaced");- fs::create_dir(&replaced_candidate).unwrap();- prune([old.clone(), replaced_candidate].into_iter(), &mut result);- assert_eq!(result.pruned, 1);- assert!(result.prune_error.is_some());- assert_eq!(fs::read(new).unwrap(), b"new");- assert!(!old.exists());}}diff --git a/rust/apps/cli-next/tests/support/auth.rs b/rust/apps/cli-next/tests/support/auth.rsindex 8197df84fc..c3672e6776 100644--- a/rust/apps/cli-next/tests/support/auth.rs+++ b/rust/apps/cli-next/tests/support/auth.rs@@ -96,8 +96,6 @@ fn refresh_keeps_progress_and_refuses_unreadable_records_until_updated() {"export",output_dir.path().to_str().unwrap(),"--plaintext",- "--keep",- "1","--json",]);let stderr = failure(&failed);@@ -107,7 +105,7 @@ fn refresh_keeps_progress_and_refuses_unreadable_records_until_updated() {assert!(!stderr.contains("JBSWY3DPEHPK3PXP"));assert_eq!(serde_json::from_slice::<Value>(&failed.stdout).unwrap(),- json!({"output": null, "records": 0, "failed": 2, "pruned": 0})+ json!({"output": null, "records": 0, "failed": 2}));assert_eq!(fs::read_dir(output_dir.path()).unwrap().count(), 1);changed.assert();@@ -327,7 +325,6 @@ fn encrypted_export_and_independent_decrypt_keep_artifacts_separate_from_summari);let summary: Value = serde_json::from_slice(&result.stdout).unwrap();assert_eq!(summary["records"], 1);- assert_eq!(summary["pruned"], 0);assert_eq!(summary["failed"], 0);let encoded = fs::read(&encrypted).unwrap();let stream = success(@@ -435,8 +432,6 @@ fn password_and_destination_errors_are_resolved_before_account_access() {for args in [vec!["auth", "export"],vec!["auth", "export", "dir", "--output", "-"],- vec!["auth", "export", "--output", "-", "--keep", "1"],- vec!["auth", "export", "dir", "--keep", "0"],] {failure(&home.run(&args));}