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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Custom recursive-descent JSON parser for Azure Policy rules.
//!
//! Parses Azure Policy JSON directly from [`Lexer`] tokens, building span-annotated
//! AST nodes in a single pass. No intermediate `serde_json::Value` is created.
//!
//! The parser is policy-aware: when parsing JSON objects, it dispatches on key names
//! (`allOf`, `anyOf`, `not`, `field`, `value`, `count`, operator names) to build
//! the appropriate AST nodes.
//!
//! ## Usage
//!
//! ```ignore
//! use regorus::Source;
//! use regorus::languages::azure_policy::parser;
//!
//! let json = r#"{ "if": { "field": "type", "equals": "Microsoft.Compute/virtualMachines" },
//!                 "then": { "effect": "deny" } }"#;
//! let source = Source::from_contents("policy.json".into(), json.into())?;
//! let rule = parser::parse_policy_rule(&source)?;
//! ```

mod constraint;
mod core;
mod error;
mod policy_definition;
mod policy_rule;

pub(super) use self::core::json_unescape;

pub use error::ParseError;

use alloc::format;
use alloc::string::ToString as _;

use ::core::num::NonZeroU32;

use crate::lexer::{Source, TokenKind};

use super::ast::{Constraint, FieldKind, OperatorKind, PolicyDefinition, PolicyRule};
use super::expr::ExprParser;

use self::core::Parser;

/// Column-width limit for Azure Policy definitions.
///
/// Azure Policy definitions are often serialized as single-line JSON with
/// deeply nested template expressions, requiring a much higher limit than
/// the standard Rego default (1024).
pub const MAX_COL: u32 = Parser::MAX_COL;

// ============================================================================
// Public API
// ============================================================================

/// Parse an Azure Policy rule from a JSON source.
///
/// The source should contain a complete `policyRule` JSON object:
/// ```json
/// {
///   "if": { "field": "type", "equals": "Microsoft.Compute/virtualMachines" },
///   "then": { "effect": "deny" }
/// }
/// ```
///
/// Returns a span-annotated [`PolicyRule`] AST.
pub fn parse_policy_rule(source: &Source) -> Result<PolicyRule, ParseError> {
    parse_policy_rule_with_max_col(source, None)
}

/// Like [`parse_policy_rule`] but with an explicit column-width override.
///
/// When `max_col` is `None`, uses [`MAX_COL`] (the Azure Policy default).
pub fn parse_policy_rule_with_max_col(
    source: &Source,
    max_col: Option<NonZeroU32>,
) -> Result<PolicyRule, ParseError> {
    let mut parser = Parser::new_with_max_col(source, max_col.or(NonZeroU32::new(MAX_COL)))?;
    let rule = parser.parse_policy_rule()?;

    if parser.tok.0 != TokenKind::Eof {
        return Err(ParseError::UnexpectedToken {
            span: parser.tok.1.clone(),
            expected: "end of input",
        });
    }

    Ok(rule)
}

/// Parse a full Azure Policy definition from a JSON source.
///
/// Accepts two forms:
/// 1. **Wrapped**: `{ "properties": { "policyRule": ..., ... }, "id": ..., ... }`
/// 2. **Unwrapped**: `{ "displayName": ..., "policyRule": ..., ... }`
///
/// Returns a [`PolicyDefinition`] with typed fields for known properties
/// and a catch-all list of `extra` entries for everything else.
pub fn parse_policy_definition(source: &Source) -> Result<PolicyDefinition, ParseError> {
    parse_policy_definition_with_max_col(source, None)
}

/// Like [`parse_policy_definition`] but with an explicit column-width override.
///
/// When `max_col` is `None`, uses [`MAX_COL`] (the Azure Policy default).
pub fn parse_policy_definition_with_max_col(
    source: &Source,
    max_col: Option<NonZeroU32>,
) -> Result<PolicyDefinition, ParseError> {
    let mut parser = Parser::new_with_max_col(source, max_col.or(NonZeroU32::new(MAX_COL)))?;
    let defn = parser.parse_policy_definition()?;

    if parser.tok.0 != TokenKind::Eof {
        return Err(ParseError::UnexpectedToken {
            span: parser.tok.1.clone(),
            expected: "end of input",
        });
    }

    Ok(defn)
}

