rippy-cli 0.1.2

A shell command safety hook for AI coding tools (Claude Code, Cursor, Gemini CLI) — Rust rewrite of Dippy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use rable::{Node, NodeKind};

use crate::allowlists;

/// The operator used in a file redirect.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RedirectOp {
    /// `>` — write (truncate)
    Write,
    /// `>>` — append
    Append,
    /// `<` — read
    Read,
    /// `>&` or `&>` — file descriptor duplication
    FdDup,
    /// Anything else
    Other,
}

/// Extract the command name from a word slice.
#[must_use]
pub fn command_name_from_words(words: &[Node]) -> Option<&str> {
    words.first().and_then(word_value)
}

/// Extract the command name from a `Command` node.
#[must_use]
pub fn command_name(node: &Node) -> Option<&str> {
    let NodeKind::Command { words, .. } = &node.kind else {
        return None;
    };
    command_name_from_words(words)
}

/// Extract command arguments from a word slice (all words after the name).
#[must_use]
pub fn command_args_from_words(words: &[Node]) -> Vec<String> {
    words.iter().skip(1).map(node_text).collect()
}

/// Extract command arguments from a `Command` node.
#[must_use]
pub fn command_args(node: &Node) -> Vec<String> {
    let NodeKind::Command { words, .. } = &node.kind else {
        return Vec::new();
    };
    command_args_from_words(words)
}

/// Extract the redirect operator and target from a `Redirect` node.
#[must_use]
pub fn redirect_info(node: &Node) -> Option<(RedirectOp, String)> {
    let NodeKind::Redirect { op, target, .. } = &node.kind else {
        return None;
    };
    let redirect_op = match op.as_str() {
        ">" => RedirectOp::Write,
        ">>" => RedirectOp::Append,
        "<" | "<<<" => RedirectOp::Read,
        "&>" | ">&" => RedirectOp::FdDup,
        _ => RedirectOp::Other,
    };
    Some((redirect_op, node_text(target)))
}

/// Check whether a node contains command or process substitutions.
///
/// Rable keeps `$(...)` and backtick substitutions as literal text in word
/// values, so we check word values for expansion patterns.
#[must_use]
pub fn has_expansions(node: &Node) -> bool {
    has_expansions_kind(&node.kind)
}

/// Check for expansions in word and redirect slices.
#[must_use]
pub fn has_expansions_in_slices(words: &[Node], redirects: &[Node]) -> bool {
    words.iter().any(has_expansions) || redirects.iter().any(has_expansions)
}

/// Returns `true` if the node kind is itself a shell expansion.
///
/// This is the single source of truth for which `NodeKind` variants
/// represent expansions. Used by both `has_expansions_kind` (AST walking)
/// and `analyze_node` (verdict generation).
#[must_use]
pub const fn is_expansion_node(kind: &NodeKind) -> bool {
    matches!(
        kind,
        NodeKind::CommandSubstitution { .. }
            | NodeKind::ProcessSubstitution { .. }
            | NodeKind::ParamExpansion { .. }
            | NodeKind::ParamIndirect { .. }
            | NodeKind::ParamLength { .. }
            | NodeKind::AnsiCQuote { .. }
            | NodeKind::LocaleString { .. }
            | NodeKind::ArithmeticExpansion { .. }
            | NodeKind::BraceExpansion { .. }
    )
}

fn has_expansions_kind(kind: &NodeKind) -> bool {
    if is_expansion_node(kind) {
        return true;
    }
    match kind {
        NodeKind::Word { value, parts, .. } => {
            // Trust the parsed parts when present: rable decomposes words into
            // typed expansion nodes, so a `Word` whose parts are all literal
            // (e.g., `WordLiteral` for `'$(whoami)'`) contains no expansion
            // even though its raw value has metacharacters.
            //
            // Only fall back to the textual scan when parts are absent (e.g.,
            // synthetic words from heredoc content).
            if parts.is_empty() {
                has_shell_expansion_pattern(value)
            } else {
                parts.iter().any(has_expansions)
            }
        }
        NodeKind::Command {
            words, redirects, ..
        } => has_expansions_in_slices(words, redirects),
        NodeKind::Pipeline { commands, .. } => commands.iter().any(has_expansions),
        NodeKind::List { items } => items.iter().any(|item| has_expansions(&item.command)),
        NodeKind::Redirect { target, .. } => has_expansions(target),
        NodeKind::If {
            condition,
            then_body,
            else_body,
            ..
        } => {
            has_expansions(condition)
                || has_expansions(then_body)
                || else_body.as_deref().is_some_and(has_expansions)
        }
        NodeKind::Subshell { body, .. } | NodeKind::BraceGroup { body, .. } => has_expansions(body),
        NodeKind::HereDoc {
            content, quoted, ..
        } => !quoted && has_shell_expansion_pattern(content),
        _ => false,
    }
}

