regorus 0.14.1

A fast, lightweight Rego (OPA policy language) interpreter
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Shared helpers: type coercion, comparison, pattern matching, and path resolution.

#![deny(
    clippy::arithmetic_side_effects,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::panic,
    clippy::shadow_unrelated,
    clippy::unwrap_used,
    clippy::missing_const_for_fn,
    clippy::option_if_let_else,
    clippy::semicolon_if_nothing_returned,
    clippy::useless_let_if_seq
)]

use crate::languages::azure_policy::strings;
use crate::value::Value;

use alloc::string::{String, ToString as _};
use alloc::vec::Vec;

// ── Type helpers ──────────────────────────────────────────────────────

pub const fn is_true(value: &Value) -> bool {
    matches!(value, Value::Bool(true))
}

pub const fn is_undefined(value: &Value) -> bool {
    matches!(value, Value::Undefined)
}

pub fn as_string(value: &Value) -> Option<String> {
    match *value {
        Value::String(ref s) => Some(s.to_string()),
        _ => None,
    }
}

/// Borrow the inner string of a `Value::String` without cloning.
pub fn as_str(value: &Value) -> Option<&str> {
    match *value {
        Value::String(ref s) => Some(s),
        _ => None,
    }
}

/// Coerce a value to its string representation for policy comparison operators.
///
/// Azure Policy coerces numbers and booleans to strings when used with string
/// operators (`like`, `match`, `contains`, `matchInsensitively`).  This is
/// needed when, for example, a count result (always a number) is compared
/// using a string operator: `count(...) like 2`.
pub fn coerce_to_string(value: &Value) -> Option<String> {
    match *value {
        Value::String(ref s) => Some(s.to_string()),
        Value::Number(ref n) => Some(n.format_decimal()),
        Value::Bool(b) => Some(if b { "true" } else { "false" }.to_string()),
        _ => None,
    }
}

pub fn coerce_to_string_ci(value: &Value) -> Option<String> {
    coerce_to_string(value).map(|s| strings::case_fold::fold(&s).into_owned())
}

// ── Collection helpers ────────────────────────────────────────────────

/// Check if an array or set contains a null sentinel.
pub fn collection_has_null(v: &Value) -> bool {
    match *v {
        Value::Array(ref items) => items.iter().any(|i| matches!(i, Value::Null)),
        Value::Set(ref items) => items.iter().any(|i| matches!(i, Value::Null)),
        _ => false,
    }
}

/// Check if any non-null element in a collection case-insensitively equals `target`.
/// Scalar RHS is treated as a single-element collection.
pub fn collection_any_ci_eq_excluding_null(collection: &Value, target: &Value) -> bool {
    match *collection {
        Value::Array(ref items) => items
            .iter()
            .filter(|i| !matches!(i, Value::Null))
            .any(|i| case_insensitive_equals(i, target)),
        Value::Set(ref items) => items
            .iter()
            .filter(|i| !matches!(i, Value::Null))
            .any(|i| case_insensitive_equals(i, target)),
        _ => case_insensitive_equals(collection, target),
    }
}

pub fn as_boolish(value: &Value) -> Option<bool> {
    match *value {
        Value::Bool(b) => Some(b),
        Value::String(ref s) => {
            if s.eq_ignore_ascii_case("true") {
                Some(true)
            } else if s.eq_ignore_ascii_case("false") {
                Some(false)
            } else {
                None
            }
        }
        _ => None,
    }
}

// ── Comparison and coercion ───────────────────────────────────────────

pub fn compare_values(left: &Value, right: &Value) -> Option<i8> {
    if is_undefined(left) || is_undefined(right) {
        return None;
    }

    #[allow(clippy::pattern_type_mismatch)]
    match (left, right) {
        (Value::String(a), Value::String(b)) => Some(match strings::case_fold::cmp(a, b) {
            core::cmp::Ordering::Less => -1,
            core::cmp::Ordering::Equal => 0,
            core::cmp::Ordering::Greater => 1,
        }),
        (Value::Number(a), Value::Number(b)) => Some(if a < b {
            -1
        } else if a > b {
            1
        } else {
            0
        }),
        (Value::Bool(a), Value::Bool(b)) => Some(if a == b {
            0
        } else if !a && *b {
            -1
        } else {
            1
        }),
        // String ↔ Number coercion
        (Value::String(s), Value::Number(n)) => try_coerce_to_number(s).map(|sn| {
            if &sn < n {
                -1
            } else if &sn > n {
                1
            } else {
                0
            }
        }),
        (Value::Number(n), Value::String(s)) => try_coerce_to_number(s).map(|sn| {
            if n < &sn {
                -1
            } else if n > &sn {
                1
            } else {
                0
            }
        }),
        _ => None,
    }
}