/// Parse a standalone constraint from a JSON source.
///
/// Useful for parsing just the `"if"` part of a policy rule.
pub fn parse_constraint(source: &Source) -> Result<Constraint, ParseError> {
    let mut parser = Parser::new(source)?;
    let constraint = parser.parse_constraint()?;

    if parser.tok.0 != TokenKind::Eof {
        return Err(ParseError::UnexpectedToken {
            span: parser.tok.1.clone(),
            expected: "end of input",
        });
    }

    Ok(constraint)
}

// ============================================================================
// Helper functions (used across submodules)
// ============================================================================

/// Check if a string is an ARM template expression (`[...]` but not `[[...`).
pub(super) fn is_template_expr(s: &str) -> bool {
    s.starts_with('[') && s.ends_with(']') && !s.starts_with("[[")
}

/// Checked `s[prefix_len..]`.
///
/// Callers guarantee bounds via a prior `starts_with` check on an ASCII
/// prefix whose byte-length equals `prefix_len`.
fn tail(s: &str, prefix_len: usize) -> &str {
    s.get(prefix_len..).unwrap_or_default()
}

/// Checked `s[prefix_len .. s.len() - suffix_len]`.
///
/// Callers guarantee bounds via prior `starts_with` / `ends_with` checks.
fn unwrap(s: &str, prefix_len: usize, suffix_len: usize) -> &str {
    let end = s.len().saturating_sub(suffix_len);
    s.get(prefix_len..end).unwrap_or_default()
}

fn strip_matching_outer_quotes(s: &str) -> Option<&str> {
    s.strip_prefix('\'')
        .and_then(|inner| inner.strip_suffix('\''))
        .or_else(|| {
            s.strip_prefix('"')
                .and_then(|inner| inner.strip_suffix('"'))
        })
}

/// Classify a field string into a [`FieldKind`].
///
/// In bracket tag notation (`tags[...]`), whitespace surrounding the tag
/// name is trimmed, using the same definition of whitespace as
/// [`str::trim`] (characters with the Unicode `White_Space` property).
/// Whitespace inside quotes is preserved, so `tags[ env ]` and
/// `tags[ 'env' ]` name `env` while `tags[' env ']` names ` env `.
/// Brackets that are empty or contain only whitespace are rejected.
pub(super) fn classify_field(
    text: &str,
    span: &crate::lexer::Span,
) -> Result<FieldKind, ParseError> {
    let lower = text.to_lowercase();
    match lower.as_str() {
        "type" => Ok(FieldKind::Type),
        "id" => Ok(FieldKind::Id),
        "kind" => Ok(FieldKind::Kind),
        "name" => Ok(FieldKind::Name),
        "location" => Ok(FieldKind::Location),
        "fullname" => Ok(FieldKind::FullName),
        "tags" => Ok(FieldKind::Tags),
        "identity.type" => Ok(FieldKind::IdentityType),
        _ if lower.starts_with("identity.") => Ok(FieldKind::IdentityField(
            tail(text, "identity.".len()).into(),
        )),
        "apiversion" => Ok(FieldKind::ApiVersion),
        _ if lower.starts_with("tags.") => Ok(FieldKind::Tag(tail(text, "tags.".len()).into())),
        // Tags[tagName] — bracket notation without quotes.
        // Tag name is everything between the first '[' and the LAST ']'.
        // e.g. Tags[Dept.Name]] → tag name "Dept.Name]"
        // Surrounding whitespace is trimmed; see the doc comment above.
        _ if lower.starts_with("tags[") && text.ends_with(']') => {
            let tag = unwrap(text, "tags[".len(), "]".len()).trim();
            let quoted = strip_matching_outer_quotes(tag);
            if quoted.unwrap_or(tag).is_empty() {
                return Err(ParseError::Custom {
                    span: span.clone(),
                    message: format!("empty tag name in field: {text:?}"),
                });
            }
            let kind = quoted.map_or_else(
                || {
                    if text.contains("[*]") {
                        FieldKind::Alias(text.into())
                    } else {
                        FieldKind::Tag(tag.into())
                    }
                },
                |quoted_tag| FieldKind::Tag(quoted_tag.into()),
            );
            Ok(kind)
        }
        _ if is_template_expr(text) => {
            let inner = unwrap(text, 1, 1);
            let expr = ExprParser::parse_from_brackets(inner, span).map_err(|e| {
                ParseError::ExprParse {
                    span: span.clone(),
                    message: e.to_string(),
                }
            })?;
            Ok(FieldKind::Expr(expr))
        }
        _ => Ok(FieldKind::Alias(text.into())),
    }
}

