-
Notifications
You must be signed in to change notification settings - Fork 35
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Rule: sprintf-arguments-mismatch
#1011
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
# METADATA | ||
# description: Mismatch in `sprintf` arguments count | ||
package regal.rules.bugs["sprintf-arguments-mismatch"] | ||
|
||
import rego.v1 | ||
|
||
import data.regal.ast | ||
import data.regal.config | ||
import data.regal.result | ||
|
||
# METADATA | ||
# description: Missing capability for built-in `sprintf` | ||
# custom: | ||
# severity: none | ||
notices contains result.notice(rego.metadata.chain()) if not "sprintf" in object.keys(config.capabilities.builtins) | ||
|
||
# METADATA | ||
# description: | | ||
# Count the number of distinct arguments ("verbs", denoted by %) in the string argument, | ||
# compare it to the number of items in the array (if known), and flag when the numbers | ||
# don't match | ||
report contains violation if { | ||
some fn | ||
ast.function_calls[_][fn].name == "sprintf" | ||
|
||
fn.args[1].type == "array" # can only check static arrays, not vars | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 😱 that's a possibility... |
||
|
||
values_in_arr := count(fn.args[1].value) | ||
str_no_escape := replace(fn.args[0].value, "%%", "") # don't include '%%' as it's used to "escape" % | ||
values_in_str := strings.count(str_no_escape, "%") - _repeated_explicit_argument_indexes(str_no_escape) | ||
|
||
values_in_str != values_in_arr | ||
|
||
violation := result.fail(rego.metadata.chain(), result.ranged_location_between(fn.args[0], regal.last(fn.args))) | ||
} | ||
|
||
default _repeated_explicit_argument_indexes(_) := 0 | ||
|
||
# see: https://pkg.go.dev/fmt#hdr-Explicit_argument_indexes | ||
# each distinct explicit argument index should only contribute one value to the | ||
# values array. this calculates the number to subtract from the total expected | ||
# number of values based on the number of eai's occurring more than once | ||
_repeated_explicit_argument_indexes(str) := sum([n | | ||
some eai in _unique_explicit_arguments(str) | ||
n := strings.count(str, eai) - 1 | ||
]) | ||
|
||
_unique_explicit_arguments(str) := {eai | some eai in regex.find_n(`%\[\d\]`, str, -1)} |
89 changes: 89 additions & 0 deletions
89
bundle/regal/rules/bugs/sprintf_argument_mismatch_test.rego
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
package regal.rules.bugs["sprintf-arguments-mismatch_test"] | ||
|
||
import rego.v1 | ||
|
||
import data.regal.ast | ||
import data.regal.config | ||
|
||
import data.regal.rules.bugs["sprintf-arguments-mismatch"] as rule | ||
|
||
test_fail_too_many_values_in_array if { | ||
r := rule.report with input as ast.with_rego_v1(`x := sprintf("%s", [1, 2])`) | ||
r == {{ | ||
"category": "bugs", | ||
"description": "Mismatch in `sprintf` arguments count", | ||
"level": "error", | ||
"location": { | ||
"row": 5, | ||
"col": 14, | ||
"end": {"col": 26, "row": 5}, | ||
"file": "policy.rego", | ||
"text": "x := sprintf(\"%s\", [1, 2])", | ||
}, | ||
"related_resources": [{ | ||
"description": "documentation", | ||
"ref": config.docs.resolve_url("$baseUrl/$category/sprintf-arguments-mismatch", "bugs"), | ||
}], | ||
"title": "sprintf-arguments-mismatch", | ||
}} | ||
} | ||
|
||
test_fail_too_few_values_in_array if { | ||
r := rule.report with input as ast.with_rego_v1(`x := sprintf("%s%v", [1])`) | ||
r == {{ | ||
"category": "bugs", | ||
"description": "Mismatch in `sprintf` arguments count", | ||
"level": "error", | ||
"location": { | ||
"row": 5, | ||
"col": 14, | ||
"end": {"col": 25, "row": 5}, | ||
"file": "policy.rego", | ||
"text": `x := sprintf("%s%v", [1])`, | ||
}, | ||
"related_resources": [{ | ||
"description": "documentation", | ||
"ref": config.docs.resolve_url("$baseUrl/$category/sprintf-arguments-mismatch", "bugs"), | ||
}], | ||
"title": "sprintf-arguments-mismatch", | ||
}} | ||
} | ||
|
||
test_success_same_number_of_values if { | ||
r := rule.report with input as ast.with_rego_v1(`x := sprintf("%s%d", [1, 2])`) | ||
r == set() | ||
} | ||
|
||
test_fail_different_number_of_values_with_explicit_index if { | ||
r := rule.report with input as ast.with_rego_v1(`x := sprintf("%[1]s %[1]s %[2]d", [1, 2, 3])`) | ||
r == {{ | ||
"category": "bugs", | ||
"description": "Mismatch in `sprintf` arguments count", | ||
"level": "error", | ||
"location": { | ||
"row": 5, | ||
"col": 14, | ||
"end": { | ||
"col": 44, | ||
"row": 5, | ||
}, | ||
"file": "policy.rego", | ||
"text": "x := sprintf(\"%[1]s %[1]s %[2]d\", [1, 2, 3])", | ||
}, | ||
"related_resources": [{ | ||
"description": "documentation", | ||
"ref": config.docs.resolve_url("$baseUrl/$category/sprintf-arguments-mismatch", "bugs"), | ||
}], | ||
"title": "sprintf-arguments-mismatch", | ||
}} | ||
} | ||
|
||
test_success_same_number_of_values_with_explicit_index if { | ||
r := rule.report with input as ast.with_rego_v1(`x := sprintf("%[1]s %[1]s %[2]d", [1, 2])`) | ||
r == set() | ||
} | ||
|
||
test_success_escaped_verbs_are_ignored if { | ||
r := rule.report with input as ast.with_rego_v1(`x := sprintf("%d %% %% %s", [1, "f"])`) | ||
r == set() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
# sprintf-arguments-mismatch | ||
|
||
**Summary**: Mismatch in `sprintf` arguments count | ||
|
||
**Category**: Bugs | ||
|
||
**Avoid** | ||
```rego | ||
package policy | ||
|
||
import rego.v1 | ||
|
||
max_issues := 1 | ||
|
||
report contains warning if { | ||
count(issues) > max_issues | ||
|
||
# two placeholders found in the string, but only one value in the array | ||
warning := sprintf("number of issues (%d) must not be higher than %d", [count(issues)]) | ||
} | ||
``` | ||
|
||
**Prefer** | ||
```rego | ||
package policy | ||
|
||
import rego.v1 | ||
|
||
max_issues := 1 | ||
|
||
report contains warning if { | ||
count(issues) > max_issues | ||
|
||
# two placeholders found in the string, and two values in the array | ||
warning := sprintf("number of issues (%d) must not be higher than %d", [count(issues), max_issues]) | ||
} | ||
``` | ||
|
||
## Rationale | ||
|
||
While the built-in `sprintf` function itself reports argument mismatches, it'll do so by returning a string containing | ||
the error message rather than actually failing. | ||
|
||
```shell | ||
> opa eval -f pretty 'sprintf("%v %d", [1])' | ||
"1 %!d(MISSING)" | ||
``` | ||
|
||
While this is normally caught in development and testing, having this issue reported at "compile time", which ideally | ||
is [directly in your editor](https://docs.styra.com/regal/language-server) as you work on your policy. This means less | ||
time spent chasing down issues later, and a happier development experience. | ||
|
||
## Configuration Options | ||
|
||
This linter rule provides the following configuration options: | ||
|
||
```yaml | ||
rules: | ||
bugs: | ||
sprintf-arguments-mismatch: | ||
# one of "error", "warning", "ignore" | ||
level: error | ||
``` | ||
|
||
## Related Resources | ||
|
||
- OPA Docs: [Built-in Functions: `sprintf`](https://www.openpolicyagent.org/docs/latest/policy-reference/#builtin-strings-sprintf) | ||
|
||
## Community | ||
|
||
If you think you've found a problem with this rule or its documentation, would like to suggest improvements, new rules, | ||
or just talk about Regal in general, please join us in the `#regal` channel in the Styra Community | ||
[Slack](https://communityinviter.com/apps/styracommunity/signup)! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks expensive. Have you ever tried using an reverse-index here? Like "all locations where function
sprintf
is used"There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we've mostly paid the cost at this point, as
ast.function_calls
essentially filtersast.found.refs
keeping only function calls, and then providing them in compact format nicer to work with.But yeah,
ast.found.refs
is a beast, and as I'm sure you remember, I tried to collect more types in that traversal, and things... broke :P