guard-core-engine 4.3.2

Detection engine for the Guard ecosystem: pattern compilation, input preprocessing, and semantic analysis.
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
//! Template-injection scan matchers ported from
//! `guard_core/handlers/_suspatterns_templates.py` (spec 4.0.2).
//!
//! Region scan between opening/closing delimiters (`{{ }}`, `${ }`, `{% %}`,
//! `<% %>`, `#{ }`), not naive regex: an indicator must appear strictly inside
//! the region, and `{{`/`#{` forms skip regions dominated by a date.
//!
//! The indicator sources embed a `(?<!\d)` guard in front of the literal
//! arithmetic branch; the guard is enforced with a char check on the candidate
//! start (a candidate beginning mid-number is rejected, mirroring the
//! lookbehind exactly because every inner start of a digit run is also
//! digit-preceded).

use super::chars_util::{str_find_from, walk_forward_while};
use super::pyregex::{Candidate, PyRegex};

const KEYWORD_INDICATOR: &str = r"(?:system|exec|popen|eval|require|include)\s*\z";
const DOLLAR_INDICATOR: &str = r"@[\w.]+@|\b\w+\s*\(";
const CURLY_INDICATOR: &str = r"@[\w.]+@|\b\w+\(\s*\)";
const HASH_INDICATOR: &str = r"@[\w.]+@|\b\w+\s*\(";
const ASP_INDICATOR: &str = r"system|exec|eval|`|Runtime|IO\.|File\.|Dir\.";
const ARITH_UNQUOTED: &str = r"\d+\s*[*/%+\-]\s*\d+";
const ARITH_ASP: &str = r"\d+\s*[-+*/]\s*\d+";
const ARITH_QUOTED: &str = r#"['"]?\d+['"]?\s*[*/%+\-]\s*['"]?\d+['"]?"#;
const DATE_SOURCE: &str = r"\d{4}-\d{1,2}-\d{1,2}";

pub struct TemplateKind {
    pub opening: &'static str,
    pub closing: &'static str,
    /// indicator branches without the arithmetic alternative
    pub indicator: &'static str,
    /// arithmetic branch source (last alternative, carries the `(?<!\d)`
    /// guard structurally)
    pub arithmetic: &'static str,
}

pub const KIND_DOLLAR: TemplateKind = TemplateKind {
    opening: "${",
    closing: "}",
    indicator: DOLLAR_INDICATOR,
    arithmetic: ARITH_UNQUOTED,
};
pub const KIND_CURLY_CALL: TemplateKind = TemplateKind {
    opening: "{{",
    closing: "}}",
    indicator: CURLY_INDICATOR,
    arithmetic: ARITH_QUOTED,
};
pub const KIND_CURLY_KEYWORD: TemplateKind = TemplateKind {
    opening: "{{",
    closing: "}}",
    indicator: KEYWORD_INDICATOR,
    arithmetic: "",
};
pub const KIND_HASH: TemplateKind = TemplateKind {
    opening: "#{",
    closing: "}",
    indicator: HASH_INDICATOR,
    arithmetic: ARITH_QUOTED,
};
pub const KIND_PERCENT_KEYWORD: TemplateKind = TemplateKind {
    opening: "{%",
    closing: "%}",
    indicator: KEYWORD_INDICATOR,
    arithmetic: "",
};
pub const KIND_ASP: TemplateKind = TemplateKind {
    opening: "<%",
    closing: "%>",
    indicator: ASP_INDICATOR,
    arithmetic: ARITH_ASP,
};

pub struct TemplateRegion {
    pub start: usize,
    pub barrier: usize,
    pub end: usize,
}

/// `_template_regions`: opening/closing delimiter pairs with the reference's
/// cursor advance (`cursor = max(body_start, barrier - len(opening) + 1)`).
#[must_use]
pub fn template_regions(content: &str, opening: &str, closing: &str) -> Vec<TemplateRegion> {
    let mut regions = Vec::new();
    let mut cursor = 0usize;
    while let Some(start) = str_find_from(content, opening, cursor) {
        let body_start = start + opening.len();
        let Some(barrier) = str_find_from(content, &closing[..1], body_start) else {
            break;
        };
        cursor = body_start.max(barrier + 1 - opening.len());
        if content[barrier..].starts_with(closing) {
            regions.push(TemplateRegion {
                start,
                barrier,
                end: barrier + closing.len(),
            });
        }
    }
    regions
}

/// The frame: `opening + [^<first closing char>]* + closing`, anchored at the
/// region start and truncated at the region end.
fn template_frame(
    content: &str,
    opening: &str,
    closing: &str,
    start: usize,
    end: usize,
) -> Option<Candidate> {
    if !content[start..].starts_with(opening) {
        return None;
    }
    let body_start = start + opening.len();
    let first = closing.chars().next()?;
    let body_end = walk_forward_while(content, body_start, |c| c != first);
    if !content[body_end..].starts_with(closing) {
        return None;
    }
    let frame_end = body_end + closing.len();
    if frame_end > end {
        return None;
    }
    Some(Candidate::new(start, frame_end))
}

