Skip to content

Commit

Permalink
Allow parameters and constants in top level rule (#347)
Browse files Browse the repository at this point in the history
The `top-level-iteration` is meant to detect rules that have iteration
without function body. Referencing parameters or constants should be
okay without a function body. This change allows that.
  • Loading branch information
zregvart committed Sep 25, 2023
1 parent 0098ff7 commit 938172a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
23 changes: 19 additions & 4 deletions bundle/regal/rules/bugs/top_level_iteration.rego
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,29 @@ report contains violation if {
rule.head.value.type == "ref"

last := regal.last(rule.head.value.value)
last.type == "var"

illegal_value_ref(last.value)
last.type == "var"
illegal_value_ref(last.value, rule)

violation := result.fail(rego.metadata.chain(), result.location(rule.head))
}

_rule_names := {ast.name(rule) | some rule in input.rules}

# regal ignore:external-reference
illegal_value_ref(value) if not value in _rule_names
_arg_names(rule) := {arg.value | some arg in rule.head.args}

_path(loc) := concat(".", {l.value | some l in loc})

illegal_value_ref(value, rule) if {
# regal ignore:external-reference
not value in _rule_names
not is_arg_or_input(value, rule)
}

is_arg_or_input(value, rule) if {
value in _arg_names(rule)
}

is_arg_or_input(value, rule) if {
startswith(_path(value), "input.")
}
10 changes: 10 additions & 0 deletions bundle/regal/rules/bugs/top_level_iteration_test.rego
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,13 @@ test_success_top_level_input_ref if {
r := rule.report with input as ast.with_future_keywords(`x := input.foo.bar[input.y]`)
r == set()
}

test_success_top_level_const if {
r := rule.report with input as ast.with_future_keywords(`x := input.foo.bar[4]`)
r == set()
}

test_success_top_level_param if {
r := rule.report with input as ast.with_future_keywords(`x(y) := input.foo.bar[y]`)
r == set()
}

0 comments on commit 938172a

Please sign in to comment.