Skip to main content

ruso_script/script/parser/
mod.rs

1//! Parse RSL source into a [`Program`].
2//!
3//! `pest` turns the source into a parse tree according to `grammar.pest`; the
4//! modules here walk that tree and build AST nodes. One module per statement
5//! family: `metadata`, `probes`, `socket`, `body`, `match_expr`, and
6//! `statements`, with shared helpers in `helpers`.
7
8mod body;
9mod helpers;
10mod match_expr;
11mod metadata;
12mod probes;
13mod socket;
14mod statements;
15
16use pest::Parser;
17use pest::iterators::Pair;
18use thiserror::Error;
19
20use crate::script::ast::{Program, Stmt};
21use crate::script::grammar::{Rule, ScannerParser};
22
23use self::match_expr::build_qualified_expr;
24
25/// Why a script could not be parsed.
26#[derive(Debug, Error)]
27pub enum ParseError {
28    /// The source does not match the grammar. The wrapped `pest` error carries
29    /// the line, column, and the rules that were expected.
30    #[error("parse error: {0}")]
31    Pest(#[from] pest::error::Error<Rule>),
32    /// The parse tree held a rule this parser does not handle — an internal
33    /// inconsistency between `grammar.pest` and the AST builders, not a fault
34    /// in the script.
35    #[error("unexpected rule: {0:?}")]
36    UnexpectedRule(Rule),
37    /// The source parsed but is not valid: a bad literal, an out-of-range
38    /// port, an unknown severity, or nesting beyond the depth limit.
39    #[error("{0}")]
40    Invalid(String),
41}
42
43/// Maximum structural nesting depth accepted before parsing.
44///
45/// `pest` is a recursive-descent (PEG) parser, so each nested block
46/// (`if`/`for` … `end`) or object (`{ … }`) costs one parser
47/// stack frame. A few thousand levels — comfortably under the backend's
48/// 256 KiB source cap — overflow the stack and **abort the process**. A
49/// stack overflow cannot be caught by `catch_unwind` and is not bounded
50/// by the executor's wall-clock budget, so a single over-nested publish
51/// could take the whole server down. We reject such input cheaply here,
52/// before pest ever recurses. Real scanner scripts nest a handful of
53/// levels deep; 64 is generous headroom.
54const MAX_NESTING_DEPTH: usize = 64;
55
56/// Conservative pre-parse guard: bound the simultaneous nesting depth.
57///
58/// At the point of pest's deepest recursion, every still-open construct is
59/// either a brace pair (`{`…`}`) or a block keyword (`if`/`for`
60/// closed by `end`). Counting openers minus closers therefore tracks the
61/// parser's stack depth exactly, so this can't be evaded by interleaving
62/// the two forms. String (`"…"`) and regex (`'…'`) literals and `#`
63/// comments are skipped so braces/keywords inside them don't inflate the
64/// count. The scan is a single linear pass over the bytes and only slices
65/// the source at ASCII identifier boundaries, so it never panics.
66fn check_nesting_depth(source: &str) -> Result<(), ParseError> {
67    let too_deep = || {
68        ParseError::Invalid(format!(
69            "script nesting exceeds the maximum depth of {MAX_NESTING_DEPTH}"
70        ))
71    };
72    let bytes = source.as_bytes();
73    let n = bytes.len();
74    let mut i = 0;
75    let mut depth: usize = 0;
76    while i < n {
77        match bytes[i] {
78            b'#' => {
79                while i < n && bytes[i] != b'\n' {
80                    i += 1;
81                }
82            }
83            b'"' => {
84                i += 1;
85                while i < n {
86                    match bytes[i] {
87                        b'\\' => i += 2,
88                        b'"' => {
89                            i += 1;
90                            break;
91                        }
92                        _ => i += 1,
93                    }
94                }
95            }
96            b'\'' => {
97                i += 1;
98                while i < n && bytes[i] != b'\'' {
99                    i += 1;
100                }
101                i += 1;
102            }
103            b'{' => {
104                depth += 1;
105                if depth > MAX_NESTING_DEPTH {
106                    return Err(too_deep());
107                }
108                i += 1;
109            }
110            b'}' => {
111                depth = depth.saturating_sub(1);
112                i += 1;
113            }
114            b if b.is_ascii_alphabetic() || b == b'_' => {
115                let start = i;
116                while i < n && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
117                    i += 1;
118                }
119                let word = &source[start..i];
120                if word.eq_ignore_ascii_case("if") || word.eq_ignore_ascii_case("for") {
121                    depth += 1;
122                    if depth > MAX_NESTING_DEPTH {
123                        return Err(too_deep());
124                    }
125                } else if word.eq_ignore_ascii_case("end") {
126                    depth = depth.saturating_sub(1);
127                }
128            }
129            _ => i += 1,
130        }
131    }
132    Ok(())
133}
134
135/// Parse RSL source into a [`Program`].
136///
137/// This is syntax and literal validation only — no network, no filesystem, and
138/// no semantic checks on whether the probes referenced actually exist. Hand the
139/// result to [`compile`](crate::compile) to produce bytecode.
140///
141/// # Errors
142///
143/// Returns [`ParseError`] when the source does not match the grammar, carries
144/// an invalid literal, or nests deeper than the parser's depth limit.
145pub fn parse(source: &str) -> Result<Program, ParseError> {
146    // Reject pathologically nested input *before* pest recurses on it
147    // (see `check_nesting_depth`). Without this, ~46 KiB of nested blocks
148    // overflows the parser stack and aborts the process.
149    check_nesting_depth(source)?;
150
151    let mut pairs = ScannerParser::parse(Rule::program, source)?;
152    let mut statements = Vec::new();
153
154    let program = pairs
155        .next()
156        .ok_or(ParseError::UnexpectedRule(Rule::program))?;
157
158    for item in program.into_inner() {
159        match item.as_rule() {
160            Rule::statement => statements.extend(build_statement(item)?),
161            Rule::pad => {
162                let stmt = item
163                    .into_inner()
164                    .find(|p| p.as_rule() == Rule::statement)
165                    .ok_or(ParseError::UnexpectedRule(Rule::pad))?;
166                statements.extend(build_statement(stmt)?);
167            }
168            _ => {}
169        }
170    }
171
172    Ok(Program { statements })
173}
174
175pub(crate) fn build_statement(pair: Pair<Rule>) -> Result<Vec<Stmt>, ParseError> {
176    let inner = pair
177        .into_inner()
178        .next()
179        .ok_or(ParseError::UnexpectedRule(Rule::statement))?;
180
181    Ok(match inner.as_rule() {
182        Rule::metadata_block => metadata::build_metadata_block(inner)?,
183        Rule::set_stmt => vec![statements::build_set(inner)?],
184        Rule::http_block => vec![probes::build_http_block(inner)?],
185        Rule::dns_block => {
186            let probe = socket::build_socket_block(inner)?;
187            vec![Stmt::Dns(probe)]
188        }
189        Rule::tcp_block => {
190            let probe = socket::build_socket_block(inner)?;
191            vec![Stmt::Tcp(probe)]
192        }
193        Rule::udp_block => {
194            let probe = socket::build_socket_block(inner)?;
195            vec![Stmt::Udp(probe)]
196        }
197        Rule::send_stmt => vec![statements::build_send(inner)?],
198        Rule::match_stmt => {
199            let expr = inner
200                .into_inner()
201                .find(|p| p.as_rule() == Rule::qualified_expr)
202                .ok_or(ParseError::UnexpectedRule(Rule::match_stmt))?;
203            vec![Stmt::Match(build_qualified_expr(expr)?)]
204        }
205        Rule::match_group => vec![match_expr::build_match_group(inner)?],
206        Rule::assert_stmt => {
207            let expr = inner
208                .into_inner()
209                .find(|p| p.as_rule() == Rule::qualified_expr)
210                .ok_or(ParseError::UnexpectedRule(Rule::assert_stmt))?;
211            vec![Stmt::Assert(build_qualified_expr(expr)?)]
212        }
213        Rule::extract_stmt => vec![statements::build_extract(inner)?],
214        Rule::if_block => vec![statements::build_if(inner)?],
215        Rule::for_block => vec![statements::build_for(inner)?],
216        Rule::save_stmt => vec![statements::build_save(inner)?],
217        Rule::evidence_stmt => vec![statements::build_evidence(inner)?],
218        Rule::flow_stmt => vec![statements::build_flow(inner)?],
219        Rule::retry_stmt => vec![statements::build_retry(inner)?],
220        Rule::sleep_stmt => {
221            let duration = inner
222                .into_inner()
223                .find(|p| p.as_rule() == Rule::duration)
224                .map(|p| p.as_str().to_string())
225                .unwrap_or_default();
226            vec![Stmt::Sleep(duration)]
227        }
228        rule => return Err(ParseError::UnexpectedRule(rule)),
229    })
230}
231
232#[cfg(test)]
233mod nesting_tests {
234    use super::*;
235
236    #[test]
237    fn deeply_nested_input_is_rejected_not_overflowed() {
238        // Without the depth guard this same input overflows the pest parser
239        // stack and aborts the process (depth 2000 ≈ 46 KiB does it). The
240        // guard must turn it into a graceful error instead.
241        let depth = 5000;
242        let mut src = String::new();
243        for _ in 0..depth {
244            src.push_str("if a.status == 200\n");
245        }
246        src.push_str("sleep 1s\n");
247        for _ in 0..depth {
248            src.push_str("end\n");
249        }
250        match parse(&src) {
251            Err(ParseError::Invalid(msg)) => assert!(msg.contains("nesting")),
252            other => panic!("expected Invalid nesting error, got {other:?}"),
253        }
254    }
255
256    #[test]
257    fn deeply_nested_objects_are_rejected() {
258        // Brace nesting via repeated `{` (object/block openers).
259        let mut src = String::from("http p ");
260        for _ in 0..200 {
261            src.push('{');
262        }
263        let _ = parse(&src).expect_err("over-nested braces must be rejected");
264        // Specifically the depth guard, not a downstream pest error.
265        assert!(matches!(
266            check_nesting_depth(&src),
267            Err(ParseError::Invalid(_))
268        ));
269    }
270
271    #[test]
272    fn normal_nesting_passes_the_guard() {
273        // A realistically nested script (a few levels) must not trip the
274        // guard. `end` and `}` close their constructs; `endpoint`/`iframe`
275        // must not be mistaken for `end`/`if`.
276        let src = r#"
277            set endpoint "/login"
278            http probe {
279                method get
280                path "/"
281                json { "iframe": "{{ endpoint }}" }
282            }
283            if probe.status == 200
284                for marker in ["ok", "yes"]
285                    match probe.body contains "{{ marker }}"
286                end
287            end
288        "#;
289        assert!(check_nesting_depth(src).is_ok());
290    }
291
292    #[test]
293    fn braces_inside_strings_and_comments_do_not_count() {
294        let src = r#"
295            # if for repeat { { { these are in a comment
296            set s "}}}}}}{{{{{{ if if if"
297            set r '}}}}}}{{{{{{'
298        "#;
299        assert!(check_nesting_depth(src).is_ok());
300    }
301
302    #[test]
303    fn repeat_is_no_longer_valid_syntax() {
304        // `repeat` was removed from the grammar entirely; it no longer parses.
305        let src = r#"
306            repeat 2
307                sleep 1s
308            end
309        "#;
310        assert!(parse(src).is_err(), "`repeat` must not parse");
311    }
312}