/// Check if a string contains shell expansion patterns (`$(`, `` ` ``, `${`, or `$` + identifier).
///
/// Used for heredoc content and other string-level expansion detection where
/// structured AST nodes are not available.
#[must_use]
pub fn has_shell_expansion_pattern(s: &str) -> bool {
    let bytes = s.as_bytes();
    for (i, &b) in bytes.iter().enumerate() {
        if b == b'`' {
            return true;
        }
        if b == b'$'
            && let Some(&next) = bytes.get(i + 1)
            && (next == b'('
                || next == b'{'
                || next == b'\''
                || next == b'"'
                || next.is_ascii_alphabetic()
                || next == b'_')
        {
            return true;
        }
    }
    false
}

/// Check if a redirect target is inherently safe (e.g., /dev/null).
#[must_use]
pub fn is_safe_redirect_target(target: &str) -> bool {
    matches!(target, "/dev/null" | "/dev/stdout" | "/dev/stderr")
}

/// Check if a command node has file output redirects (>, >>)
/// to targets other than safe ones.
#[must_use]
pub fn has_unsafe_file_redirect(node: &Node) -> bool {
    let NodeKind::Command { redirects, .. } = &node.kind else {
        return false;
    };
    redirects.iter().any(|r| {
        let Some((op, target)) = redirect_info(r) else {
            return false;
        };
        matches!(op, RedirectOp::Write | RedirectOp::Append) && !is_safe_redirect_target(&target)
    })
}

/// Check if a node is a harmless fallback command (for `|| true` patterns).
#[must_use]
pub fn is_harmless_fallback(node: &Node) -> bool {
    let Some(name) = command_name(node) else {
        return false;
    };
    matches!(name, "true" | "false" | ":" | "echo" | "printf")
}

/// Extract text from a node, stripping quotes.
fn node_text(node: &Node) -> String {
    if let NodeKind::Word { value, .. } = &node.kind {
        strip_quotes(value)
    } else {
        String::new()
    }
}

/// Get the string value of a word node.
const fn word_value(node: &Node) -> Option<&str> {
    if let NodeKind::Word { value, .. } = &node.kind {
        Some(value.as_str())
    } else {
        None
    }
}

/// Strip surrounding quotes from a string token.
fn strip_quotes(s: &str) -> String {
    let s = s.trim();
    if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
        s[1..s.len() - 1].to_owned()
    } else if s.len() >= 3
        && ((s.starts_with("$'") && s.ends_with('\''))
            || (s.starts_with("$\"") && s.ends_with('"')))
    {
        s[2..s.len() - 1].to_owned()
    } else {
        s.to_owned()
    }
}