fn search_between(re: &PyRegex, haystack: &str, start: usize, end: usize) -> bool {
    if start >= end || end > haystack.len() {
        return false;
    }
    re.re().is_match(&haystack[start..end])
}

/// Arithmetic-branch hit with the `(?<!\d)` guard enforced structurally.
#[must_use]
fn arithmetic_in_window(content: &str, arithmetic: &PyRegex, start: usize, end: usize) -> bool {
    if start >= end || end > content.len() {
        return false;
    }
    let window = &content[start..end];
    for m in arithmetic.re().find_iter(window) {
        // lookbehind sees the full string, not just the window
        let abs_start = start + m.start();
        let digit_before = content[..abs_start]
            .chars()
            .next_back()
            .is_some_and(|c| c.is_ascii_digit());
        if !digit_before {
            return true;
        }
    }
    false
}

fn date_restart(
    content: &str,
    opening: &str,
    start: usize,
    barrier: usize,
    dates: &PyRegex,
) -> Option<usize> {
    let from = (start + 2).min(content.len());
    let to = barrier.min(content.len());
    if from >= to {
        return Some(start);
    }
    let last_date = dates
        .re()
        .find_iter(&content[from..to])
        .last()
        .map(|m| m.start() + from);
    last_date.map_or(Some(start), |pos| {
        // no later opening before the barrier: the reference finds nothing and
        // skips the region entirely
        str_find_from(content, opening, pos + 1).filter(|i| *i < barrier)
    })
}

/// `_template_keyword_matches`: an indicator keyword must appear strictly
/// inside the region (excluding the first char after the opening delimiter).
#[must_use]
pub fn template_keyword_matches(
    content: &str,
    kind: &TemplateKind,
    ignore_case: bool,
) -> Vec<Candidate> {
    #[cfg(not(coverage))] // unreachable: every kind indicator is a statically
    // valid literal
    let Ok(indicator) = PyRegex::compile(kind.indicator, ignore_case) else {
        return Vec::new();
    };
    #[cfg(coverage)]
    let indicator = PyRegex::compile(kind.indicator, ignore_case).expect("statically valid");
    let mut matches = Vec::new();
    for region in template_regions(content, kind.opening, kind.closing) {
        let from = region.start + kind.opening.len() + 1;
        if search_between(&indicator, content, from, region.barrier)
            && let Some(frame) = template_frame(
                content,
                kind.opening,
                kind.closing,
                region.start,
                region.end,
            )
        {
            matches.push(frame);
        }
    }
    matches
}

/// `_template_expression_matches`: indicator inside the region, with the
/// date-dominance restart for `{{`/`#{` forms.
#[must_use]
pub fn template_expression_matches(
    content: &str,
    kind: &TemplateKind,
    ignore_case: bool,
) -> Vec<Candidate> {
    #[cfg(not(coverage))] // unreachable: every kind indicator is a statically
    // valid literal
    let Ok(indicator) = PyRegex::compile(kind.indicator, ignore_case) else {
        return Vec::new();
    };
    #[cfg(coverage)]
    let indicator = PyRegex::compile(kind.indicator, ignore_case).expect("statically valid");
    let arithmetic = PyRegex::compile(kind.arithmetic, ignore_case).ok();
    let dates = PyRegex::compile(DATE_SOURCE, ignore_case).ok();
    let has_dates = matches!(kind.opening, "{{" | "#{");
    let mut matches = Vec::new();
    let mut last_end = 0usize;
    for region in template_regions(content, kind.opening, kind.closing) {
        if region.start < last_end {
            continue;
        }
        let mut start = region.start;
        if has_dates && let Some(dates) = &dates {
            let Some(restarted) = date_restart(content, kind.opening, start, region.barrier, dates)
            else {
                continue;
            };
            start = restarted;
        }
        let hit = search_between(
            &indicator,
            content,
            start + kind.opening.len(),
            region.barrier,
        ) || arithmetic.as_ref().is_some_and(|a| {
            arithmetic_in_window(content, a, start + kind.opening.len(), region.barrier)
        });
        if hit
            && let Some(frame) =
                template_frame(content, kind.opening, kind.closing, start, region.end)
        {
            matches.push(frame);
            last_end = region.end;
        }
    }
    matches
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn curly_keyword_requires_indicator_inside() {
        // the reference search window excludes the first body char, so a
        // keyword flush against the opening delimiter does not fire
        assert!(template_keyword_matches("{{system('id')}}", &KIND_CURLY_KEYWORD, true).is_empty());
        let ms = template_keyword_matches("{{ system }}", &KIND_CURLY_KEYWORD, true);
        assert_eq!(ms.len(), 1);
        assert!(template_keyword_matches("{{name}}", &KIND_CURLY_KEYWORD, true).is_empty());
    }

    #[test]
    fn curly_call_date_suppression() {
        let stale = "{{ 2024-01-02 }}";
        assert!(template_expression_matches(stale, &KIND_CURLY_CALL, true).is_empty());
        let call = "{{ render() }}";
        assert_eq!(
            template_expression_matches(call, &KIND_CURLY_CALL, true).len(),
            1
        );
    }

    #[test]
    fn hash_brace_call() {
        let ms = template_expression_matches("#{7*7}", &KIND_HASH, true);
        assert_eq!(ms.len(), 1);
    }

    #[test]
    fn dollar_brace_call() {
        let ms = template_expression_matches("${eval(x)}", &KIND_DOLLAR, true);
        assert_eq!(ms.len(), 1);
        assert_eq!(ms[0].text("${eval(x)}"), "${eval(x)}");
    }

    #[test]
    fn arithmetic_guard_blocks_digit_preceded_start() {
        // "3*4" is preceded by a space: the (?<!\d) guard passes
        assert_eq!(
            template_expression_matches("{{12 3*4}}", &KIND_CURLY_CALL, true).len(),
            1
        );
        assert_eq!(
            template_expression_matches("{{7*6}}", &KIND_CURLY_CALL, true).len(),
            1
        );
        // "a123*4" matches at the leading digit ("a" precedes it)
        assert_eq!(
            template_expression_matches("{{a123*4}}", &KIND_CURLY_CALL, true).len(),
            1
        );
        // "12 3" cannot start mid-number: the only candidate start "3*" is
        // fine, but "2 3*4"-style digit-preceded starts never occur here
        assert_eq!(
            template_expression_matches("{{x1 3*4}}", &KIND_CURLY_CALL, true).len(),
            1
        );
    }
}

