From 6d976e6f67610da7d3a733ebb0c76a858e83038c Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:19:05 +0000 Subject: [PATCH] fix(app-logic): create the write backup exclusively (#1735) Co-Authored-By: Claude Sonnet 5.5 --- .../issue-1735-backup-exclusive-create.md | 2 + .../src/orchestration/remote_files.rs | 72 +++++++++++++++---- crates/ssh-transport/src/local_sftp.rs | 24 +++++++ docs/specs/0020-sftp-file-transfer.md | 4 +- 4 files changed, 89 insertions(+), 13 deletions(-) create mode 100644 changelog.d/issue-1735-backup-exclusive-create.md diff --git a/changelog.d/issue-1735-backup-exclusive-create.md b/changelog.d/issue-1735-backup-exclusive-create.md new file mode 100644 index 000000000..00936df0c --- /dev/null +++ b/changelog.d/issue-1735-backup-exclusive-create.md @@ -0,0 +1,2 @@ +### Fixed +- The safety backup made before a confirmed remote file write no longer overwrites or deletes an existing file (or follows a symlink) at the backup name; the write fails instead. diff --git a/crates/app-logic/src/orchestration/remote_files.rs b/crates/app-logic/src/orchestration/remote_files.rs index e99b9ccc1..610aa78d5 100644 --- a/crates/app-logic/src/orchestration/remote_files.rs +++ b/crates/app-logic/src/orchestration/remote_files.rs @@ -350,8 +350,11 @@ fn backup_path_for(path: &str) -> String { /// returns the SHA-256 (hex) of the bytes copied. The copy is bounded by /// `size` (the `stat` size of `path`): a file that yields more bytes (grew, /// endless special file) fails the copy instead of filling the server's disk. -/// Any read or write error aborts the copy; a partial backup is removed -/// best-effort so it is never mistaken for a complete one. +/// The backup is created exclusively (`create_file_exclusive`): a file or +/// symlink already at `backup` fails the copy and is neither written through +/// nor removed. Any read or write error after that aborts the copy; the +/// partial backup, and only that one, is removed best-effort so it is never +/// mistaken for a complete one. async fn copy_to_backup( sftp: &mut dyn ssh_manager_core::ssh::SftpSession, path: &str, @@ -377,6 +380,11 @@ async fn copy_to_backup_inner( use sha2::{Digest, Sha256}; let mut hasher = Sha256::new(); let mut offset: u64 = 0; + // `created` is set only after the exclusive create succeeded, so cleanup + // never removes a file this call did not create (an existing file or + // symlink at the backup name makes the create fail instead). + sftp.create_file_exclusive(backup).await?; + *created = true; loop { let remaining = size.saturating_sub(offset); if remaining == 0 { @@ -398,18 +406,9 @@ async fn copy_to_backup_inner( break; } hasher.update(&chunk); - // Mark before writing: `write_range(.., true)` creates/truncates the - // file even when the write itself then fails. - let truncate = !*created; - *created = true; - sftp.write_range(backup, offset, &chunk, truncate).await?; + sftp.write_range(backup, offset, &chunk, false).await?; offset += chunk.len() as u64; } - if !*created { - // An empty file still gets an (empty) backup. - *created = true; - sftp.write_range(backup, 0, &[], true).await?; - } Ok(hex_of_digest(hasher.finalize().as_slice())) } @@ -824,3 +823,52 @@ mod hash_tests { assert_eq!(missing, None); } } + +#[cfg(test)] +mod backup_tests { + use super::copy_to_backup; + use ssh_manager_core::ssh::mock::MockSftpSession; + + /// Issue #1735: a file (or symlink, which the exclusive create never + /// follows) already at the backup name fails the copy and is neither + /// modified nor removed. + #[tokio::test] + async fn test_backup_onto_an_existing_name_fails_and_keeps_that_file() { + let mut sftp = MockSftpSession::new() + .with_file("/h/a.conf", b"old".to_vec()) + .with_file("/h/a.conf.smartssh-backup-1", b"foreign".to_vec()); + let err = copy_to_backup(&mut sftp, "/h/a.conf", "/h/a.conf.smartssh-backup-1", 3) + .await + .unwrap_err(); + assert_eq!(err.code(), "SSH_SFTP_ALREADY_EXISTS"); + assert_eq!( + sftp.file_content("/h/a.conf.smartssh-backup-1"), + Some(b"foreign".to_vec()) + ); + assert_eq!(sftp.file_content("/h/a.conf"), Some(b"old".to_vec())); + let calls = sftp.calls(); + assert!( + calls + .iter() + .all(|c| !c.starts_with("write_range") && !c.starts_with("remove")), + "{calls:?}" + ); + } + + /// Issue #1735: an empty source still gets an empty backup, created + /// exclusively and without a truncating write. + #[tokio::test] + async fn test_empty_backup_is_created_exclusively() { + let mut sftp = MockSftpSession::new().with_file("/h/e", Vec::new()); + copy_to_backup(&mut sftp, "/h/e", "/h/e.smartssh-backup-1", 0) + .await + .unwrap(); + assert_eq!( + sftp.file_content("/h/e.smartssh-backup-1"), + Some(Vec::new()) + ); + assert!(sftp + .calls() + .contains(&"create_file_exclusive /h/e.smartssh-backup-1".to_string())); + } +} diff --git a/crates/ssh-transport/src/local_sftp.rs b/crates/ssh-transport/src/local_sftp.rs index 5f5a95008..e299d95d8 100644 --- a/crates/ssh-transport/src/local_sftp.rs +++ b/crates/ssh-transport/src/local_sftp.rs @@ -656,6 +656,30 @@ mod tests { assert!(home.path().join("dir").is_dir()); } + /// Issue #1735: exclusive create does not follow a symlink at the name: + /// it fails and leaves the link and its target untouched. + #[cfg(unix)] + #[tokio::test] + async fn test_create_file_exclusive_does_not_follow_a_symlink() { + let home = tempfile::tempdir().unwrap(); + let mut session = LocalFileSession::with_home(Some(home.path().to_path_buf())); + session.write_file("target.txt", b"payload").await.unwrap(); + std::os::unix::fs::symlink(home.path().join("target.txt"), home.path().join("link")) + .unwrap(); + std::os::unix::fs::symlink(home.path().join("missing"), home.path().join("dangling")) + .unwrap(); + for name in ["link", "dangling"] { + let err = session.create_file_exclusive(name).await.unwrap_err(); + assert_eq!(err.code(), "SSH_SFTP_ALREADY_EXISTS", "{name}"); + assert!(home.path().join(name).is_symlink(), "{name}"); + } + assert_eq!( + std::fs::read(home.path().join("target.txt")).unwrap(), + b"payload" + ); + assert!(!home.path().join("missing").exists()); + } + /// Issue #10: write, read, stat, rename, create/remove dir and delete /// via relative paths act on files under home. #[tokio::test] diff --git a/docs/specs/0020-sftp-file-transfer.md b/docs/specs/0020-sftp-file-transfer.md index 96e3ef6c3..0398e625f 100644 --- a/docs/specs/0020-sftp-file-transfer.md +++ b/docs/specs/0020-sftp-file-transfer.md @@ -111,7 +111,9 @@ Die sicherheitskritischste Aktion dieser Spec. Ablauf: 4. **Automatisches Backup.** Vor dem Überschreiben einer bestehenden Datei legt die App auf dem Server eine Sicherungskopie `.smartssh-backup-` an. Der Backup-Pfad steht im - Chat-Ergebnis. Beim regulären Schreiben ist die Kopie durch die Dateigröße + Chat-Ergebnis. Eine Datei (oder ein Symlink), die unter diesem Namen schon + existiert, wird nie überschrieben, durchschrieben oder entfernt: Die Aktion + scheitert, bevor die Zieldatei angefasst wird. Beim regulären Schreiben ist die Kopie durch die Dateigröße vor dem Schreiben begrenzt: Liefert die Datei mehr Bytes (gewachsen, Endlos-Spezialdatei), scheitert die Aktion, die Zieldatei bleibt unverändert und eine angefangene Sicherungskopie wird entfernt.