/// Returns `true` when a node is a safe heredoc data-passing idiom:
/// a single `SIMPLE_SAFE` command whose only redirects are quoted heredocs,
/// with no word-level expansions.
///
/// Example: `cat <<'EOF' ... EOF` — `cat` is safe, heredoc is quoted,
/// no pipes, no lists.
#[must_use]
pub fn is_safe_heredoc_substitution(command: &Node) -> bool {
    let NodeKind::Command {
        words, redirects, ..
    } = &command.kind
    else {
        return false;
    };
    let Some(name) = command_name_from_words(words) else {
        return false;
    };
    if !allowlists::is_simple_safe(name) {
        return false;
    }
    if redirects.is_empty() {
        return false;
    }
    let all_quoted_heredocs = redirects
        .iter()
        .all(|r| matches!(&r.kind, NodeKind::HereDoc { quoted, .. } if *quoted));
    if !all_quoted_heredocs {
        return false;
    }
    !words.iter().any(has_expansions)
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use crate::parser::BashParser;

    use super::*;

    fn parse_first(source: &str) -> Vec<Node> {
        let mut parser = BashParser::new().unwrap();
        parser.parse(source).unwrap()
    }

    fn find_command(nodes: &[Node]) -> Option<&Node> {
        for node in nodes {
            match &node.kind {
                NodeKind::Command { .. } => return Some(node),
                NodeKind::Pipeline { commands, .. } => {
                    if let Some(cmd) = find_command(commands) {
                        return Some(cmd);
                    }
                }
                NodeKind::List { items } => {
                    let nodes: Vec<&Node> = items.iter().map(|i| &i.command).collect();
                    if let Some(cmd) = find_command_refs(&nodes) {
                        return Some(cmd);
                    }
                }
                _ => {}
            }
        }
        None
    }

    fn find_command_refs<'a>(nodes: &[&'a Node]) -> Option<&'a Node> {
        for node in nodes {
            if matches!(node.kind, NodeKind::Command { .. }) {
                return Some(node);
            }
        }
        None
    }

    #[test]
    fn extract_command_name() {
        let nodes = parse_first("git status");
        let cmd = find_command(&nodes).unwrap();
        assert_eq!(command_name(cmd), Some("git"));
    }

    #[test]
    fn extract_command_args() {
        let nodes = parse_first("git commit -m 'hello world'");
        let cmd = find_command(&nodes).unwrap();
        let args = command_args(cmd);
        assert!(args.contains(&"commit".to_owned()));
        assert!(args.contains(&"-m".to_owned()));
    }

    #[test]
    fn detect_command_substitution() {
        let nodes = parse_first("echo $(whoami)");
        assert!(has_expansions(&nodes[0]));
    }

    #[test]
    fn no_expansions_in_literal() {
        let nodes = parse_first("echo hello");
        let cmd = find_command(&nodes).unwrap();
        assert!(!has_expansions(cmd));
    }

    #[test]
    fn redirect_write() {
        let nodes = parse_first("echo foo > output.txt");
        let NodeKind::Command { redirects, .. } = &nodes[0].kind else {
            unreachable!("expected Command node");
        };
        let (op, target) = redirect_info(&redirects[0]).unwrap();
        assert_eq!(op, RedirectOp::Write);
        assert_eq!(target, "output.txt");
    }

    #[test]
    fn redirect_append() {
        let nodes = parse_first("echo foo >> log.txt");
        let NodeKind::Command { redirects, .. } = &nodes[0].kind else {
            unreachable!("expected Command node");
        };
        let (op, target) = redirect_info(&redirects[0]).unwrap();
        assert_eq!(op, RedirectOp::Append);
        assert_eq!(target, "log.txt");
    }

    // ---- Expansion detection for hardened node types ----

    #[test]
    fn detect_param_expansion() {
        let nodes = parse_first("echo ${HOME}");
        assert!(has_expansions(&nodes[0]));
    }

    #[test]
    fn detect_simple_var_expansion() {
        let nodes = parse_first("echo $HOME");
        assert!(has_expansions(&nodes[0]));
    }

    #[test]
    fn detect_param_length() {
        let nodes = parse_first("echo ${#var}");
        assert!(has_expansions(&nodes[0]));
    }

    #[test]
    fn detect_param_indirect() {
        let nodes = parse_first("echo ${!ref}");
        assert!(has_expansions(&nodes[0]));
    }

    #[test]
    fn detect_ansi_c_quote() {
        let nodes = parse_first("echo $'\\x41'");
        assert!(has_expansions(&nodes[0]));
    }

    #[test]
    fn detect_locale_string() {
        let nodes = parse_first("echo $\"hello\"");
        assert!(has_expansions(&nodes[0]));
    }

    #[test]
    fn detect_arithmetic_expansion_inline() {
        let nodes = parse_first("echo $((1+1))");
        assert!(has_expansions(&nodes[0]));
    }

    #[test]
    fn detect_brace_expansion() {
        let nodes = parse_first("echo {a,b,c}");
        assert!(has_expansions(&nodes[0]));
    }

    #[test]
    fn detect_brace_expansion_range() {
        let nodes = parse_first("echo {1..10}");
        assert!(has_expansions(&nodes[0]));
    }

    // ---- Quote stripping for ANSI-C and locale ----

    #[test]
    fn strip_ansi_c_quotes() {
        assert_eq!(strip_quotes("$'hello'"), "hello");
    }

    #[test]
    fn strip_locale_quotes() {
        assert_eq!(strip_quotes("$\"hello\""), "hello");
    }

    #[test]
    fn strip_regular_quotes_unchanged() {
        assert_eq!(strip_quotes("'hello'"), "hello");
        assert_eq!(strip_quotes("\"hello\""), "hello");
        assert_eq!(strip_quotes("hello"), "hello");
    }

    // ---- Shell expansion pattern detection ----

    #[test]
    fn expansion_pattern_detects_dollar_var() {
        assert!(has_shell_expansion_pattern("$HOME"));
        assert!(has_shell_expansion_pattern("hello $USER world"));
        assert!(has_shell_expansion_pattern("$_private"));
    }

    #[test]
    fn expansion_pattern_detects_braced() {
        assert!(has_shell_expansion_pattern("${HOME}"));
    }

    #[test]
    fn expansion_pattern_detects_command_sub() {
        assert!(has_shell_expansion_pattern("$(whoami)"));
        assert!(has_shell_expansion_pattern("`whoami`"));
    }

    #[test]
    fn expansion_pattern_detects_ansi_c() {
        assert!(has_shell_expansion_pattern("$'hello'"));
    }

    #[test]
    fn expansion_pattern_no_false_positive() {
        assert!(!has_shell_expansion_pattern("hello world"));
        assert!(!has_shell_expansion_pattern("price is $5"));
        assert!(!has_shell_expansion_pattern(""));
    }
}