pub fn case_insensitive_equals(left: &Value, right: &Value) -> bool {
    if is_undefined(left) || is_undefined(right) {
        return false;
    }

    // Azure Policy treats an explicit null field value as "" (empty string)
    // for comparison purposes.  Missing fields are Undefined and caught above.
    #[allow(clippy::pattern_type_mismatch)]
    match (left, right) {
        (Value::Null, Value::Null) => true,
        (Value::Null, Value::String(b)) => strings::case_fold::eq("", b),
        (Value::String(a), Value::Null) => strings::case_fold::eq(a, ""),
        (Value::String(a), Value::String(b)) => strings::case_fold::eq(a, b),
        // String ↔ Number coercion
        (Value::String(s), Value::Number(_)) | (Value::Number(_), Value::String(s)) => {
            try_coerce_to_number(s).is_some_and(|n| {
                let num_val = Value::Number(n);
                let other = if matches!(left, Value::String(_)) {
                    right
                } else {
                    left
                };
                &num_val == other
            })
        }
        // String ↔ Bool coercion ("true"/"false" ↔ true/false)
        (Value::String(_), Value::Bool(b)) | (Value::Bool(b), Value::String(_)) => {
            as_boolish(if matches!(left, Value::String(_)) {
                left
            } else {
                right
            }) == Some(*b)
        }
        _ => left == right,
    }
}

/// Try to parse a string as a number for Azure Policy type coercion.
pub fn try_coerce_to_number(s: &str) -> Option<crate::number::Number> {
    use core::str::FromStr as _;
    // Try integer first, then float.
    i64::from_str(s.trim())
        .map(crate::number::Number::from)
        .ok()
        .or_else(|| {
            f64::from_str(s.trim())
                .map(crate::number::Number::from)
                .ok()
        })
}

// ── Pattern matching ──────────────────────────────────────────────────

pub fn match_pattern(input_val: &Value, pattern_val: &Value, insensitive: bool) -> bool {
    let Some(mut input) = coerce_to_string(input_val) else {
        return false;
    };
    let Some(mut pattern) = coerce_to_string(pattern_val) else {
        return false;
    };

    if insensitive {
        input = strings::case_fold::fold(&input).into_owned();
        pattern = strings::case_fold::fold(&pattern).into_owned();
    }

    match_question_hash_pattern(&input, &pattern)
}

pub fn match_like_pattern_ci(input: &str, pattern: &str) -> bool {
    wildcard_match(input, pattern)
}

fn next_char(s: &str, index: usize) -> Option<(char, usize)> {
    s.get(index..)?
        .chars()
        .next()
        .map(|ch| (ch, index.saturating_add(ch.len_utf8())))
}

