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-1550-bounded-file-preview.md
Original file line number Diff line number Diff line change
@@ -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.
8 changes: 6 additions & 2 deletions crates/app-logic/src/orchestration/action_exec/propose.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
]
);
}
Expand Down Expand Up @@ -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<AiEvent> {
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]
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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"
]
);
}
36 changes: 34 additions & 2 deletions crates/app-logic/src/orchestration/remote_files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)),
Expand Down Expand Up @@ -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.
Expand All @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions crates/core/src/ssh/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
/// `max_bytes` of every `read_file_capped` call, in order.
capped_limits: Vec<u64>,
/// Pfade, bei denen `write_file` mit
/// [`SshError::SftpPermissionDenied`] scheitern soll — simuliert Spec
/// 0020, Abschnitt 4.3, ohne einen echten privilegierten Zielpfad zu
Expand Down Expand Up @@ -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<u64> {
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.
Expand Down Expand Up @@ -191,6 +198,7 @@ impl SftpSession for MockSftpSession {
) -> Result<Vec<u8>, 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)
Expand Down
16 changes: 11 additions & 5 deletions docs/specs/0020-sftp-file-transfer.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
`<pfad>.smartssh-backup-<zeitstempel>` an. Der Backup-Pfad steht im
Expand Down Expand Up @@ -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.
Loading