Skip to content
Merged
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-1714-bounded-remote-file-reads.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
### Fixed
- The upload comparison preview, "Open locally" and the backup before a confirmed file write no longer load a huge or growing remote file into memory.
281 changes: 281 additions & 0 deletions crates/app-logic/src/orchestration/action_exec/tests_activity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1060,3 +1060,284 @@ async fn test_start_after_exit_began_is_refused_and_started_sessions_end_once()
.count();
assert_eq!((starts, ends), (2, 2), "{events:?}");
}

/// Runs one confirmed `WriteRemoteFile` against `sftp` and returns the
/// recorded `FileWritten` fields (`backup_path`, `sha256_before`).
async fn confirmed_write(
sftp: &MockSftpSession,
path: &str,
sudo: bool,
) -> (Option<String>, Option<String>) {
let transport = MockSshTransport::default()
.with_prefix_response("sudo -S cp -p ", output(""))
.with_prefix_response("sudo -S install -m ", output(""));
let mut session = session_allowing_all(transport);
if sudo {
session
.set_sudo_password_for_tests(Some(secrecy::SecretString::from("hunter2".to_string())));
}
let (session, rx) = observed(session);
session.set_sftp_for_tests(Box::new(sftp.clone())).await;
let emitter = TestEmitter::default();
let confirmations = ConfirmationRegistry::new();
tokio::join!(
propose(
&session,
AiAction::WriteRemoteFile {
path: path.to_string(),
content: "new".to_string(),
},
ActionOrigin::Internal,
&emitter,
&confirmations,
Uuid::new_v4(),
),
approve_first_proposed_action(&emitter, &confirmations)
);
let events = take(&rx, 2);
let ActivityEventKind::FileWritten {
backup_path,
sha256_before,
..
} = &events[1].kind
else {
panic!("{events:?}")
};
(backup_path.clone(), sha256_before.clone())
}

fn sha256_of(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
Sha256::digest(bytes)
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}

/// Issue #1714: the backup of a file larger than one chunk is a byte-exact
/// copy, `sha256_before` is the hash of the original, and the old file is
/// never read in one piece.
#[tokio::test]
async fn test_backup_of_a_multi_chunk_file_is_exact_and_read_in_bounded_pieces() {
let path = "/home/deploy/big.bin";
let original: Vec<u8> = (0..(2 * 256 * 1024 + 123))
.map(|i| (i % 251) as u8)
.collect();
let sftp = MockSftpSession::new().with_file(path, original.clone());
let (backup, before) = confirmed_write(&sftp, path, false).await;
let backup = backup.expect("backup path");
assert_eq!(sftp.file_content(&backup), Some(original.clone()));
assert_eq!(before, Some(sha256_of(&original)));
let calls = sftp.calls();
assert!(
!calls.iter().any(|c| c.starts_with("read_file ")),
"{calls:?}"
);
assert!(
calls.iter().filter(|c| c.starts_with("read_range")).count() >= 3,
"{calls:?}"
);
}

/// Issue #1714: an empty existing file still gets an (empty) backup.
#[tokio::test]
async fn test_backup_of_an_empty_file_is_an_empty_file() {
let path = "/home/deploy/empty.conf";
let sftp = MockSftpSession::new().with_file(path, Vec::new());
let (backup, before) = confirmed_write(&sftp, path, false).await;
assert_eq!(sftp.file_content(&backup.unwrap()), Some(Vec::new()));
assert_eq!(before, Some(sha256_of(b"")));
}

/// Issue #1714: a read error during the backup fails the write before the
/// target is touched.
#[tokio::test]
async fn test_backup_read_error_leaves_the_target_untouched() {
let path = "/home/deploy/app.conf";
let sftp = MockSftpSession::new()
.with_file(path, b"old".to_vec())
.with_read_failure(path);
let session = session_allowing_all(MockSshTransport::default());
let (session, _rx) = observed(session);
session.set_sftp_for_tests(Box::new(sftp.clone())).await;
let emitter = TestEmitter::default();
let confirmations = ConfirmationRegistry::new();
tokio::join!(
propose(
&session,
AiAction::WriteRemoteFile {
path: path.to_string(),
content: "new".to_string(),
},
ActionOrigin::Internal,
&emitter,
&confirmations,
Uuid::new_v4(),
),
approve_first_proposed_action(&emitter, &confirmations)
);
assert_eq!(sftp.file_content(path), Some(b"old".to_vec()));
}

/// Issue #1714: the sudo fallback hashes the old content from a chunked read.
#[tokio::test]
async fn test_sudo_fallback_hashes_the_old_file_from_a_chunked_read() {
let path = "/etc/app.conf";
let original: Vec<u8> = (0..(256 * 1024 + 7)).map(|i| (i % 241) as u8).collect();
let sftp = MockSftpSession::new()
.with_file(path, original.clone())
.with_permission_denied(path);
let (_, before) = confirmed_write(&sftp, path, true).await;
assert_eq!(before, Some(sha256_of(&original)));
let calls = sftp.calls();
assert!(
calls.contains(&format!("read_file_chunked {path}")),
"{calls:?}"
);
assert!(
!calls.iter().any(|c| c.starts_with("read_file ")),
"{calls:?}"
);
}

