Compare commits

...
4 changed files with 312 additions and 18 deletions

No files matched your search

+114
View File
@@ -436,6 +436,83 @@ pub fn split_on_operators(cmd: &str, stop_at_pipe: bool) -> Vec<&str> {
results
}
/// Byte spans of statements separated by top-level newlines. A newline inside
/// quotes/backticks/`$( )`/`( )`, or after a trailing `|`/`&` continuation, is
/// not a separator.
pub fn split_top_level_newlines(cmd: &str) -> Vec<(usize, usize)> {
let bytes = cmd.as_bytes();
let mut spans = Vec::new();
let mut in_single = false;
let mut in_double = false;
let mut in_backtick = false;
let mut depth: usize = 0;
let mut seg_start = 0usize;
let mut last_nonspace: Option<u8> = None;
let mut i = 0usize;
while i < bytes.len() {
let b = bytes[i];
match b {
b'\\' if !in_single => {
if let Some(&next) = bytes.get(i + 1) {
if !next.is_ascii_whitespace() {
last_nonspace = Some(next);
}
i += 2;
continue;
}
}
b'\'' if !in_double && !in_backtick => {
in_single = !in_single;
last_nonspace = Some(b);
}
b'"' if !in_single && !in_backtick => {
in_double = !in_double;
last_nonspace = Some(b);
}
b'`' if !in_single && !in_double => {
in_backtick = !in_backtick;
last_nonspace = Some(b);
}
b'(' if !in_single && !in_double && !in_backtick => {
depth += 1;
last_nonspace = Some(b);
}
b')' if !in_single && !in_double && !in_backtick => {
depth = depth.saturating_sub(1);
last_nonspace = Some(b);
}
b'\n' if !in_single && !in_double && !in_backtick && depth == 0 => {
let continuation = matches!(last_nonspace, Some(b'|') | Some(b'&'));
if !continuation {
push_trimmed_span(cmd, seg_start, i, &mut spans);
seg_start = i + 1;
last_nonspace = None;
}
}
_ => {
if !b.is_ascii_whitespace() {
last_nonspace = Some(b);
}
}
}
i += 1;
}
push_trimmed_span(cmd, seg_start, bytes.len(), &mut spans);
spans
}
fn push_trimmed_span(cmd: &str, start: usize, end: usize, spans: &mut Vec<(usize, usize)>) {
let raw = &cmd[start..end];
let trimmed = raw.trim();
if trimmed.is_empty() {
return;
}
let span_start = start + (raw.len() - raw.trim_start().len());
spans.push((span_start, span_start + trimmed.len()));
}
#[cfg(test)]
pub fn strip_quotes(s: &str) -> String {
let chars: Vec<char> = s.chars().collect();
@@ -490,6 +567,43 @@ pub fn shell_split(input: &str) -> Vec<String> {
mod tests {
use super::*;
fn newline_segments(cmd: &str) -> Vec<&str> {
split_top_level_newlines(cmd)
.iter()
.map(|&(s, e)| &cmd[s..e])
.collect()
}
#[test]
fn test_split_top_level_newlines_basic() {
assert_eq!(newline_segments("ls\ngrep foo"), vec!["ls", "grep foo"]);
}
#[test]
fn test_split_top_level_newlines_skips_blank_lines() {
assert_eq!(newline_segments("ls\n\n\ngrep foo"), vec!["ls", "grep foo"]);
}
#[test]
fn test_split_top_level_newlines_quoted_newline_not_split() {
assert_eq!(split_top_level_newlines("echo \"a\nb\"").len(), 1);
}
#[test]
fn test_split_top_level_newlines_substitution_newline_not_split() {
assert_eq!(split_top_level_newlines("x=$(echo a\necho b)").len(), 1);
}
#[test]
fn test_split_top_level_newlines_pipe_continuation_not_split() {
assert_eq!(split_top_level_newlines("git log |\ngrep x").len(), 1);
}
#[test]
fn test_split_top_level_newlines_single_statement() {
assert_eq!(newline_segments("git status"), vec!["git status"]);
}
#[test]
fn test_simple_command() {
let tokens = tokenize("git status");
+173 -7
View File
@@ -5,7 +5,10 @@ use lazy_static::lazy_static;
use regex::{Regex, RegexSet};
use std::path::Path;
use super::lexer::{shell_split, split_on_operators, tokenize, ParsedToken, PipeKind, TokenKind};
use super::lexer::{
contains_unattestable_construct, shell_split, split_on_operators, split_top_level_newlines,
tokenize, ParsedToken, PipeKind, TokenKind,
};
use super::rules::{IGNORED_EXACT, IGNORED_PREFIXES, RULES};
const PHP_TOOL_NAMES: [&str; 6] = ["phpunit", "phpstan", "ecs", "pest", "paratest", "pint"];
@@ -573,16 +576,53 @@ pub fn rewrite_command(
return None;
}
if has_heredoc(trimmed) || trimmed.contains("$((") {
if has_heredoc(trimmed) {
return None;
}
let compiled = compile_exclude_patterns(excluded);
let normalized_prefixes = normalize_transparent_prefixes(transparent_prefixes);
// Simple (non-compound) already-RTK command — return as-is.
// For compound commands that start with "rtk" (e.g. "rtk git add . && cargo test"),
// fall through to rewrite_compound so the remaining segments get rewritten.
let statements = split_top_level_newlines(trimmed);
if statements.len() <= 1 {
return rewrite_logical_line(trimmed, &compiled, &normalized_prefixes);
}
let mut result = String::with_capacity(trimmed.len() + 32);
let mut any_changed = false;
let mut prev_end = 0;
for &(start, end) in &statements {
result.push_str(&trimmed[prev_end..start]);
let statement = &trimmed[start..end];
let rewritten = match rewrite_logical_line(statement, &compiled, &normalized_prefixes) {
Some(r) if r != statement => {
any_changed = true;
r
}
_ => statement.to_string(),
};
result.push_str(&rewritten);
prev_end = end;
}
result.push_str(&trimmed[prev_end..]);
if any_changed {
Some(result)
} else {
None
}
}
fn rewrite_logical_line(
line: &str,
excluded: &[ExcludePattern],
transparent_prefixes: &[String],
) -> Option<String> {
let trimmed = line.trim();
if trimmed.is_empty() {
return None;
}
let has_compound = trimmed.contains("&&")
|| trimmed.contains("||")
|| trimmed.contains(';')
@@ -592,7 +632,19 @@ pub fn rewrite_command(
return Some(trimmed.to_string());
}
rewrite_compound(trimmed, &compiled, &normalized_prefixes)
// Data-bound output, and the tokenizer can't safely split a substitution
// interior — keep verbatim so the hook never auto-allows it (#1155).
if contains_unattestable_construct(trimmed) {
return None;
}
// case terminators (`;;` `;&` `;;&`) tokenize as `;` + `;`/`&`, so
// rewrite_compound would emit invalid bash.
if trimmed.contains(";;") || trimmed.contains(";&") {
return None;
}
rewrite_compound(trimmed, excluded, transparent_prefixes)
}
/// Pipeline boundaries used to rewrite its final stage.
@@ -2012,6 +2064,120 @@ mod tests {
);
}
#[test]
fn test_rewrite_bundle_all_clean_statements() {
assert_eq!(
rewrite_command_no_prefixes("grep -rn foo src\nls -la src", &[]),
Some("rtk grep -rn foo src\nrtk ls -la src".into())
);
}
#[test]
fn test_rewrite_bundle_preserves_blank_lines() {
assert_eq!(
rewrite_command_no_prefixes("grep foo src\n\nls src", &[]),
Some("rtk grep foo src\n\nrtk ls src".into())
);
}
#[test]
fn test_rewrite_bundle_recovers_clean_statement_alongside_substitution() {
let bundle = "cd /repo\necho hi\nls -la src\ngrep -rn foo src 2>/dev/null | head\nf=$(grep -rl bar src | head -1); echo \"$f\"";
let out =
rewrite_command_no_prefixes(bundle, &[]).expect("clean ls statement should rewrite");
assert!(
out.contains("rtk ls -la src"),
"ls statement rewritten: {out}"
);
assert!(
out.contains("grep -rn foo src 2>/dev/null | head") && !out.contains("rtk grep -rn"),
"pipeline producer stays raw (#3128): {out}"
);
assert!(
out.contains("f=$(grep -rl bar src | head -1); echo \"$f\""),
"substitution statement preserved verbatim: {out}"
);
assert!(
out.starts_with("cd /repo\necho hi\n"),
"prefix preserved: {out}"
);
}
#[test]
fn test_rewrite_bundle_no_supported_statement_returns_none() {
assert_eq!(
rewrite_command_no_prefixes("cd /repo\necho hi\nf=$(whoami)", &[]),
None
);
}
#[test]
fn test_rewrite_single_substitution_statement_returns_none() {
assert_eq!(
rewrite_command_no_prefixes("git status $(whoami)", &[]),
None
);
}
#[test]
fn test_rewrite_multiline_pipeline_target_stays_raw() {
assert_eq!(
rewrite_command_no_prefixes("git log -50 |\ngrep fix |\nhead", &[]),
None
);
}
#[test]
fn test_rewrite_bundle_in_for_loop_compresses_body_leaf() {
let bundle = "for f in a b\ndo\ngrep foo \"$f\"\ndone";
let out = rewrite_command_no_prefixes(bundle, &[]).expect("loop body leaf should rewrite");
assert!(
out.contains("rtk grep foo \"$f\""),
"loop body grep rewritten: {out}"
);
assert!(
out.starts_with("for f in a b\ndo\n"),
"loop header preserved: {out}"
);
assert!(out.ends_with("\ndone"), "loop terminator preserved: {out}");
}
#[test]
fn test_rewrite_case_terminator_kept_verbatim() {
assert_eq!(
rewrite_command_no_prefixes("case $x in\na)\ngrep foo ;;\nesac", &[]),
None
);
}
#[test]
fn test_rewrite_case_fallthrough_terminator_kept_verbatim() {
assert_eq!(
rewrite_command_no_prefixes("case $x in\na)\ngrep foo ;&\nb)\nls ;;\nesac", &[]),
None
);
}
#[test]
fn test_rewrite_pipe_both_streams_kept_verbatim() {
assert_eq!(rewrite_command_no_prefixes("grep foo |& head", &[]), None);
}
#[test]
fn test_rewrite_clean_leaf_before_case_still_rewrites() {
let out = rewrite_command_no_prefixes("grep foo src\ncase $x in\na) ls ;;\nesac", &[])
.expect("leading grep should rewrite");
assert!(
out.contains("rtk grep foo src"),
"leading grep rewritten: {out}"
);
assert!(out.contains("a) ls ;;"), "case clause kept verbatim: {out}");
assert!(
!out.contains("rtk ls"),
"case-clause ls NOT rewritten: {out}"
);
}
// --- #345: RTK_DISABLED ---
#[test]
@@ -4327,7 +4493,7 @@ mod tests {
fn test_rewrite_command_substitution_passthrough() {
assert_eq!(
rewrite_command_no_prefixes("git log $(git rev-parse HEAD~1)", &[]),
Some("rtk git log $(git rev-parse HEAD~1)".into())
None
);
}
+4 -4
View File
@@ -136,11 +136,11 @@ fn decide_from_verdict(cmd: &str, verdict: PermissionVerdict) -> HookDecision {
if verdict == PermissionVerdict::Deny {
return HookDecision::Deny;
}
if crate::discover::lexer::contains_unattestable_construct(cmd) {
return HookDecision::Defer;
}
let attestable = !crate::discover::lexer::contains_unattestable_construct(cmd);
match get_rewritten(cmd) {
Some(r) if verdict == PermissionVerdict::Allow => HookDecision::AllowRewrite(r),
Some(r) if attestable && verdict == PermissionVerdict::Allow => {
HookDecision::AllowRewrite(r)
}
Some(r) => HookDecision::AskRewrite(r),
None => HookDecision::Defer,
}
+21 -7
View File
@@ -51,15 +51,15 @@ fn evaluate(cmd: &str, excluded: &[String], transparent_prefixes: &[String]) ->
return RewriteOutcome::Deny;
}
if crate::discover::lexer::contains_unattestable_construct(cmd) {
return RewriteOutcome::Passthrough;
}
// Unattestable commands may still be rewritten (clean statements compressed)
// but must never auto-allow, so exit 0 requires attestable + Allow (#1155).
let attestable = !crate::discover::lexer::contains_unattestable_construct(cmd);
match registry::rewrite_command(cmd, excluded, transparent_prefixes) {
Some(rewritten) => match verdict {
PermissionVerdict::Allow => RewriteOutcome::Allow(rewritten),
_ => RewriteOutcome::Ask(rewritten),
},
Some(rewritten) if attestable && verdict == PermissionVerdict::Allow => {
RewriteOutcome::Allow(rewritten)
}
Some(rewritten) => RewriteOutcome::Ask(rewritten),
None => RewriteOutcome::Passthrough,
}
}
@@ -140,6 +140,20 @@ mod tests {
RewriteOutcome::Ask(_)
));
}
#[test]
fn test_bundle_with_substitution_rewrites_clean_and_asks() {
match evaluate("grep -rn foo src\nf=$(whoami)", &[], &[]) {
RewriteOutcome::Ask(r) => {
assert!(
r.contains("rtk grep -rn foo src"),
"clean grep rewritten: {r}"
);
assert!(r.contains("f=$(whoami)"), "substitution preserved: {r}");
}
other => panic!("expected Ask(rewritten), got {other:?}"),
}
}
}
/// SECURITY: Verify the exit code protocol for permission verdicts.