diff --git a/changelog.d/issue-1714-bounded-remote-file-reads.md b/changelog.d/issue-1714-bounded-remote-file-reads.md new file mode 100644 index 000000000..998c108a5 --- /dev/null +++ b/changelog.d/issue-1714-bounded-remote-file-reads.md @@ -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. diff --git a/crates/app-logic/src/orchestration/action_exec/tests_activity.rs b/crates/app-logic/src/orchestration/action_exec/tests_activity.rs index 9a52533c9..863db14db 100644 --- a/crates/app-logic/src/orchestration/action_exec/tests_activity.rs +++ b/crates/app-logic/src/orchestration/action_exec/tests_activity.rs @@ -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, Option) { + 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 = (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 = (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() + ); +} diff --git a/crates/app-logic/src/orchestration/remote_files.rs b/crates/app-logic/src/orchestration/remote_files.rs index 3bf1d2d51..e99b9ccc1 100644 --- a/crates/app-logic/src/orchestration/remote_files.rs +++ b/crates/app-logic/src/orchestration/remote_files.rs @@ -37,12 +37,17 @@ pub(crate) const MAX_PREVIEW_FILE_BYTES: u64 = 1024 * 1024; /// record keeps instead of the content itself (Spec 0057). fn sha256_hex(bytes: &[u8]) -> String { use sha2::{Digest, Sha256}; - Sha256::digest(bytes) - .iter() - .map(|b| format!("{b:02x}")) - .collect() + hex_of_digest(Sha256::digest(bytes).as_slice()) } +fn hex_of_digest(digest: &[u8]) -> String { + digest.iter().map(|b| format!("{b:02x}")).collect() +} + +/// Chunk size for reading an existing remote file (backup copy, "before" +/// hash): memory use is bounded by this, never by the file size. +const OLD_CONTENT_CHUNK_BYTES: usize = 256 * 1024; + /// What a successful write leaves for the activity record. `sha256_before` /// is `None` when the old content was not read (new file, or only readable /// with elevated rights). @@ -341,6 +346,98 @@ fn backup_path_for(path: &str) -> String { ) } +/// Copies `path` to `backup` in chunks of [`OLD_CONTENT_CHUNK_BYTES`] and +/// 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. +async fn copy_to_backup( + sftp: &mut dyn ssh_manager_core::ssh::SftpSession, + path: &str, + backup: &str, + size: u64, +) -> Result { + let mut created = false; + let result = copy_to_backup_inner(sftp, path, backup, size, &mut created).await; + if result.is_err() && created { + // Best effort: the original error is what the caller needs. + let _ = sftp.remove(backup).await; + } + result +} + +async fn copy_to_backup_inner( + sftp: &mut dyn ssh_manager_core::ssh::SftpSession, + path: &str, + backup: &str, + size: u64, + created: &mut bool, +) -> Result { + use sha2::{Digest, Sha256}; + let mut hasher = Sha256::new(); + let mut offset: u64 = 0; + loop { + let remaining = size.saturating_sub(offset); + if remaining == 0 { + // One probe byte: anything more means the file is not the size + // `stat` reported. + if !sftp.read_range(path, offset, 1).await?.is_empty() { + return Err(SshError::ChannelError(format!( + "'{path}' is larger than its reported size; backup aborted" + ))); + } + break; + } + let want = usize::try_from(remaining) + .unwrap_or(usize::MAX) + .min(OLD_CONTENT_CHUNK_BYTES); + let chunk = sftp.read_range(path, offset, want).await?; + if chunk.is_empty() { + // The file shrank since `stat`: back up what is there. + 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?; + 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())) +} + +/// SHA-256 (hex) of `path`, read in chunks and bounded by `size` (the `stat` +/// size): `None` when the read fails or yields more than `size` bytes (grown +/// or endless file), so the hash never claims to cover content it did not. +async fn hash_old_content( + sftp: &mut dyn ssh_manager_core::ssh::SftpSession, + path: &str, + size: u64, +) -> Option { + use sha2::{Digest, Sha256}; + use ssh_manager_core::ssh::{ChunkControl, TransferEnd}; + let mut hasher = Sha256::new(); + let mut total: u64 = 0; + let end = sftp + .read_file_chunked(path, OLD_CONTENT_CHUNK_BYTES, &mut |chunk| { + total += chunk.len() as u64; + if total > size { + return ChunkControl::Stop; + } + hasher.update(chunk); + ChunkControl::Continue + }) + .await; + matches!(end, Ok(TransferEnd::Completed)).then(|| hex_of_digest(hasher.finalize().as_slice())) +} + /// Regulärer (nicht-privilegierter) Schreibversuch per SFTP: Backup (falls /// die Datei existiert) + eigentliches Schreiben, in dieser Reihenfolge /// (Spec 0020, Abschnitt 4.2, Punkt 4: "vor jedem Überschreiben"). Gibt den @@ -352,6 +449,7 @@ async fn write_via_sftp_with_backup( path: &str, content: &str, existed: bool, + old_size: Option, ) -> Result { let backup_path = if existed { Some(backup_path_for(path)) @@ -363,9 +461,7 @@ async fn write_via_sftp_with_backup( if let Some(backup) = &backup_path { let mut guard = session.lock_sftp().await; let sftp = guard.sftp_or_err()?; - let old_content = sftp.read_file(path).await?; - sha256_before = Some(sha256_hex(&old_content)); - sftp.write_file(backup, &old_content).await?; + sha256_before = Some(copy_to_backup(sftp, path, backup, old_size.unwrap_or(0)).await?); } let mut guard = session.lock_sftp().await; @@ -415,6 +511,7 @@ async fn execute_privileged( /// SFTP-Lesevesuch würde mit derselben Rechte-Einschränkung scheitern wie /// der ursprüngliche Schreibversuch, SFTP kennt zudem kein eigenes /// "Kopieren". +#[allow(clippy::too_many_arguments)] async fn write_via_sudo_fallback( approval: &ApprovedFileWrite, session: &Session, @@ -422,6 +519,7 @@ async fn write_via_sudo_fallback( content: &str, existed: bool, old_mode: Option, + old_size: Option, password: &secrecy::SecretString, ) -> Result { let backup_path = if existed { @@ -431,14 +529,13 @@ async fn write_via_sudo_fallback( }; // "Before" hash: only when the old content is readable over SFTP (e.g. a - // 0644 root file); `None` when the read itself is denied or fails. + // 0644 root file); `None` when the read is denied or fails, or when the file turns out + // larger than its `stat` size. let mut sha256_before = None; if existed { let mut guard = session.lock_sftp().await; if let Some(sftp) = guard.sftp() { - if let Ok(old) = sftp.read_file(path).await { - sha256_before = Some(sha256_hex(&old)); - } + sha256_before = hash_old_content(sftp, path, old_size.unwrap_or(0)).await; } } @@ -571,7 +668,8 @@ pub(crate) async fn execute_write_remote_file( } }; - let regular = write_via_sftp_with_backup(session, &path, wire_content, existed).await; + let regular = + write_via_sftp_with_backup(session, &path, wire_content, existed, bytes_before).await; let (done, used_sudo_password) = match regular { Ok(done) => (done, false), @@ -617,6 +715,7 @@ pub(crate) async fn execute_write_remote_file( wire_content, existed, old_mode, + bytes_before, &password, ) .await @@ -704,3 +803,24 @@ pub(crate) async fn execute_write_remote_file( .await; true } + +#[cfg(test)] +mod hash_tests { + use super::*; + use ssh_manager_core::ssh::mock::MockSftpSession; + + /// Issue #1714: the sudo-fallback hash covers exactly `stat`-size bytes + /// and is `None` for a file that yields more. + #[tokio::test] + async fn test_hash_old_content_is_bounded_by_the_stat_size() { + let content = vec![3u8; OLD_CONTENT_CHUNK_BYTES + 7]; + let mut sftp = MockSftpSession::new().with_file("/f", content.clone()); + assert_eq!( + hash_old_content(&mut sftp, "/f", content.len() as u64).await, + Some(sha256_hex(&content)) + ); + assert_eq!(hash_old_content(&mut sftp, "/f", 10).await, None); + let missing = hash_old_content(&mut sftp, "/nope", 10).await; + assert_eq!(missing, None); + } +} diff --git a/crates/app-logic/tests/no_unbounded_read_file.rs b/crates/app-logic/tests/no_unbounded_read_file.rs new file mode 100644 index 000000000..17ed477bf --- /dev/null +++ b/crates/app-logic/tests/no_unbounded_read_file.rs @@ -0,0 +1,52 @@ +//! Issue #1714: production code in app-logic and app-shell never calls the +#![allow(clippy::unwrap_used)] +//! unbounded `SftpSession::read_file` for a remote file; use +//! `read_file_capped`, `read_file_chunked` or `read_range`. + +use std::path::Path; + +fn production_sources(dir: &Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + production_sources(&path, out); + } else if path.extension().is_some_and(|e| e == "rs") { + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + let in_tests_dir = path.components().any(|c| { + let c = c.as_os_str().to_string_lossy(); + c == "tests" || c.ends_with("_tests") || c.starts_with("tests_") + }); + if !in_tests_dir + && name != "tests.rs" + && !name.starts_with("tests_") + && !name.ends_with("_tests.rs") + && name != "test_support.rs" + { + out.push(path); + } + } + } +} + +#[test] +fn no_production_call_of_the_unbounded_read_file() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + let mut files = Vec::new(); + production_sources(&root.join("app-logic/src"), &mut files); + production_sources(&root.join("app-shell/src"), &mut files); + let mut hits = Vec::new(); + for f in files { + let text = std::fs::read_to_string(&f).unwrap(); + for (i, line) in text.lines().enumerate() { + // The elevated wrapper forwards the trait method (revocation + // check per operation); it is the one allowed call. + if line.contains(".read_file(") && !f.ends_with("elevation/sftp_impl.rs") { + hits.push(format!("{}:{}", f.display(), i + 1)); + } + } + } + assert!( + hits.is_empty(), + "unbounded read_file called in production code: {hits:?}" + ); +} diff --git a/crates/app-shell/src/commands/sftp/copy_content.rs b/crates/app-shell/src/commands/sftp/copy_content.rs index 916f4ae0c..e5762193f 100644 --- a/crates/app-shell/src/commands/sftp/copy_content.rs +++ b/crates/app-shell/src/commands/sftp/copy_content.rs @@ -36,10 +36,11 @@ pub(super) fn too_large_for_clipboard() -> CommandError { /// wie jeder andere `sftp_*`-Befehl in diesem Abschnitt. /// /// Größenprüfung vor dem eigentlichen Lesen (per `stat`), damit eine sehr -/// große Datei nicht erst vollständig übertragen wird, bevor sie doch -/// abgelehnt wird — ein fehlgeschlagenes `stat` blockiert den Lesevorgang -/// selbst nicht (analog zu `sftp_download`s Größen-Vorablauf oben), die -/// eigentliche `read_file`-Fehlermeldung ist dann aussagekräftig genug. +/// große Datei nicht erst übertragen wird, bevor sie doch abgelehnt wird — +/// ein fehlgeschlagenes `stat` blockiert den Lesevorgang selbst nicht +/// (analog zu `sftp_download`s Größen-Vorablauf oben). Das Lesen selbst ist +/// auf das Limit plus ein Byte begrenzt, der Speicher also unabhängig von +/// der Dateigröße. #[tauri::command] pub async fn sftp_read_text( state: State<'_, AppState>, @@ -67,7 +68,7 @@ pub(super) async fn read_text_impl( let mut sftp = guard.sftp().await?; // Ein fehlgeschlagenes `stat` blockiert das Lesen nicht (s. - // Doc-Kommentar). Ein Widerruf **zwischen** `stat` und `read_file` lässt + // Doc-Kommentar). Ein Widerruf **zwischen** `stat` und dem Lesen lässt // die Datei ungelesen: die zweite Operation prüft ihn selbst (Spec 0085, // A1.1/T6b). if let Ok(entry) = sftp.stat(path).await { @@ -76,12 +77,16 @@ pub(super) async fn read_text_impl( } } - let bytes = sftp.read_file(path).await?; + // Bounded read: at most one byte over the limit is ever held, so a failed + // `stat` or a file that grew since cannot exhaust memory. + let bytes = sftp + .read_file_capped(path, MAX_TEXT_PREVIEW_BYTES + 1, &mut |_| {}) + .await?; // Spec 0086, A1.1: Die `stat`-Prüfung oben ist eine Vorabprüfung, keine // Zusage. Die Kanal-Sperre wird je Operation genommen (Spec 0085, A1.3; - // ADR 0078 §1), zwischen `stat` und `read_file` kann also ein anderer + // ADR 0078 §1), zwischen `stat` und dem Lesen kann also ein anderer // Befehl laufen und die Datei wachsen — und ein gescheitertes `stat` - // lässt sie bewusst ganz ungeprüft (s. Doc-Kommentar oben). Maßgeblich + // prüft die Größe vorab gar nicht (s. Doc-Kommentar oben). Maßgeblich // ist deshalb diese Prüfung am tatsächlich gelesenen Inhalt: nur sie // kann die Grenze halten, die der Nutzer zugesagt bekommt. if bytes.len() as u64 > MAX_TEXT_PREVIEW_BYTES { diff --git a/crates/app-shell/src/commands/sftp/edit_session.rs b/crates/app-shell/src/commands/sftp/edit_session.rs index 937ae1d67..863ec1700 100644 --- a/crates/app-shell/src/commands/sftp/edit_session.rs +++ b/crates/app-shell/src/commands/sftp/edit_session.rs @@ -144,14 +144,17 @@ pub(super) async fn open_for_editing_impl( "SFTP_TOO_LARGE_FOR_EDITING", )); } - let bytes = sftp.read_file(remote_path).await?; + // Bounded read: one byte over the limit is enough to detect "too large". + let bytes = sftp + .read_file_capped(remote_path, max_bytes.saturating_add(1), &mut |_| {}) + .await?; (bytes, entry.modified.map(|dt| dt.to_rfc3339())) }; // Spec 0086, A1.2/A1.3: und nach dem Lesen, denn die `stat`-Größe oben // ist keine Zusage — die Kanal-Sperre wird je Operation genommen (Spec - // 0085, A1.3; ADR 0078 §1), die Datei kann zwischen `stat` und - // `read_file` gewachsen sein. Die Prüfung steht **vor** jedem + // 0085, A1.3; ADR 0078 §1), die Datei kann zwischen `stat` und dem + // Lesen gewachsen sein. Die Prüfung steht **vor** jedem // Schreibzugriff ins Temp-Verzeichnis: bei einer Ablehnung entsteht dort // weder Datei noch Verzeichnis, und eine aus einem früheren „Lokal // öffnen" schon liegende Kopie bleibt unverändert (A1.3). diff --git a/crates/app-shell/src/commands/sftp/size_limit_tests.rs b/crates/app-shell/src/commands/sftp/size_limit_tests.rs index 8e9d8dca1..a50fa1734 100644 --- a/crates/app-shell/src/commands/sftp/size_limit_tests.rs +++ b/crates/app-shell/src/commands/sftp/size_limit_tests.rs @@ -121,7 +121,7 @@ impl SftpSession for MismatchSftp { .ops .lock() .unwrap() - .push(format!("read_file_capped {path}")); + .push(format!("read_file_capped {path} limit={max_bytes}")); let len = self.0.content.len().min(max_bytes as usize); self.0.bytes_served.fetch_add(len, Ordering::SeqCst); progress(len as u64); @@ -366,7 +366,10 @@ async fn test_t1_a_file_that_grew_between_stat_and_read_is_rejected_after_readin normal.ops(), vec![ "stat /t/grown.txt".to_string(), - "read_file /t/grown.txt".to_string() + format!( + "read_file_capped /t/grown.txt limit={}", + MAX_TEXT_PREVIEW_BYTES + 1 + ) ], "die Vorabprüfung per `stat` bleibt, sie bestand hier nur" ); @@ -399,6 +402,18 @@ async fn test_t2_a_failing_stat_no_longer_lets_an_oversized_file_through() { "ein gescheitertes `stat` blockiert das Lesen weiter nicht — nur das \ Ergebnis wird jetzt geprüft" ); + // Issue #1714: only a capped read with limit + 1, never the unbounded one. + assert_eq!( + normal.ops(), + vec![ + "stat /t/unstattable.txt".to_string(), + format!( + "read_file_capped /t/unstattable.txt limit={}", + MAX_TEXT_PREVIEW_BYTES + 1 + ), + ] + ); + assert_eq!(normal.bytes_served(), (MAX_TEXT_PREVIEW_BYTES + 1) as usize); } /// Spec 0086, T3: Absicherung gegen ein `>=` statt `>` — genau 256 KB @@ -504,6 +519,14 @@ async fn test_t5_a_file_that_grew_between_stat_and_read_leaves_no_local_copy() { 1, "gelesen wurde — abgelehnt wird danach, am tatsächlichen Inhalt" ); + // Issue #1714: the read is bounded to limit + 1, never the whole file. + assert_eq!( + normal.ops(), + vec![ + "stat /t/grown.conf".to_string(), + format!("read_file_capped /t/grown.conf limit={}", LIMIT + 1), + ] + ); assert_eq!( tokio::fs::read(&existing).await.unwrap(), b"FRUEHERE-KOPIE".to_vec(), @@ -511,6 +534,20 @@ async fn test_t5_a_file_that_grew_between_stat_and_read_leaves_no_local_copy() { ); } +/// Spec 0086, T5/A1.3, Issue #1714: a grown file without an earlier copy +/// leaves no edit directory at all. +#[tokio::test] +async fn test_t5_a_grown_file_creates_no_edit_directory() { + const LIMIT: u64 = 64; + let normal = MismatchSftp::claiming(10, LIMIT as usize + 1); + let s = setup(normal, untouched()).await; + + let (result, dir) = open_for_editing(&s, s.normal_channel(), "/t/grown.conf", LIMIT).await; + + assert_too_large_for_editing(result); + assert!(!dir.exists(), "no edit directory may be created: {dir:?}"); +} + /// Spec 0086, T6: Absicherung gegen ein `>=` statt `>` — genau die Grenze /// wird geöffnet. Beide Prüfungen einzeln: die per `stat` mit der **echten** /// Konstante (`stat` meldet genau 50 MB, gelesen wird wenig), die nach dem diff --git a/crates/core/src/ssh/mock.rs b/crates/core/src/ssh/mock.rs index 2042974e8..2287185c5 100644 --- a/crates/core/src/ssh/mock.rs +++ b/crates/core/src/ssh/mock.rs @@ -54,6 +54,14 @@ struct Inner { permission_denied_paths: HashSet, /// Issue #625: bietet der simulierte Server `posix-rename@openssh.com` an? posix_rename: bool, + /// Issue #1714: paths whose chunked/ranged reads fail. + read_fails_for: HashSet, + /// Issue #1714: `stat` size override per path (a file that is larger than + /// reported, like a grown log or an endless special file). + reported_sizes: HashMap, + /// Issue #1714: path -> number of `read_range` calls that still succeed. + read_range_budget: HashMap, + write_range_fails_containing: Option, /// Issue #625: Quellpfade, bei denen `rename` scheitern soll. rename_fails_for: HashSet, /// Issue #625: Pfade, die `stat` als Ordner meldet. @@ -91,6 +99,48 @@ impl MockSftpSession { self } + /// Issue #1714: `read_file_chunked` and `read_range` of `path` fail + /// with a permission error (`stat` and the file itself stay intact). + pub fn with_read_failure(self, path: impl Into) -> Self { + lock_tolerating_poison(&self.inner) + .read_fails_for + .insert(path.into()); + self + } + + /// Issue #1714: `stat` reports `size` for `path` regardless of its content. + pub fn with_reported_size(self, path: impl Into, size: u64) -> Self { + lock_tolerating_poison(&self.inner) + .reported_sizes + .insert(path.into(), size); + self + } + + /// Issue #1714: a `write_range` to a path containing `needle` creates or + /// truncates the file (as a real server does) and then fails (e.g. ENOSPC). + pub fn with_write_range_failure_containing(self, needle: impl Into) -> Self { + lock_tolerating_poison(&self.inner).write_range_fails_containing = Some(needle.into()); + self + } + + /// Issue #1714: after `n` successful `read_range` calls on `path`, the + /// next ones fail with a permission error. + pub fn with_read_failure_after(self, path: impl Into, n: usize) -> Self { + lock_tolerating_poison(&self.inner) + .read_range_budget + .insert(path.into(), n); + self + } + + /// All paths currently holding a file. + pub fn paths(&self) -> Vec { + lock_tolerating_poison(&self.inner) + .files + .keys() + .cloned() + .collect() + } + /// Issue #625: der simulierte Server bietet `posix-rename@openssh.com` an. pub fn with_posix_rename(self) -> Self { lock_tolerating_poison(&self.inner).posix_rename = true; @@ -239,6 +289,11 @@ impl SftpSession for MockSftpSession { let content = { let mut inner = lock_tolerating_poison(&self.inner); inner.calls.push(format!("read_file_chunked {path}")); + if inner.read_fails_for.contains(path) { + return Err(SshError::SftpPermissionDenied(format!( + "read denied: {path}" + ))); + } inner .files .get(path) @@ -296,6 +351,19 @@ impl SftpSession for MockSftpSession { ) -> Result, SshError> { let mut inner = lock_tolerating_poison(&self.inner); inner.calls.push(format!("read_range {path}")); + if let Some(budget) = inner.read_range_budget.get_mut(path) { + if *budget == 0 { + return Err(SshError::SftpPermissionDenied(format!( + "read denied: {path}" + ))); + } + *budget -= 1; + } + if inner.read_fails_for.contains(path) { + return Err(SshError::SftpPermissionDenied(format!( + "read denied: {path}" + ))); + } let content = &inner .files .get(path) @@ -332,6 +400,15 @@ impl SftpSession for MockSftpSession { }, ); } + if inner + .write_range_fails_containing + .as_deref() + .is_some_and(|n| path.contains(n)) + { + return Err(SshError::ChannelError(format!( + "no space left on device: {path}" + ))); + } let file = inner .files .get_mut(path) @@ -377,6 +454,7 @@ impl SftpSession for MockSftpSession { is_symlink: false, }); } + let reported = inner.reported_sizes.get(path).copied(); inner .files .get(path) @@ -384,7 +462,7 @@ impl SftpSession for MockSftpSession { name: path.rsplit('/').next().unwrap_or(path).to_string(), path: path.to_string(), is_dir: false, - size: f.content.len() as u64, + size: reported.unwrap_or(f.content.len() as u64), permissions: f.permissions, modified: f.modified, uid: None, diff --git a/docs/specs/0020-sftp-file-transfer.md b/docs/specs/0020-sftp-file-transfer.md index 8d384f69b..96e3ef6c3 100644 --- a/docs/specs/0020-sftp-file-transfer.md +++ b/docs/specs/0020-sftp-file-transfer.md @@ -111,7 +111,10 @@ 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. + Chat-Ergebnis. 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. 5. **Ergebnis.** Nach der Bestätigung wird geschrieben; Erfolg oder Fehler samt Backup-Pfad gehen als Ergebnis in den KI-Kontext zurück. @@ -137,6 +140,9 @@ Server ein Sudo-Passwort hinterlegt (Spec 0018), gilt: Modus, eine neue bekommt 0644. 4. Das Backup aus 4.2, Punkt 4 entsteht in diesem Fall ebenfalls mit Sudo (`sudo -S cp -p`), weil die Zieldatei sonst nicht kopierbar wäre. + Diese Sudo-Kopie ist nicht größenbegrenzt; nur der SHA-256-Wert „vorher“ + ist begrenzt und fehlt bei einer Datei, die größer ist als ihre + Größenabfrage meldet. 5. Ist **kein** Sudo-Passwort hinterlegt (oder wurde es nicht angekündigt), wird der Fehler unverändert gemeldet, mit dem Hinweis, dass für den Pfad erhöhte Rechte nötig sind. Es gibt keinen stillen Ersatzweg. diff --git a/docs/specs/0086-sftp-limits-and-session-pairing.md b/docs/specs/0086-sftp-limits-and-session-pairing.md index 359b006e6..ebe4c5d15 100644 --- a/docs/specs/0086-sftp-limits-and-session-pairing.md +++ b/docs/specs/0086-sftp-limits-and-session-pairing.md @@ -10,8 +10,8 @@ Review-Priorität: erhöht für A3 (Sitzungsaufbau, normaler Kanal), sonst norma - „Dateiinhalt kopieren“ funktioniert für Textdateien bis 50 MB und lehnt eine größere Datei ab, auch wenn sie erst nach der Größenabfrage so groß wurde. Ab 5 MB zeigt die Oberfläche Fortschritt und einen Abbrechen-Knopf. „Lokal öffnen“ lehnt Dateien über - 50 MB ab, vor dem Lesen, wenn die Größe schon bekannt ist, sonst nach dem - Lesen. + 50 MB ab, vor dem Lesen, wenn die Größe bekannt ist; sonst oder bei zu klein + gemeldeter Größe werden höchstens 50 MB + 1 Byte gelesen. - Scheitert ein Download oder Upload über den erhöhten Kanal, weil der Modus widerrufen wurde, nennt die Übertragungsliste denselben Text wie der Befehl. @@ -21,10 +21,10 @@ Review-Priorität: erhöht für A3 (Sitzungsaufbau, normaler Kanal), sonst norma ## 2. Nicht-Ziele -- Kein begrenztes Lesen für „Lokal öffnen“ und die Vorschau des - Upload-Vergleichs: Eine Datei darf dort kurz ganz im Speicher liegen, sie - wird nur nicht weitergegeben. „Dateiinhalt kopieren“ liest dagegen - begrenzt (A1.1). +- Keine Zusage, dass eine Datei über der Grenze gar nicht übertragen wird: + Die Größenprüfung per `stat` ist eine Vorabprüfung (A1.1, A1.2). Gelesen + wird aber nie mehr als die Grenze plus ein Byte, der Speicher hängt also + nicht von der Dateigröße ab. - Keine Grenze für Download, Upload oder die KI-Lesepfade (für die KI gilt Spec 0020, Abschnitt 4.1). - Die Meldung bei einem Wechsel des Zielnutzers im erhöhten Modus bleibt, wie @@ -48,7 +48,8 @@ Review-Priorität: erhöht für A3 (Sitzungsaufbau, normaler Kanal), sonst norma - **A1.2** „Lokal öffnen“ lehnt eine Datei über 50 MB (50 × 1024 × 1024 Bytes) ab. Meldung, wörtlich: `Datei ist größer als 50 MB — zu groß zum lokalen Öffnen. Bitte stattdessen herunterladen.` Ein gescheiterter - Größenabruf bricht den Befehl wie bisher ab. + Größenabruf bricht den Befehl wie bisher ab. Gelesen werden höchstens 50 MB + + 1 Byte. - **A1.3** Bei einer Ablehnung nach A1.2 entsteht **keine** lokale Datei und kein Ordner in der Bearbeitungskopie-Ablage. Eine dort schon liegende Kopie derselben Datei aus einem früheren „Lokal öffnen“ bleibt unverändert. @@ -63,7 +64,8 @@ Review-Priorität: erhöht für A3 (Sitzungsaufbau, normaler Kanal), sonst norma bedienbar. Abbrechen beendet das Lesen, kopiert nichts und zeigt keine Fehlermeldung. - **A1.6** Die Grenze der Vorschau im Upload-Vergleich (256 KB) und der - KI-Lesepfad (Spec 0020, Abschnitt 4.1) bleiben unverändert. + KI-Lesepfad (Spec 0020, Abschnitt 4.1) bleiben unverändert. Auch die + Vorschau liest höchstens 256 KB + 1 Byte. ### A2 — Transfer-Meldung beim Widerruf @@ -162,11 +164,15 @@ heutige Ziel umgeschrieben oder entfernt; die Kennung bleibt vergeben. Lesen und kopiert nichts. - **T3c (A1.6)** Die Vorschau des Upload-Vergleichs lehnt weiter über 256 KB ab. +- **T3d (A1.6)** Scheitert die Größenabfrage der Vorschau im Upload-Vergleich + oder meldet sie zu wenig, werden höchstens 256 KB + 1 Byte gelesen. - **T4 (A1.2)** `stat` meldet 50 MB + 1: Ablehnung mit dem Text aus A1.2, ohne dass gelesen wurde; kein Eintrag in der Bearbeitungskopie-Ablage. - **T5 (A1.2/A1.3)** `stat` meldet 10 Bytes, gelesen werden 50 MB + 1: Ablehnung, keine lokale Datei; eine vorhandene Kopie ist danach byte-gleich. + Es entsteht auch dann kein Ordner, wenn vorher keine Kopie existierte. + Gelesen wird nur bis zur Grenze + 1 Byte. - **T6 (A1.2)** Genau 50 MB werden geöffnet (Grenzwert). - **T7 (A1.4)** T3 und T4 auch über den erhöhten Kanal. - **T8 (A2.1)** Download und Upload über den erhöhten Kanal, Widerruf nach