Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(quoting): add quoted-heredoc body stripping to prevent false positives

Steven Enamakel7d94c88a922f
diff --git a/crates/openhuman-core/src/security/policy/policy_command/quoting.rs b/crates/openhuman-core/src/security/policy/policy_command/quoting.rs
index 239fa6c4fa..53ce1a9958 100644
--- a/crates/openhuman-core/src/security/policy/policy_command/quoting.rs
+++ b/crates/openhuman-core/src/security/policy/policy_command/quoting.rs
@@ -1,6 +1,10 @@
//! Quote-aware shell-string scanning: splitting a command into `;`/`|`/`&&`/
//! `||`-separated segments, and detecting unquoted control characters
-//! (`&`, arbitrary redirects) without being fooled by quoted literals.
+//! (`&`, arbitrary redirects) without being fooled by quoted literals, plus a
+//! pre-pass that blanks quoted-heredoc bodies so document text is not scanned
+//! as shell syntax.
+
+use std::borrow::Cow;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum QuoteState {
@@ -280,3 +284,162 @@ pub(in crate::security::policy) fn contains_unquoted_char(command: &str, target:
false
}
+
+/// Blank out the body of every **quoted-delimiter** heredoc in `command`.
+///
+/// `classify_command` and the structural guards scan the raw command string, so
+/// until now a heredoc body was read as live shell text. That is wrong for a
+/// quoted delimiter: in `cat > f << 'EOF' … EOF` the shell performs no
+/// expansion inside the body, so an `&`, a `` ` `` or a `$(` there is data.
+/// Measured consequence (life-scenario `meal-plan`): a recipe document was
+/// refused as "background (&) is not allowed" because four dinner titles read
+/// "Chicken & Spinach".
+///
+/// An **unquoted** delimiter (`<< EOF`) is deliberately left alone — expansion
+/// *is* live inside that body, so `$(rm -rf ~)` there really would execute and
+/// must keep tripping the guard.
+///
+/// Body lines are replaced by empty lines rather than removed, so line counts,
+/// the surrounding command text and the `>` of the redirect are all preserved:
+/// a heredoc write still classifies as [`CommandClass::Write`] and still
+/// prompts. Returns [`Cow::Borrowed`] when the command has no quoted heredoc,
+/// which is the overwhelmingly common case.
+pub(in crate::security::policy) fn strip_quoted_heredoc_bodies(command: &str) -> Cow<'_, str> {
+ if !command.contains("<<") {
+ return Cow::Borrowed(command);
+ }
+
+ let mut delimiters: Vec<String> = Vec::new();
+ let mut quote = QuoteState::None;
+ let mut escaped = false;
+ let mut chars = command.char_indices().peekable();
+ // Byte offsets of the `<<` operators whose delimiter is quoted, in order.
+ let mut operators: Vec<usize> = Vec::new();
+
+ while let Some((idx, ch)) = chars.next() {
+ match quote {
+ QuoteState::Single => {
+ if ch == '\'' {
+ quote = QuoteState::None;
+ }
+ }
+ QuoteState::Double => {
+ if escaped {
+ escaped = false;
+ continue;
+ }
+ match ch {
+ '\\' => escaped = true,
+ '"' => quote = QuoteState::None,
+ _ => {}
+ }
+ }
+ QuoteState::None => {
+ if escaped {
+ escaped = false;
+ continue;
+ }
+ match ch {
+ '\\' => escaped = true,
+ '\'' => quote = QuoteState::Single,
+ '"' => quote = QuoteState::Double,
+ '<' if chars.next_if(|(_, c)| *c == '<').is_some() => {
+ // `<<<` is a here-string, not a heredoc: no body follows.
+ if chars.next_if(|(_, c)| *c == '<').is_some() {
+ continue;
+ }
+ let rest = &command[idx + 2..];
+ if let Some((delim, consumed)) = quoted_heredoc_delimiter(rest) {
+ delimiters.push(delim);
+ operators.push(idx);
+ // Skip past the delimiter token so its quotes do not
+ // re-enter the quote state machine.
+ for _ in 0..consumed {
+ chars.next();
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ }
+
+ if operators.is_empty() {
+ return Cow::Borrowed(command);
+ }
+
+ // Walk the lines. Once the line carrying the Nth operator ends, every
+ // following line is body until its terminator line appears.
+ let mut out = String::with_capacity(command.len());
+ let mut next_delim = 0usize;
+ let mut open: Option<String> = None;
+ let mut consumed_bytes = 0usize;
+
+ for line in command.split_inclusive('\n') {
+ let line_start = consumed_bytes;
+ consumed_bytes += line.len();
+
+ if let Some(delim) = open.clone() {
+ if line.trim() == delim {
+ open = None;
+ out.push_str(line);
+ } else {
+ // Blank the body, keeping the newline so offsets stay sane.
+ if line.ends_with('\n') {
+ out.push('\n');
+ }
+ }
+ continue;
+ }
+
+ out.push_str(line);
+ let line_end = line_start + line.len();
+ while next_delim < operators.len() && operators[next_delim] < line_end {
+ // The last operator on a line wins: `cat << 'A' << 'B'` reads A's
+ // body first, but only tracking one at a time is enough for the
+ // guard, and a nested case simply keeps scanning as today.
+ open = Some(delimiters[next_delim].clone());
+ next_delim += 1;
+ }
+ }
+
+ Cow::Owned(out)
+}
+
+/// Parse a heredoc delimiter token immediately after `<<`, returning the
+/// delimiter and how many chars of `rest` it spans — **only** when the token is
+/// quoted (`'EOF'` or `"EOF"`), optionally preceded by `-` and whitespace.
+/// An unquoted delimiter returns `None`, because its body is still expanded.
+fn quoted_heredoc_delimiter(rest: &str) -> Option<(String, usize)> {
+ let mut consumed = 0usize;
+ let mut chars = rest.chars().peekable();
+
+ if chars.peek() == Some(&'-') {
+ chars.next();
+ consumed += 1;
+ }
+ while chars.peek().is_some_and(|c| *c == ' ' || *c == '\t') {
+ chars.next();
+ consumed += 1;
+ }
+
+ let quote = match chars.next() {
+ Some(q @ ('\'' | '"')) => q,
+ _ => return None,
+ };
+ consumed += 1;
+
+ let mut delim = String::new();
+ for c in chars {
+ consumed += 1;
+ if c == quote {
+ return (!delim.is_empty()).then_some((delim, consumed));
+ }
+ if c == '\n' {
+ return None;
+ }
+ delim.push(c);
+ }
+ None
+}