Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.d/issue-1735-backup-exclusive-create.md
Original file line number Diff line number Diff line change
@@ -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.
72 changes: 60 additions & 12 deletions crates/app-logic/src/orchestration/remote_files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 {
Expand All @@ -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()))
}

Expand Down Expand Up @@ -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()));
}
}
24 changes: 24 additions & 0 deletions crates/ssh-transport/src/local_sftp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
4 changes: 3 additions & 1 deletion docs/specs/0020-sftp-file-transfer.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
`<pfad>.smartssh-backup-<zeitstempel>` 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.
Expand Down
Loading