/// Try to parse a lowercase key as an operator kind.
pub(super) fn parse_operator_kind(key: &str) -> Option<OperatorKind> {
    match key {
        "contains" => Some(OperatorKind::Contains),
        "containskey" => Some(OperatorKind::ContainsKey),
        "equals" => Some(OperatorKind::Equals),
        "greater" => Some(OperatorKind::Greater),
        "greaterorequals" => Some(OperatorKind::GreaterOrEquals),
        "exists" => Some(OperatorKind::Exists),
        "in" => Some(OperatorKind::In),
        "less" => Some(OperatorKind::Less),
        "lessorequals" => Some(OperatorKind::LessOrEquals),
        "like" => Some(OperatorKind::Like),
        "match" => Some(OperatorKind::Match),
        "matchinsensitively" => Some(OperatorKind::MatchInsensitively),
        "notcontains" => Some(OperatorKind::NotContains),
        "notcontainskey" => Some(OperatorKind::NotContainsKey),
        "notequals" => Some(OperatorKind::NotEquals),
        "notin" => Some(OperatorKind::NotIn),
        "notlike" => Some(OperatorKind::NotLike),
        "notmatch" => Some(OperatorKind::NotMatch),
        "notmatchinsensitively" => Some(OperatorKind::NotMatchInsensitively),
        _ => None,
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;

    fn dummy_span() -> crate::lexer::Span {
        let source =
            crate::lexer::Source::from_contents("<test>".into(), alloc::string::String::new())
                .unwrap();
        crate::lexer::Span {
            source,
            line: 1,
            col: 1,
            start: 0,
            end: 0,
        }
    }

    #[test]
    fn test_is_template_expr() {
        assert!(is_template_expr("[field('type')]"));
        assert!(is_template_expr("[concat('a', 'b')]"));
        assert!(!is_template_expr("[[escaped]"));
        assert!(!is_template_expr("not-an-expr"));
        assert!(!is_template_expr("[no-end-bracket"));
    }

    #[test]
    fn test_classify_field_builtin_names() {
        let span = dummy_span();
        assert!(matches!(classify_field("type", &span), Ok(FieldKind::Type)));
        assert!(matches!(classify_field("Type", &span), Ok(FieldKind::Type)));
        assert!(matches!(classify_field("name", &span), Ok(FieldKind::Name)));
        assert!(matches!(
            classify_field("location", &span),
            Ok(FieldKind::Location)
        ));
    }

    #[test]
    fn test_classify_field_tag_bracket_quotes() {
        let span = dummy_span();

        for (field, expected) in [
            ("tags['123']", "123"),
            ("tags[\"123\"]", "123"),
            ("tags['environment']", "environment"),
            ("tags[\"environment\"]", "environment"),
            ("tags[unquoted]", "unquoted"),
            ("tags['embedded\"quote']", "embedded\"quote"),
            ("tags['dept[*]']", "dept[*]"),
            ("tags[\"dept[*]\"]", "dept[*]"),
        ] {
            match classify_field(field, &span) {
                Ok(FieldKind::Tag(actual)) => assert_eq!(actual, expected),
                other => panic!("expected Tag for {field:?}, got {other:?}"),
            }
        }
    }

    #[test]
    fn test_classify_field_empty_bracket_tag_name_is_rejected() {
        let span = dummy_span();

        for field in ["tags[]", "tags['']", "tags[\"\"]"] {
            assert!(
                matches!(classify_field(field, &span), Err(ParseError::Custom { .. })),
                "expected error for {field:?}"
            );
        }
    }

    #[test]
    fn test_classify_field_tag_bracket_preserves_unmatched_quotes() {
        let span = dummy_span();

        for (field, expected) in [("tags[\"123']", "\"123'"), ("tags['123\"]", "'123\"")] {
            match classify_field(field, &span) {
                Ok(FieldKind::Tag(actual)) => assert_eq!(actual, expected),
                other => panic!("expected Tag for {field:?}, got {other:?}"),
            }
        }
    }

    #[test]
    fn test_classify_field_unquoted_tag_wildcards_are_not_tag_names() {
        let span = dummy_span();

        for field in ["tags[*]", "tags[a[*]]", "tags[*][*]"] {
            match classify_field(field, &span) {
                Ok(FieldKind::Alias(actual)) => assert_eq!(actual, field),
                other => panic!("expected Alias for unquoted tag wildcard, got {other:?}"),
            }
        }
    }

    #[test]
    fn test_classify_field_tag_bracket_trims_outer_whitespace() {
        let span = dummy_span();

        for (field, expected) in [
            ("tags[ env ]", "env"),
            ("tags[  'env' ]", "env"),
            ("tags[ \"env\" ]", "env"),
            ("tags[\tenv\n]", "env"),
            ("tags[\u{3000}env\u{a0}]", "env"),
            ("tags[ my tag ]", "my tag"),
            ("tags[ ' env ' ]", " env "),
            ("tags[ \" a b \" ]", " a b "),
        ] {
            match classify_field(field, &span) {
                Ok(FieldKind::Tag(actual)) => assert_eq!(actual, expected, "field {field:?}"),
                other => panic!("expected Tag for {field:?}, got {other:?}"),
            }
        }
    }

    #[test]
    fn test_classify_field_tag_bracket_preserves_quoted_whitespace() {
        let span = dummy_span();

        for (field, expected) in [
            ("tags['my tag']", "my tag"),
            ("tags[' env ']", " env "),
            ("tags[\" a b \"]", " a b "),
            ("tags[' ']", " "),
            ("tags[\"\t\"]", "\t"),
        ] {
            match classify_field(field, &span) {
                Ok(FieldKind::Tag(actual)) => assert_eq!(actual, expected, "field {field:?}"),
                other => panic!("expected Tag for {field:?}, got {other:?}"),
            }
        }
    }

    #[test]
    fn test_classify_field_whitespace_only_bracket_tag_name_is_rejected() {
        let span = dummy_span();

        for field in [
            "tags[ ]",
            "tags[   ]",
            "tags[\t\n]",
            "tags[\u{3000}]",
            "tags[ '' ]",
            "tags[ \"\" ]",
        ] {
            assert!(
                matches!(classify_field(field, &span), Err(ParseError::Custom { .. })),
                "expected error for {field:?}"
            );
        }
    }

    #[test]
    fn test_classify_field_tag_bracket_padded_literals() {
        let span = dummy_span();

        // Only the exact text `[*]` is a wildcard; a padded star is a tag name.
        for (field, expected) in [
            ("tags[ * ]", "*"),
            ("tags[ ' ]", "'"),
            ("tags[ 'env\" ]", "'env\""),
            ("TAGS[ Env ]", "Env"),
        ] {
            match classify_field(field, &span) {
                Ok(FieldKind::Tag(actual)) => assert_eq!(actual, expected, "field {field:?}"),
                other => panic!("expected Tag for {field:?}, got {other:?}"),
            }
        }
        assert!(matches!(
            classify_field("tags[*]", &span),
            Ok(FieldKind::Alias(_))
        ));
    }

    #[test]
    fn test_classify_field_empty_tag_name_error_escapes_text() {
        let span = dummy_span();

        match classify_field("tags[\t\n]", &span) {
            Err(ParseError::Custom { message, .. }) => {
                assert!(message.contains("empty tag name"), "{message}");
                assert!(message.contains("\"tags[\\t\\n]\""), "{message}");
                assert!(
                    !message.contains('\t') && !message.contains('\n'),
                    "{message}"
                );
            }
            other => panic!("expected empty tag name error, got {other:?}"),
        }
    }

    #[test]
    fn test_classify_field_alias() {
        let span = dummy_span();
        match classify_field("Microsoft.Compute/virtualMachines/storageProfile", &span) {
            Ok(FieldKind::Alias(a)) => {
                assert_eq!(a, "Microsoft.Compute/virtualMachines/storageProfile");
            }
            other => panic!("expected Alias, got {:?}", other),
        }
    }

    #[test]
    fn test_classify_field_expression() {
        let span = dummy_span();
        match classify_field("[field('type')]", &span) {
            Ok(FieldKind::Expr(_)) => {}
            other => panic!("expected Expr, got {:?}", other),
        }
    }

    #[test]
    fn test_classify_field_double_bracket_not_expr() {
        // [[escaped] should NOT be parsed as an expression.
        let span = dummy_span();
        match classify_field("[[escaped]", &span) {
            Ok(FieldKind::Alias(a)) => assert_eq!(a, "[[escaped]"),
            other => panic!("expected Alias, got {:?}", other),
        }
    }
}