Skip to content

Commit

Permalink
Fix: prefer-some-in-iteration false positive iteration in fn args
Browse files Browse the repository at this point in the history
This fixes one of the errors reported in #528

Signed-off-by: Anders Eknert <anders@styra.com>
  • Loading branch information
anderseknert committed Mar 7, 2024
1 parent 3889772 commit fd766cd
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
18 changes: 18 additions & 0 deletions bundle/regal/rules/style/prefer_some_in_iteration.rego
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,24 @@ invalid_some_context(rule, path) if {
impossible_some(node)
}

# don't recommend `some .. in` if iteration occurs inside of a
# function call args list, like `startswith(input.foo[_], "foo")`
# this should honestly be a rule of its own, I think, but it's
# not _directly_ replaceable by `some .. in`, so we'll leave it
# be here
invalid_some_context(rule, path) if {
some p in all_paths(path)

node := object.get(rule, p, [])

node.terms[0].type == "ref"
node.terms[0].value[0].type == "var"
node.terms[0].value[0].value in ast.all_function_names # regal ignore:external-reference
}

# if previous node is of type call, also don't recommend `some .. in`
invalid_some_context(rule, path) if object.get(rule, array.slice(path, 0, count(path) - 2), {}).type == "call"

impossible_some(node) if node.type in {"array", "object", "set"}

impossible_some(node) if node.key
Expand Down
27 changes: 27 additions & 0 deletions bundle/regal/rules/style/prefer_some_in_iteration_test.rego
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package regal.rules.style["prefer-some-in-iteration_test"]
import rego.v1

import data.regal.ast
import data.regal.capabilities
import data.regal.config
import data.regal.rules.style["prefer-some-in-iteration"] as rule

Expand Down Expand Up @@ -233,6 +234,32 @@ test_success_allow_if_contains_check_equal if {
r == set()
}

test_success_iteration_in_args if {
policy := ast.with_rego_v1(`no_violation if {
startswith(input.foo[_], "f")
}`)

r := rule.report with config.for_rule as {
"level": "error",
"ignore-nesting-level": 5,
}
with input as policy
with data.internal.combined_config as {"capabilities": capabilities.provided}
r == set()
}

test_success_iteration_in_args_call_in_comprehension_head if {
policy := ast.with_rego_v1(`r := [f(obj[k], v) | some k, v in p]`)

r := rule.report with config.for_rule as {
"level": "error",
"ignore-nesting-level": 5,
}
with input as policy
with data.internal.combined_config as {"capabilities": capabilities.provided}
r == set()
}

allow_nesting(i) := {
"level": "error",
"ignore-nesting-level": i,
Expand Down

0 comments on commit fd766cd

Please sign in to comment.