Skip to main content

vtcode_safety/command_safety/shell_parser/
mod.rs

1#![expect(
2    clippy::indexing_slicing,
3    clippy::string_slice,
4    reason = "Shell parsing tracks byte offsets at character boundaries while validating operator pairs."
5)]
6
7//! Shell script parser for `bash -lc` and similar commands.
8//!
9//! This module parses shell commands like:
10//! ```sh
11//! bash -lc "git status && cargo check"
12//! ```
13//!
14//! Into individual command vectors for independent safety checking:
15//! ```text
16//! [["git", "status"], ["cargo", "check"]]
17//! ```
18//!
19//! **Phase 4 Implementation**: Uses tree-sitter for accurate bash AST parsing.
20//! Falls back to basic tokenization for minimal shell syntax.
21
22mod ast;
23
24use anyhow::Result;
25
26use ast::parse_bash_tree;
27pub use ast::{BashNode, BashTree, prewarm_bash_parser};
28
29/// Parses a shell script into individual commands using tree-sitter bash grammar
30///
31/// # Example
32/// ```text
33/// Input:  "git status && cargo check"
34/// Output: Ok([["git", "status"], ["cargo", "check"]])
35/// ```
36///
37/// # Fallback
38/// If tree-sitter parsing fails, falls back to simple tokenization
39pub fn parse_shell_commands(script: &str) -> Result<Vec<Vec<String>>, String> {
40    // Try tree-sitter parsing first
41    match parse_with_tree_sitter(script, false) {
42        Ok(commands) if !commands.is_empty() => return Ok(commands),
43        Ok(_) => {} // Empty result, fall through to basic parsing
44        Err(e) => {
45            tracing::debug!("Tree-sitter bash parsing failed: {}, falling back to basic tokenization", e);
46        }
47    }
48
49    // Fallback to simple tokenization
50    parse_with_basic_tokenization(script)
51}
52
53/// Parses a shell script using tree-sitter bash grammar only (no fallback tokenization).
54///
55/// Use this when caller behavior must be strictly gated on bash grammar validity.
56pub fn parse_shell_commands_tree_sitter(script: &str) -> Result<Vec<Vec<String>>, String> {
57    parse_with_tree_sitter(script, true)
58}
59
60/// Returns whether a shell command contains syntax whose meaning depends on
61/// shell expansion rather than the literal argument text.
62///
63/// Safety-sensitive classification must only operate on static command
64/// shapes. Parameter expansion, command substitution, brace expansion,
65/// globbing, and unquoted backslash escapes can otherwise turn a
66/// harmless-looking token into a different executable argument at runtime.
67/// Backslash escapes inside double-quoted arguments are consumed as literal
68/// argument syntax so patterns such as `rg -n "\\[profile"` remain classifiable.
69pub fn contains_dynamic_shell_syntax(command: &str) -> bool {
70    enum ShellQuote {
71        Single,
72        Double,
73    }
74
75    let mut quote: Option<ShellQuote> = None;
76    let mut characters = command.chars();
77
78    while let Some(character) = characters.next() {
79        match quote {
80            Some(ShellQuote::Single) => {
81                if character == '\'' {
82                    quote = None;
83                }
84            }
85            Some(ShellQuote::Double) => match character {
86                '"' => quote = None,
87                '$' | '`' => return true,
88                '\\'
89                    // Backslash escapes inside double quotes are literal
90                    // argument syntax. Consume the escaped character so an
91                    // escaped quote cannot incorrectly end the quoted region;
92                    // unquoted escapes remain rejected below because they can
93                    // alter the command token or its shell structure.
94                    if characters.next().is_none() => {
95                        return true;
96                    }
97                _ => {}
98            },
99            None => match character {
100                '\'' => quote = Some(ShellQuote::Single),
101                '"' => quote = Some(ShellQuote::Double),
102                '\\' | '$' | '`' | '{' | '}' | '*' | '?' | '[' | ']' => return true,
103                _ => {}
104            },
105        }
106    }
107
108    quote.is_some()
109}
110
111/// Returns whether a `find` command contains shell syntax that can change the
112/// literal option tokens after approval-time tokenization.
113pub fn contains_dynamic_find_syntax(script: &str) -> bool {
114    if let Ok(commands) = parse_shell_commands_tree_sitter(script)
115        && commands.iter().any(|command| {
116            command
117                .first()
118                .map(|program| base_command_name(program) == "find")
119                .unwrap_or(false)
120                && command.iter().any(|word| contains_dynamic_shell_syntax(word))
121        })
122    {
123        return true;
124    }
125
126    // Be conservative when the grammar cannot identify the command shape: a
127    // raw script containing a find invocation and dynamic syntax must not pass
128    // preflight just because parsing was incomplete.
129    let has_find_word = script.split_whitespace().any(|word| {
130        let command = word.trim_matches(|character: char| !character.is_ascii_alphanumeric() && character != '/');
131        base_command_name(command) == "find"
132    });
133    has_find_word && contains_dynamic_shell_syntax(script)
134}
135
136/// Returns whether every redirection in a static shell script only routes
137/// command output. Input, heredoc, and descriptor-closing redirections remain
138/// unsupported so progress classification can fail closed.
139pub fn has_only_output_redirections(script: &str) -> bool {
140    if contains_dynamic_shell_syntax(script) {
141        return false;
142    }
143    if contains_background_operator(script) {
144        return false;
145    }
146
147    let Ok(tree) = BashTree::parse(script) else {
148        return false;
149    };
150    if tree.has_error() {
151        return false;
152    }
153
154    let mut saw_redirection = false;
155    if !collect_output_redirections(tree.root(), &mut saw_redirection) {
156        return false;
157    }
158    saw_redirection
159}
160
161/// Validate literal file-redirection targets before command classification drops them.
162/// Descriptor routing carries no path; unresolved shell expansion fails closed.
163pub(crate) fn validate_redirection_paths(script: &str) -> Result<()> {
164    use anyhow::{Context, anyhow, ensure};
165    if !script.contains(['<', '>']) {
166        return Ok(());
167    }
168    let tree = BashTree::parse(script).map_err(|error| anyhow!("failed to parse shell redirections: {error}"))?;
169    ensure!(!tree.has_error(), "cannot validate malformed shell redirections");
170    let mut pending = vec![tree.root()];
171    while let Some(node) = pending.pop() {
172        if node.kind() == "file_redirect" {
173            let text = node.text();
174            let operator = text.trim_start_matches(|character: char| character.is_ascii_digit());
175            let descriptor_route = operator.starts_with(">&") || operator.starts_with("<&");
176            for destination in node.field_children("destination") {
177                let raw = destination.text();
178                ensure!(!contains_dynamic_shell_syntax(raw), "dynamic redirection destination is not allowed");
179                let words = shell_words::split(raw).context("invalid quoted redirection destination")?;
180                ensure!(words.len() == 1, "redirection destination must be one literal path");
181                let path = words.first().context("missing redirection destination")?;
182                if descriptor_route && (path == "-" || path.chars().all(|character| character.is_ascii_digit())) {
183                    continue;
184                }
185                // `sh` expands a leading `~` after validation, so treating it
186                // as a relative literal would let a redirection escape the
187                // workspace (for example, `> ~/.config`). Require callers to
188                // provide an explicit, policy-checked destination instead.
189                ensure!(!path.starts_with('~'), "home-directory redirection destinations are not allowed");
190                // The null sink is the one intentional device path used by normal commands.
191                if path == "/dev/null" {
192                    continue;
193                }
194                vtcode_commons::paths::validate_path_safety(path)
195                    .with_context(|| format!("unsafe shell redirection destination: {path}"))?;
196            }
197        }
198        pending.extend(node.named_children());
199    }
200    Ok(())
201}
202
203fn contains_background_operator(script: &str) -> bool {
204    let chars = script.chars().collect::<Vec<_>>();
205    let mut index = 0;
206    let mut in_single_quote = false;
207    let mut in_double_quote = false;
208
209    while index < chars.len() {
210        let character = chars[index];
211        if character == '\'' && !in_double_quote {
212            in_single_quote.toggle();
213            index += 1;
214            continue;
215        }
216        if character == '"' && !in_single_quote {
217            in_double_quote.toggle();
218            index += 1;
219            continue;
220        }
221        if in_single_quote || in_double_quote {
222            index += 1;
223            continue;
224        }
225
226        if character == '&' {
227            let previous = index.checked_sub(1).and_then(|position| chars.get(position));
228            let next = chars.get(index + 1);
229            if next == Some(&'&') {
230                index += 2;
231                continue;
232            }
233            let part_of_allowed_operator = next == Some(&'&')
234                || next == Some(&'>')
235                || previous == Some(&'>')
236                || previous == Some(&'|')
237                || previous == Some(&'<');
238            if !part_of_allowed_operator {
239                return true;
240            }
241        }
242        index += 1;
243    }
244
245    false
246}
247
248fn collect_output_redirections(node: BashNode<'_>, saw_redirection: &mut bool) -> bool {
249    match node.kind() {
250        "file_redirect" => {
251            *saw_redirection = true;
252            if !is_output_redirection(node.text()) {
253                return false;
254            }
255        }
256        "heredoc_redirect" | "herestring_redirect" => return false,
257        _ => {}
258    }
259
260    node.children()
261        .iter()
262        .all(|child| collect_output_redirections(*child, saw_redirection))
263}
264
265fn is_output_redirection(text: &str) -> bool {
266    let redirect = text.trim_start_matches(|character: char| character.is_ascii_digit());
267    if redirect.starts_with("&>") {
268        return !redirect.starts_with("&>-");
269    }
270    if let Some(destination) = redirect.strip_prefix(">&") {
271        return destination.trim().chars().all(|character| character.is_ascii_digit());
272    }
273
274    redirect.starts_with('>') && !redirect.starts_with(">&-")
275}
276
277/// Parses shell script using tree-sitter bash grammar.
278fn parse_with_tree_sitter(script: &str, reject_syntax_errors: bool) -> Result<Vec<Vec<String>>, String> {
279    let tree = BashTree::parse(script)?;
280
281    let mut commands = Vec::new();
282    if reject_syntax_errors && tree.has_error() {
283        return Err("Shell script contains syntax errors".to_string());
284    }
285
286    // Walk the full tree so commands inside loops/conditionals are remembered
287    // for approval and checked for safety.  Top-level-only extraction misses
288    // common read loops such as `for f in ...; do grep ...; done`.
289    collect_commands_from_node(tree.root(), &mut commands);
290
291    Ok(commands)
292}
293
294fn collect_commands_from_node(node: BashNode<'_>, commands: &mut Vec<Vec<String>>) {
295    match node.kind() {
296        "command" | "simple_command" => {
297            if let Some(cmd) = extract_command_from_node(node)
298                && !cmd.is_empty()
299            {
300                commands.push(cmd);
301            }
302        }
303        _ => {
304            for child in node.children() {
305                collect_commands_from_node(child, commands);
306            }
307        }
308    }
309}
310
311/// Extracts a command vector from a bash AST node
312fn extract_command_from_node(node: BashNode<'_>) -> Option<Vec<String>> {
313    let mut command = Vec::new();
314
315    // For pipeline nodes, extract the first command in the pipeline
316    if node.kind() == "pipeline" {
317        for child in node.children() {
318            if child.kind() == "command" || child.kind() == "simple_command" {
319                return extract_command_from_node(child);
320            }
321        }
322    }
323
324    // Extract arguments from command node
325    for child in node.children() {
326        if child.kind() == "command_name" {
327            let trimmed = child.text().trim();
328            if !trimmed.is_empty() {
329                command.push(trimmed.to_string());
330            }
331            continue;
332        }
333
334        // Leading `KEY=value` prefixes and concatenated assignment values
335        // (`NODE_OPTIONS='--require ./x'`) are part of the command's
336        // environment contract. Keep them as one word so intent/activity
337        // classification can inspect injection keys;
338        // `command_words_after_environment_prefix` still strips them before
339        // locating the executable. `concatenation` must use the full span
340        // text — its children are only the `NAME=` and quoted value pieces.
341        if matches!(child.kind(), "variable_assignment" | "concatenation") {
342            let trimmed = child.text().trim();
343            if !trimmed.is_empty() {
344                command.push(trimmed.to_string());
345            }
346            continue;
347        }
348
349        if matches!(
350            child.kind(),
351            "word" | "string" | "raw_string" | "ansi_c_string" | "simple_expansion" | "variable_expansion"
352        ) {
353            let trimmed = child.text().trim();
354            if !trimmed.is_empty() {
355                command.push(trimmed.to_string());
356            }
357        }
358    }
359
360    if command.is_empty() { None } else { Some(command) }
361}
362
363/// Fallback: Parses shell script with simple tokenization
364fn parse_with_basic_tokenization(script: &str) -> Result<Vec<Vec<String>>, String> {
365    let mut commands = Vec::new();
366    let mut current_command = String::new();
367    let mut in_quotes = false;
368    let mut quote_char = ' ';
369    let mut escaped = false;
370
371    for ch in script.chars() {
372        if escaped {
373            current_command.push(ch);
374            escaped = false;
375            continue;
376        }
377
378        match ch {
379            '\\' => {
380                escaped = true;
381            }
382            '\'' | '"' if !in_quotes => {
383                in_quotes = true;
384                quote_char = ch;
385            }
386            c if c == quote_char && in_quotes => {
387                in_quotes = false;
388            }
389            '&' | '|' | ';' if !in_quotes => {
390                if !current_command.trim().is_empty()
391                    && let Ok(cmd) = tokenize_command(&current_command)
392                {
393                    commands.push(cmd);
394                }
395                current_command.clear();
396            }
397            _ => current_command.push(ch),
398        }
399    }
400
401    if !current_command.trim().is_empty()
402        && let Ok(cmd) = tokenize_command(&current_command)
403    {
404        commands.push(cmd);
405    }
406
407    Ok(commands)
408}
409
410/// Splits a command string into arguments
411/// Respects quoted strings and escapes
412fn tokenize_command(cmd: &str) -> Result<Vec<String>, String> {
413    shell_words::split(cmd).map_err(|err| format!("failed to tokenize command: {err}"))
414}
415
416/// Parses `bash -lc "script"` style invocations
417///
418/// # Example
419/// ```text
420/// Input:  vec!["bash", "-lc", "git status && rm /"]
421/// Output: Some([["git", "status"], ["rm", "/"]])
422/// ```
423pub fn parse_bash_lc_commands(command: &[String]) -> Option<Vec<Vec<String>>> {
424    if command.is_empty() {
425        return None;
426    }
427
428    let cmd_name = command[0].as_str();
429    let base_cmd = std::path::Path::new(cmd_name)
430        .file_name()
431        .and_then(|osstr| osstr.to_str())
432        .unwrap_or("");
433
434    if base_cmd != "bash" && base_cmd != "zsh" && base_cmd != "sh" {
435        return None;
436    }
437
438    // Look for -lc or -c pattern
439    for window in command.windows(2) {
440        if matches!(window[0].as_str(), "-lc" | "-c" | "-il" | "-ic") {
441            let script = &window[1];
442            return parse_shell_commands(script).ok();
443        }
444    }
445
446    None
447}
448
449// === Injection detection (moved from tools::validation::commands) ===
450
451use anyhow::{anyhow, bail};
452
453/// Delimiter token of a quoted heredoc starting just after `<<` / `<<-`.
454///
455/// Returns `(delimiter, token_byte_len)` where the token covers the optional
456/// `-`, surrounding whitespace, and the quoted delimiter word. Bare
457/// (unquoted) delimiters return `None`: those bodies still allow substitution.
458pub(crate) fn quoted_heredoc_delim(rest: &str) -> Option<(String, usize)> {
459    let mut idx = 0usize;
460    let bytes = rest.as_bytes();
461    if bytes.first() == Some(&b'-') {
462        idx += 1;
463    }
464    while idx < bytes.len() && (bytes[idx] == b' ' || bytes[idx] == b'\t') {
465        idx += 1;
466    }
467    let quote = match bytes.get(idx) {
468        Some(b'\'') | Some(b'"') => bytes[idx],
469        _ => return None,
470    };
471    idx += 1;
472    let delim_start = idx;
473    while idx < bytes.len() && bytes[idx] != quote {
474        idx += 1;
475    }
476    if idx >= bytes.len() || idx == delim_start {
477        return None;
478    }
479    let delim = rest[delim_start..idx].to_string();
480    idx += 1; // closing quote
481    Some((delim, idx))
482}
483
484/// Byte length of a quoted heredoc body starting just after the opener line's
485/// newline, through the closing delimiter line (inclusive). Returns `None`
486/// when the closing delimiter never appears so callers keep scanning the
487/// unterminated body and fail closed on anything executable inside it.
488pub(crate) fn heredoc_body_skip_len(rest: &str, delim: &str) -> Option<usize> {
489    let bytes = rest.as_bytes();
490    let mut idx = 0usize;
491    while idx <= bytes.len() {
492        let line_end = rest[idx..].find('\n').map(|offset| idx + offset).unwrap_or(bytes.len());
493        let line = rest[idx..line_end].trim_end_matches('\r');
494        let next = if line_end < bytes.len() {
495            line_end + 1
496        } else {
497            bytes.len()
498        };
499        if line == delim {
500            return Some(next);
501        }
502        if line_end >= bytes.len() {
503            return None;
504        }
505        idx = next;
506    }
507    None
508}
509
510/// Advance a `CharIndices` iterator by at most `max_bytes`, returning the byte
511/// index just past the last consumed char (or `fallback` when nothing remains).
512fn consume_bytes(
513    chars: &mut std::iter::Peekable<std::str::CharIndices<'_>>,
514    max_bytes: usize,
515    fallback: usize,
516) -> usize {
517    let mut consumed = 0usize;
518    let mut end = fallback;
519    while consumed < max_bytes
520        && let Some((idx, ch)) = chars.next()
521    {
522        consumed += ch.len_utf8();
523        end = idx + ch.len_utf8();
524    }
525    end
526}
527
528/// Quote state for shell segment splitting.
529#[derive(Clone, Copy, Eq, PartialEq)]
530enum QuoteState {
531    None,
532    Single,
533    Double,
534}
535
536/// Command substitution construct that tripped an injection scan.
537#[derive(Clone, Copy, Debug, PartialEq, Eq)]
538pub(crate) enum SubstitutionKind {
539    Backtick,
540    DollarParen,
541}
542
543impl SubstitutionKind {
544    fn label(self) -> &'static str {
545        match self {
546            Self::Backtick => "backtick",
547            Self::DollarParen => "'$('",
548        }
549    }
550}
551
552/// Actionable injection error: names the construct and its byte offset so the
553/// caller can locate the rejected span in its own command. Keeps the legacy
554/// "Command injection pattern detected" prefix so downstream policy matchers
555/// (`preflight_policy_correction`) keep routing to the security-policy branch.
556pub(crate) fn substitution_error(kind: SubstitutionKind, byte_idx: usize) -> anyhow::Error {
557    anyhow!(
558        "Command injection pattern detected: {} command substitution at byte {byte_idx}; rewrite without dynamic expansion",
559        kind.label()
560    )
561}
562
563/// Split a shell command into segments on unquoted `|` and `&` boundaries,
564/// while detecting injection patterns (`;`, backticks, `$()`, newlines).
565pub(crate) fn split_shell_segments(command: &str) -> Result<Vec<String>> {
566    let mut segments = Vec::new();
567    let mut state = QuoteState::None;
568    let mut escaped = false;
569    let mut segment_start = 0usize;
570    // Delimiter of a `<<'EOF'`-shaped heredoc whose opener line has not ended
571    // yet. The opener line stays live shell; the body is skipped at the
572    // unquoted newline.
573    let mut pending_heredoc: Option<String> = None;
574    let mut chars = command.char_indices().peekable();
575
576    while let Some((idx, ch)) = chars.next() {
577        match state {
578            QuoteState::Single => {
579                if ch == '\'' {
580                    state = QuoteState::None;
581                }
582            }
583            QuoteState::Double => {
584                if escaped {
585                    escaped = false;
586                    continue;
587                }
588
589                match ch {
590                    '\\' => escaped = true,
591                    '"' => state = QuoteState::None,
592                    '`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
593                    '$' if matches!(chars.peek(), Some((_, '('))) => {
594                        return Err(substitution_error(SubstitutionKind::DollarParen, idx));
595                    }
596                    _ => {}
597                }
598            }
599            QuoteState::None => {
600                if escaped {
601                    escaped = false;
602                    continue;
603                }
604
605                match ch {
606                    '\\' => escaped = true,
607                    '\'' => state = QuoteState::Single,
608                    '"' => state = QuoteState::Double,
609                    // Quoted heredoc bodies are literal data (newlines, backticks
610                    // included). Arm the skip here but keep scanning: everything
611                    // after the delimiter on the opener line is live shell, so
612                    // operators there must still split segments or bail. The
613                    // body is skipped at the unquoted opener newline below.
614                    '<' if matches!(chars.peek(), Some((_, '<'))) => {
615                        let _ = chars.next(); // second '<'
616                        let rest: String = chars.clone().map(|(_, c)| c).collect();
617                        if let Some((delim, token_len)) = quoted_heredoc_delim(&rest) {
618                            let _ = consume_bytes(&mut chars, token_len, idx + ch.len_utf8());
619                            pending_heredoc = Some(delim);
620                        }
621                    }
622                    '`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
623                    '$' if matches!(chars.peek(), Some((_, '('))) => {
624                        return Err(substitution_error(SubstitutionKind::DollarParen, idx));
625                    }
626                    ';' => bail!("Unquoted command chaining detected"),
627                    '\n' => {
628                        // The opener line ended in unquoted context: the quoted
629                        // heredoc body starts here and is literal data. Without
630                        // a closing delimiter the body keeps being scanned, so
631                        // executable content in it still fails closed.
632                        if let Some(delim) = pending_heredoc.take() {
633                            let rest: String = chars.clone().map(|(_, c)| c).collect();
634                            if let Some(skip) = heredoc_body_skip_len(&rest, &delim) {
635                                // The opener line is a live command; the body
636                                // belongs to no segment.
637                                push_segment(command, segment_start, idx, &mut segments);
638                                segment_start = consume_bytes(&mut chars, skip, command.len());
639                                continue;
640                            }
641                        }
642                        bail!(
643                            "multi-line shell commands are not allowed; write the content with `apply_patch` instead of a heredoc"
644                        );
645                    }
646                    '|' | '&' => {
647                        push_segment(command, segment_start, idx, &mut segments);
648                        segment_start = idx + ch.len_utf8();
649                        if let Some((next_idx, next_ch)) = chars.peek().copied()
650                            && next_ch == ch
651                        {
652                            let _next = chars.next();
653                            segment_start = next_idx + next_ch.len_utf8();
654                        }
655                    }
656                    _ => {}
657                }
658            }
659        }
660    }
661
662    push_segment(command, segment_start, command.len(), &mut segments);
663    Ok(segments)
664}
665
666fn push_segment(command: &str, start: usize, end: usize, segments: &mut Vec<String>) {
667    let segment = command[start..end].trim();
668    if !segment.is_empty() {
669        segments.push(segment.to_string());
670    }
671}
672
673/// Check for additional dangerous patterns not covered by the central dangerous-command detector.
674pub(crate) fn additional_dangerous_pattern(segment: &str) -> Option<&'static str> {
675    let segment_lower = segment.to_ascii_lowercase();
676    if segment_lower.starts_with(":(){:|:&};:") {
677        return Some(":(){:|:&};:");
678    }
679
680    let tokens =
681        shell_words::split(segment).unwrap_or_else(|_| segment.split_whitespace().map(ToString::to_string).collect());
682    let first = tokens.first()?;
683    let command_name = base_command_name(strip_wrapping_quotes(first)).to_ascii_lowercase();
684
685    match command_name.as_str() {
686        "rmdir" => Some("rmdir"),
687        "wget" => Some("wget"),
688        "curl" => Some("curl"),
689        "chmod" if tokens.iter().skip(1).any(|arg| strip_wrapping_quotes(arg).starts_with("777")) => Some("chmod 777"),
690        "chown"
691            if tokens.iter().skip(1).any(|arg| {
692                let arg = strip_wrapping_quotes(arg).to_ascii_lowercase();
693                arg == "root" || arg.starts_with("root:")
694            }) =>
695        {
696            Some("chown root")
697        }
698        _ => None,
699    }
700}
701
702fn strip_wrapping_quotes(token: &str) -> &str {
703    token
704        .strip_prefix('\'')
705        .and_then(|token| token.strip_suffix('\''))
706        .or_else(|| token.strip_prefix('"').and_then(|token| token.strip_suffix('"')))
707        .unwrap_or(token)
708}
709
710fn base_command_name(command: &str) -> &str {
711    std::path::Path::new(command)
712        .file_name()
713        .and_then(|name| name.to_str())
714        .unwrap_or(command)
715}
716#[cfg(test)]
717mod tests;