/// Issue #1714: a read error in the sudo fallback leaves `sha256_before`
/// `None` and the write still proceeds.
#[tokio::test]
async fn test_sudo_fallback_read_error_leaves_the_hash_none_and_still_writes() {
let path = "/etc/app.conf";
let sftp = MockSftpSession::new()
.with_file(path, b"old".to_vec())
.with_permission_denied(path)
.with_read_failure(path);
let (backup, before) = confirmed_write(&sftp, path, true).await;
assert!(backup.is_some());
assert_eq!(before, None);
}

/// Issue #1714: a file that yields more bytes than `stat` reported (grown,
/// endless special file) fails the write, leaves no backup and the target
/// untouched.
#[tokio::test]
async fn test_backup_of_a_file_larger_than_its_stat_size_fails_and_leaves_no_backup() {
let path = "/home/deploy/zero";
let sftp = MockSftpSession::new()
.with_file(path, vec![0u8; 3 * 256 * 1024])
.with_reported_size(path, 0);
let session = session_allowing_all(MockSshTransport::default());
let (session, _rx) = observed(session);
session.set_sftp_for_tests(Box::new(sftp.clone())).await;
let emitter = TestEmitter::default();
let confirmations = ConfirmationRegistry::new();
tokio::join!(
propose(
&session,
AiAction::WriteRemoteFile {
path: path.to_string(),
content: "new".to_string(),
},
ActionOrigin::Internal,
&emitter,
&confirmations,
Uuid::new_v4(),
),
approve_first_proposed_action(&emitter, &confirmations)
);
assert_eq!(sftp.file_content(path), Some(vec![0u8; 3 * 256 * 1024]));
let calls = sftp.calls();
assert!(
!calls.iter().any(|c| c.starts_with("write_file ")),
"{calls:?}"
);
assert!(
sftp.paths()
.iter()
.all(|p| !p.contains(".smartssh-backup-")),
"{:?}",
sftp.paths()
);
}

/// Issue #1714: `write_range` creates the backup before it can fail, so a
/// failure on the very first chunk must not leave a partial backup either.
#[tokio::test]
async fn test_backup_failing_on_the_first_write_removes_the_partial_backup() {
let path = "/home/deploy/first.bin";
let sftp = MockSftpSession::new()
.with_file(path, b"old".to_vec())
.with_write_range_failure_containing(".smartssh-backup-");
let session = session_allowing_all(MockSshTransport::default());
let (session, _rx) = observed(session);
session.set_sftp_for_tests(Box::new(sftp.clone())).await;
let emitter = TestEmitter::default();
let confirmations = ConfirmationRegistry::new();
tokio::join!(
propose(
&session,
AiAction::WriteRemoteFile {
path: path.to_string(),
content: "new".to_string(),
},
ActionOrigin::Internal,
&emitter,
&confirmations,
Uuid::new_v4(),
),
approve_first_proposed_action(&emitter, &confirmations)
);
assert_eq!(sftp.file_content(path), Some(b"old".to_vec()));
assert!(
sftp.paths()
.iter()
.all(|p| !p.contains(".smartssh-backup-")),
"{:?}",
sftp.paths()
);
}

/// Issue #1714: a failure on a later chunk removes the partial backup.
#[tokio::test]
async fn test_backup_failing_on_a_later_chunk_removes_the_partial_backup() {
let path = "/home/deploy/big.bin";
let sftp = MockSftpSession::new()
.with_file(path, vec![7u8; 2 * 256 * 1024 + 5])
.with_read_failure_after(path, 1);
let session = session_allowing_all(MockSshTransport::default());
let (session, _rx) = observed(session);
session.set_sftp_for_tests(Box::new(sftp.clone())).await;
let emitter = TestEmitter::default();
let confirmations = ConfirmationRegistry::new();
tokio::join!(
propose(
&session,
AiAction::WriteRemoteFile {
path: path.to_string(),
content: "new".to_string(),
},
ActionOrigin::Internal,
&emitter,
&confirmations,
Uuid::new_v4(),
),
approve_first_proposed_action(&emitter, &confirmations)
);
let calls = sftp.calls();
assert!(
calls.iter().any(|c| c.starts_with("write_range ")),
"first chunk was written: {calls:?}"
);
assert!(
calls.iter().any(|c| c.starts_with("remove ")),
"partial backup removed: {calls:?}"
);
assert_eq!(
sftp.file_content(path).map(|c| c.len()),
Some(2 * 256 * 1024 + 5)
);
assert!(
sftp.paths()
.iter()
.all(|p| !p.contains(".smartssh-backup-")),
"{:?}",
sftp.paths()
);
}
Loading
Loading