fn wildcard_match(input: &str, pattern: &str) -> bool {
    let (mut ii, mut pi) = (0_usize, 0_usize);
    let mut star_pat: Option<usize> = None;
    let mut star_inp = 0_usize;

    while ii < input.len() {
        let pat = next_char(pattern, pi);
        let inp = next_char(input, ii);

        if let (Some((pc, next_pi)), Some((ic, next_ii))) = (pat, inp) {
            if pc == '?' || pc == ic {
                pi = next_pi;
                ii = next_ii;
                continue;
            }
        }

        if matches!(pat, Some(('*', _))) {
            star_pat = Some(pi);
            star_inp = ii;
            pi = pi.saturating_add('*'.len_utf8());
        } else if let Some(saved_pi) = star_pat {
            pi = saved_pi.saturating_add('*'.len_utf8());
            if let Some((_, next_ii)) = next_char(input, star_inp) {
                star_inp = next_ii;
                ii = star_inp;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    while matches!(next_char(pattern, pi), Some(('*', _))) {
        pi = pi.saturating_add('*'.len_utf8());
    }

    pi == pattern.len()
}

pub fn match_question_hash_pattern(input: &str, pattern: &str) -> bool {
    let mut input_chars = input.chars();
    let mut pattern_chars = pattern.chars();

    loop {
        match (input_chars.next(), pattern_chars.next()) {
            (None, None) => return true,
            (Some(_), None) | (None, Some(_)) => return false,
            (Some(input_char), Some(pattern_char)) => {
                if pattern_char == '.' {
                    // '.' matches any single character (letter, digit, or special).
                } else if pattern_char == '#' {
                    if !input_char.is_ascii_digit() {
                        return false;
                    }
                } else if pattern_char == '?' {
                    if !input_char.is_ascii_alphabetic() {
                        return false;
                    }
                } else if input_char != pattern_char {
                    return false;
                }
            }
        }
    }
}

// ── Path resolution ───────────────────────────────────────────────────

pub fn resolve_path(root: &Value, path: &str) -> Value {
    // An empty or unclosed bracket (e.g. `tags[ ]`, `tags[env`) names no
    // property; it must not collapse onto the parent object.
    let Some(segments) = tokenize_path(path) else {
        return Value::Undefined;
    };
    let mut current = root.clone();

    for segment in segments {
        #[allow(clippy::pattern_type_mismatch)]
        match &current {
            Value::Object(map) => {
                let mut next = None;
                for (key, value) in map.iter_sorted() {
                    if let Value::String(ref key_str) = *key {
                        if strings::keys::eq(key_str, &segment) {
                            next = Some(value.clone());
                            break;
                        }
                    }
                }

                if let Some(value) = next {
                    current = value;
                } else {
                    return Value::Undefined;
                }
            }
            Value::Array(items) => {
                let Ok(index) = segment.parse::<usize>() else {
                    return Value::Undefined;
                };

                let Some(value) = items.get(index) else {
                    return Value::Undefined;
                };
                current = value.clone();
            }
            _ => return Value::Undefined,
        }
    }

    current
}

/// The key named by the contents of a `[...]` path segment, using the same
/// rule as the Azure Policy parser: trim surrounding whitespace (as
/// `str::trim` does), then strip one matching pair of outer `'` or `"`
/// quotes. Whitespace inside the quotes is kept.
fn bracket_key(contents: &str) -> &str {
    let trimmed = contents.trim();
    trimmed
        .strip_prefix('\'')
        .and_then(|inner| inner.strip_suffix('\''))
        .or_else(|| {
            trimmed
                .strip_prefix('"')
                .and_then(|inner| inner.strip_suffix('"'))
        })
        .unwrap_or(trimmed)
}

fn tokenize_path(path: &str) -> Option<Vec<String>> {
    let mut segments = Vec::new();
    let mut token = String::new();
    let mut bracket = String::new();
    let mut in_bracket = false;

    for ch in path.chars() {
        match ch {
            '.' if !in_bracket => {
                if !token.is_empty() {
                    segments.push(token.clone());
                    token.clear();
                }
            }
            '[' => {
                in_bracket = true;
                if !token.is_empty() {
                    segments.push(token.clone());
                    token.clear();
                }
            }
            ']' => {
                in_bracket = false;
                let cleaned = bracket_key(&bracket);
                if cleaned.is_empty() {
                    return None;
                }
                segments.push(cleaned.to_string());
                bracket.clear();
            }
            _ => {
                if in_bracket {
                    bracket.push(ch);
                } else {
                    token.push(ch);
                }
            }
        }
    }

    if in_bracket {
        return None;
    }
    if !token.is_empty() {
        segments.push(token);
    }

    Some(segments)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)] // test fixtures are static JSON

    use super::{resolve_path, tokenize_path};
    use crate::Value;
    use alloc::string::ToString as _;
    use alloc::vec;

    #[test]
    fn tokenize_path_tag_brackets_follow_parser_rule() {
        for (path, expected) in [
            ("tags[env]", "env"),
            ("tags[ env ]", "env"),
            ("tags[ 'env' ]", "env"),
            ("tags[ \"env\" ]", "env"),
            ("tags[\tenv\n]", "env"),
            ("tags[ ' env ' ]", " env "),
            ("tags[\" a b \"]", " a b "),
            ("tags['env\"]", "'env\""),
            ("tags[ ' ]", "'"),
        ] {
            assert_eq!(
                tokenize_path(path),
                Some(vec!["tags".to_string(), expected.to_string()]),
                "path {path:?}"
            );
        }
    }

    #[test]
    fn resolve_path_empty_normalized_brackets_are_undefined() {
        let resource = Value::from_json_str(r#"{"tags":{"env":"production","":"empty"}}"#)
            .expect("valid resource");
        for path in [
            "tags[]",
            "tags[ ]",
            "tags[\t\n]",
            "tags[\u{3000}]",
            "tags[ '' ]",
            "tags[ \"\" ]",
            "tags[ ].env",
            "tags[   ",
            "tags[env",
        ] {
            assert_eq!(resolve_path(&resource, path), Value::Undefined, "{path:?}");
        }
    }

    #[test]
    fn resolve_path_preserves_quoted_whitespace_and_one_quote_pair() {
        let resource =
            Value::from_json_str(r#"{"tags":{" ":"space","'env'":"quoted","env":"plain"}}"#)
                .expect("valid resource");
        for (path, expected) in [
            ("tags[ ' ' ]", "space"),
            ("tags[ \" \" ]", "space"),
            ("tags[ ''env'' ]", "quoted"),
            ("tags[ env ]", "plain"),
        ] {
            assert_eq!(
                resolve_path(&resource, path),
                Value::from(expected),
                "{path:?}"
            );
        }
    }
}