diff --git a/changelog.d/issue-1550-bounded-file-preview.md b/changelog.d/issue-1550-bounded-file-preview.md new file mode 100644 index 000000000..20767e353 --- /dev/null +++ b/changelog.d/issue-1550-bounded-file-preview.md @@ -0,0 +1,2 @@ +### Security +- The diff preview of a proposed file write no longer reads a huge or endless target file into memory, and a denied write reads nothing at all. diff --git a/crates/app-logic/src/orchestration/action_exec/propose.rs b/crates/app-logic/src/orchestration/action_exec/propose.rs index bb859704e..30c27e29d 100644 --- a/crates/app-logic/src/orchestration/action_exec/propose.rs +++ b/crates/app-logic/src/orchestration/action_exec/propose.rs @@ -341,8 +341,12 @@ async fn announce_proposal( }; let (previous_note_content, target_name) = note_target_preview_for_action(action, ctx.session, ctx.profile_store).await; - let (previous_file_content, previous_file_size) = - previous_file_content_for_action(action, ctx.session).await; + // Issue #1550: a denied action never reads the target file. + let (previous_file_content, previous_file_size) = if matches!(decision, Decision::Deny { .. }) { + (None, None) + } else { + previous_file_content_for_action(action, ctx.session).await + }; let payload = emit_chat_action_proposed( ctx.emitter, ctx.session_id, diff --git a/crates/app-logic/src/orchestration/action_exec/tests_files_and_ledger.rs b/crates/app-logic/src/orchestration/action_exec/tests_files_and_ledger.rs index d1d104985..1078165db 100644 --- a/crates/app-logic/src/orchestration/action_exec/tests_files_and_ledger.rs +++ b/crates/app-logic/src/orchestration/action_exec/tests_files_and_ledger.rs @@ -236,7 +236,7 @@ async fn test_read_remote_file_allow_rule_autoexecs_and_redacts_content() { mock_sftp.calls(), vec![ "stat /home/deploy/app.conf", - "read_file /home/deploy/app.conf" + "read_file_capped /home/deploy/app.conf" ] ); } @@ -1499,3 +1499,160 @@ async fn test_file_actions_report_a_chat_error_when_sftp_cannot_be_opened() { ); } } + +// --- Issue #1550: bounded reads before the user decides --------------------- + +use super::super::remote_files::MAX_PREVIEW_FILE_BYTES; + +async fn run_write_proposal_turn(session: &Session) -> TestEmitter { + let emitter = TestEmitter::default(); + let profile_store = InMemoryProfileStore::default(); + let confirmations = ConfirmationRegistry::new(); + let turn = run_chat_turn( + session, + Uuid::new_v4(), + &emitter, + &profile_store, + &confirmations, + ); + let responder = deny_first_proposed_action(&emitter, &confirmations); + tokio::join!(turn, responder); + emitter +} + +fn write_proposal(path: &str) -> Vec { + vec![ + AiEvent::ActionProposed(AiAction::WriteRemoteFile { + path: path.to_string(), + content: "new".to_string(), + }), + AiEvent::Done, + ] +} + +/// The preview read never uses the uncapped `read_file` and asks for at most +/// cap + 1 bytes; a file above the cap yields a size note, no content. +#[tokio::test] +async fn preview_read_is_capped() { + let path = "/home/deploy/huge.bin"; + let session = + test_session_allowing_everything(write_proposal(path), MockSshTransport::default()); + let big = vec![b'a'; (MAX_PREVIEW_FILE_BYTES + 10) as usize]; + let sftp = MockSftpSession::new().with_file(path, big); + session.set_sftp_for_tests(Box::new(sftp.clone())).await; + + let emitter = run_write_proposal_turn(&session).await; + + let calls = sftp.calls(); + assert!( + !calls.contains(&format!("read_file {path}")), + "uncapped read: {calls:?}" + ); + assert!(calls.contains(&format!("read_file_capped {path}"))); + assert_eq!(sftp.capped_read_limits(), vec![MAX_PREVIEW_FILE_BYTES + 1]); + let events = emitter.events.lock().unwrap().clone(); + assert_eq!(events[0].1["previousFileContent"], serde_json::json!(null)); + assert_eq!( + events[0].1["previousFileSize"], + serde_json::json!(MAX_PREVIEW_FILE_BYTES) + ); +} + +/// A file exactly at the cap still gets a content preview. +#[tokio::test] +async fn preview_file_at_cap_still_shows_content() { + let path = "/home/deploy/edge.conf"; + let session = + test_session_allowing_everything(write_proposal(path), MockSshTransport::default()); + let sftp = MockSftpSession::new().with_file(path, vec![b'a'; MAX_PREVIEW_FILE_BYTES as usize]); + session.set_sftp_for_tests(Box::new(sftp)).await; + + let emitter = run_write_proposal_turn(&session).await; + let events = emitter.events.lock().unwrap().clone(); + assert!(events[0].1["previousFileContent"].is_string()); + assert_eq!(events[0].1["previousFileSize"], serde_json::json!(null)); +} + +/// A `WriteRemoteFile` denied by the filter engine triggers no SFTP access. +#[tokio::test] +async fn denied_write_proposal_reads_nothing() { + struct DenyAllWrites; + #[async_trait] + impl PolicyStore for DenyAllWrites { + async fn rules_for(&self, _scope: &EffectiveScope) -> PolicyRules { + PolicyRules::complete(vec![Rule { + id: ssh_manager_core::filter::RuleId("deny-writes".to_string()), + pattern: ssh_manager_core::filter::Pattern::Glob("sftp-write /etc/*".to_string()), + action: ssh_manager_core::filter::RuleAction::Deny, + scope: ssh_manager_core::filter::Scope::Global, + priority: 0, + origin: ssh_manager_core::filter::RuleOrigin::User, + }]) + } + } + let path = "/etc/passwd"; + let mut session = test_session(write_proposal(path), MockSshTransport::default()); + session.set_filter_engine_for_tests(Box::new(FilterEngine::new(DenyAllWrites))); + let sftp = MockSftpSession::new().with_file(path, b"root".to_vec()); + session.set_sftp_for_tests(Box::new(sftp.clone())).await; + + let emitter = TestEmitter::default(); + run_chat_turn( + &session, + Uuid::new_v4(), + &emitter, + &InMemoryProfileStore::default(), + &ConfirmationRegistry::new(), + ) + .await; + + let events = emitter.events.lock().unwrap().clone(); + assert!(events[0].1["decision"]["Deny"].is_object()); + assert!( + !sftp.calls().iter().any(|c| c.starts_with("read_file")), + "{:?}", + sftp.calls() + ); +} + +/// `ReadRemoteFile` with a failing `stat` (missing path) or size 0 reads only +/// through the capped variant. +#[tokio::test] +async fn read_remote_file_without_usable_stat_uses_capped_read_only() { + for existing in [false, true] { + let path = "/dev/zero"; + let session = test_session_allowing_everything( + vec![ + AiEvent::ActionProposed(AiAction::ReadRemoteFile { + path: path.to_string(), + }), + AiEvent::Done, + ], + MockSshTransport::default(), + ); + let mut sftp = MockSftpSession::new(); + if existing { + sftp = sftp.with_file(path, Vec::new()); + } + session.set_sftp_for_tests(Box::new(sftp.clone())).await; + let emitter = TestEmitter::default(); + run_chat_turn( + &session, + Uuid::new_v4(), + &emitter, + &InMemoryProfileStore::default(), + &ConfirmationRegistry::new(), + ) + .await; + let calls = sftp.calls(); + assert!( + calls.contains(&format!("read_file_capped {path}")), + "{calls:?}" + ); + assert!(!calls.contains(&format!("read_file {path}")), "{calls:?}"); + assert_eq!( + sftp.capped_read_limits(), + vec![crate::orchestration::remote_files::MAX_READ_FILE_BYTES + 1] + ); + } +} diff --git a/crates/app-logic/src/orchestration/action_exec/tests_path_normalisation.rs b/crates/app-logic/src/orchestration/action_exec/tests_path_normalisation.rs index 11ac3a3f4..46db48807 100644 --- a/crates/app-logic/src/orchestration/action_exec/tests_path_normalisation.rs +++ b/crates/app-logic/src/orchestration/action_exec/tests_path_normalisation.rs @@ -72,7 +72,7 @@ async fn test_read_remote_file_filter_and_sftp_see_same_normalised_path() { mock_sftp.calls(), vec![ "stat /etc/nginx/secret.conf", - "read_file /etc/nginx/secret.conf" + "read_file_capped /etc/nginx/secret.conf" ] ); } diff --git a/crates/app-logic/src/orchestration/remote_files.rs b/crates/app-logic/src/orchestration/remote_files.rs index 20e7bfc5e..13526bd59 100644 --- a/crates/app-logic/src/orchestration/remote_files.rs +++ b/crates/app-logic/src/orchestration/remote_files.rs @@ -28,6 +28,11 @@ use super::chat_turn::{emit_activity_for_action, push_history_scoped}; /// entsprechende Einstellungs-UI vorgesehen). pub(crate) const MAX_READ_FILE_BYTES: u64 = 256 * 1024; +/// Issue #1550, Spec 0020 section 4.2 point 3: upper bound for reading the +/// current target file for the diff preview. A larger file gets no content +/// preview (reported like a binary file, with this cap as the size). +pub(crate) const MAX_PREVIEW_FILE_BYTES: u64 = 1024 * 1024; + /// Lowercase hex SHA-256 of `bytes` — the content fingerprint the activity /// record keeps instead of the content itself (Spec 0057). fn sha256_hex(bytes: &[u8]) -> String { @@ -90,7 +95,15 @@ pub(crate) async fn previous_file_content_for_action( let Some(sftp) = guard.sftp() else { return (None, None); }; - match sftp.read_file(path).await { + // Issue #1550: bounded read (cap + 1 detects "larger than the cap"); the + // target may be a huge file or a special file such as /dev/zero. + match sftp + .read_file_capped(path, MAX_PREVIEW_FILE_BYTES + 1, &mut |_| {}) + .await + { + Ok(bytes) if bytes.len() as u64 > MAX_PREVIEW_FILE_BYTES => { + (None, Some(MAX_PREVIEW_FILE_BYTES)) + } Ok(bytes) => match String::from_utf8(bytes) { Ok(text) => (Some(text), None), Err(err) => (None, Some(err.into_bytes().len() as u64)), @@ -208,7 +221,12 @@ pub(crate) async fn execute_read_remote_file( let raw = { let mut guard = session.lock_sftp().await; match guard.sftp_or_err() { - Ok(sftp) => sftp.read_file(&path).await, + // Issue #1550: capped even when `stat` failed or reported 0 + // (special files such as /dev/zero); +1 detects "over the limit". + Ok(sftp) => { + sftp.read_file_capped(&path, MAX_READ_FILE_BYTES + 1, &mut |_| {}) + .await + } // Derselbe Fehlertyp wie `read_file` — der leere Kanal läuft // damit durch den bestehenden `Err`-Zweig unten, ohne dass hier // unter gehaltener SFTP-Sperre etwas emittiert wird. @@ -217,6 +235,20 @@ pub(crate) async fn execute_read_remote_file( }; match raw { + Ok(bytes) if bytes.len() as u64 > MAX_READ_FILE_BYTES => { + emit_action_error( + session, + emitter, + session_id, + format!( + "Datei '{path}' ist zu groß (Obergrenze {MAX_READ_FILE_BYTES} Bytes) \ + — wird nicht gelesen." + ), + None, + persist, + ) + .await + } Ok(bytes) => { // Activity record (Spec 0057): path, size and hash only — never // the content. Hash of the raw bytes, before redaction. diff --git a/crates/core/src/ssh/mock.rs b/crates/core/src/ssh/mock.rs index 5002d1dfa..2042974e8 100644 --- a/crates/core/src/ssh/mock.rs +++ b/crates/core/src/ssh/mock.rs @@ -45,6 +45,8 @@ struct Inner { /// Methode überhaupt erreicht wurde, z. B. "wurde vor der Bestätigung /// nichts geschrieben" (Spec 0020, Abschnitt 4.2, Punkt 2). calls: Vec, + /// `max_bytes` of every `read_file_capped` call, in order. + capped_limits: Vec, /// Pfade, bei denen `write_file` mit /// [`SshError::SftpPermissionDenied`] scheitern soll — simuliert Spec /// 0020, Abschnitt 4.3, ohne einen echten privilegierten Zielpfad zu @@ -123,6 +125,11 @@ impl MockSftpSession { lock_tolerating_poison(&self.inner).calls.clone() } + /// The `max_bytes` passed to each `read_file_capped` call, in order. + pub fn capped_read_limits(&self) -> Vec { + lock_tolerating_poison(&self.inner).capped_limits.clone() + } + /// Aktueller Inhalt eines Pfads, falls (noch) vorhanden — für Tests, die /// nach einem `write_file`/`remove`/`rename` den resultierenden Zustand /// direkt prüfen wollen, ohne selbst wieder über den Trait zu lesen. @@ -191,6 +198,7 @@ impl SftpSession for MockSftpSession { ) -> Result, SshError> { let mut inner = lock_tolerating_poison(&self.inner); inner.calls.push(format!("read_file_capped {path}")); + inner.capped_limits.push(max_bytes); let content = inner .files .get(path) diff --git a/docs/specs/0020-sftp-file-transfer.md b/docs/specs/0020-sftp-file-transfer.md index 3abc86129..b1edd18a5 100644 --- a/docs/specs/0020-sftp-file-transfer.md +++ b/docs/specs/0020-sftp-file-transfer.md @@ -77,7 +77,9 @@ vertrauenswürdig gekennzeichnet (Spec 0039). Dateien über **256 KB** werden mit klarer Meldung an Nutzer und KI abgelehnt, statt vollständig in den KI-Kontext geladen zu werden. Die Grenze ist fest, nicht einstellbar. Sie wird anhand der vorab abgefragten Größe geprüft; -liefert diese Abfrage keinen Wert, wird trotzdem gelesen. +zusätzlich begrenzt das Lesen selbst die Datenmenge, sodass auch eine Datei +ohne verwertbare Größenangabe oder eine zwischen Abfrage und Lesen gewachsene +Datei nie vollständig geladen wird, sondern abgelehnt wird. ### 4.2 Schreiben @@ -98,7 +100,12 @@ Die sicherheitskritischste Aktion dieser Spec. Ablauf: Notiz-Vorschlägen (Spec 0019). Existiert die Datei nicht, zeigt der Dialog den vollen Inhalt als neue Datei ohne Hervorhebung. Ist die bestehende Datei nicht als Text lesbar (Binärdatei), zeigt der Dialog - stattdessen einen Hinweis mit alter und neuer Größe. + stattdessen einen Hinweis mit alter und neuer Größe. Die App liest dafür + höchstens 1 MiB der bestehenden Datei; ist sie größer, wird sie wie eine + Binärdatei behandelt (Hinweis statt Diff, keine Inhaltsanzeige). Für eine + vom Filter abgelehnte Aktion liest die App die Zieldatei gar nicht. Auch + `ReadRemoteFile` liest nie mehr als die Lese-Obergrenze, selbst wenn die + Größenabfrage fehlschlägt oder 0 meldet (z. B. Spezialdateien). 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 @@ -294,6 +301,5 @@ Retina-Skalierung ein Ablegen über dem Dateibrowser nicht beim Chat landet. räumt sie nicht auf und listet sie nicht gesondert. - **Große Verzeichnisse** (mehrere tausend Einträge) werden vollständig geladen, ohne Seitenaufteilung. -- Die 256-KB-Grenze für die KI gilt nur anhand der vorab abgefragten Größe - (4.1); eine zwischen Abfrage und Lesen gewachsene Datei wird dort nicht - erneut geprüft. Für den Dateibrowser gilt die engere Regel aus Spec 0086. +- Die 256-KB-Grenze für die KI wird beim Lesen selbst durchgesetzt (4.1); + eine zwischen Abfrage und Lesen gewachsene Datei wird abgelehnt. Für den Dateibrowser gilt die engere Regel aus Spec 0086.