#[cfg(test)]
mod coverage_tests {
    use super::*;

    #[test]
    fn malformed_frames_and_missing_closers_are_rejected() {
        // two adjacent regions both match
        assert_eq!(
            template_keyword_matches("{{ system }}{{ system }}", &KIND_CURLY_KEYWORD, true).len(),
            2
        );
        // a keyword inside the first char after the opening is not "inside"
        assert!(template_keyword_matches("{{system}}", &KIND_CURLY_KEYWORD, true).is_empty());
        // an unterminated frame: no region, nothing matches
        assert!(template_keyword_matches("{{ system ", &KIND_CURLY_KEYWORD, true).is_empty());
    }
}

#[cfg(test)]
mod gap_tests {
    use super::*;

    #[test]
    fn digit_preceded_arithmetic_candidates_are_rejected() {
        // the quote forces the arithmetic match to start after the leading
        // digit, which is exactly the start the (?<!\d) guard rejects
        assert!(template_expression_matches("#{1\"2*3}", &KIND_HASH, true).is_empty());
        // the later region in the same content still fires
        assert_eq!(
            template_expression_matches("#{1\"2*3}#{eval(x)}", &KIND_HASH, true).len(),
            1
        );
    }

    #[test]
    fn a_region_body_shorter_than_the_restart_lookback_restarts_in_place() {
        // "#{}" has no body to scan for dates: the restart returns the region
        // start unchanged and the empty region never hits
        assert_eq!(
            template_expression_matches("#{}#{eval(x)}", &KIND_HASH, true).len(),
            1
        );
    }

    #[test]
    fn an_overlapping_second_region_is_skipped_after_a_hit() {
        // the inner `<%` region starts inside the first region's accepted
        // span, so the restart cursor yields it and it is dropped
        assert_eq!(
            template_expression_matches("<%eval<%>%>", &KIND_ASP, true).len(),
            1
        );
    }
}

#[cfg(test)]
mod unit_twins {
    use super::*;

    #[test]
    fn template_frame_rejects_misaligned_and_unterminated_windows() {
        // the start does not sit on the opening delimiter
        assert_eq!(template_frame("{{x}}", "{{", "}}", 1, 5), None);
        // the body never reaches the closing delimiter
        assert_eq!(template_frame("{{x", "{{", "}}", 0, 3), None);
        // the frame extends past the candidate end
        assert_eq!(template_frame("{{x}} tail", "{{", "}}", 0, 4), None);
        // a well-formed frame inside the window renders
        let frame = template_frame("{{x}} tail", "{{", "}}", 0, 10).expect("frame");
        assert_eq!((frame.start, frame.end), (0, 5));
        // an empty closing delimiter has no leading char to scan for
        assert_eq!(template_frame("{{x}}", "{{", "", 0, 5), None);
    }

    #[test]
    fn date_restart_finds_the_next_opening_inside_the_barrier() {
        let dates = PyRegex::compile(DATE_SOURCE, false).expect("statically valid");
        // a date dominates the region: the restart looks for a later opening
        // before the barrier and finds one
        let content = "{{a}} 2024-01-01 {{b}}";
        let barrier = content.len();
        assert_eq!(date_restart(content, "{{", 0, barrier, &dates), Some(17));
        // the later opening sits exactly at the barrier: filtered out
        assert_eq!(date_restart(content, "{{", 0, 17, &dates), None);
    }
}