How Do I Test Policies?

OPA gives you a high-level declarative language (Rego) to author fine-grained policies that codify important requirements in your system.

To help you verify the correctness of your policies, OPA also gives you a framework that you can use to write tests for your policies. By writing tests for your policies you can speed up the development process of new rules and reduce the amount of time it takes to modify rules as requirements evolve.

Getting Started

Let’s use an example to get started. The file below implements a simple policy that allows new users to be created and users to access their own profile.

example.rego:

  1. package authz
  2. allow {
  3. input.path == ["users"]
  4. input.method == "POST"
  5. }
  6. allow {
  7. some profile_id
  8. input.path = ["users", profile_id]
  9. input.method == "GET"
  10. profile_id == input.user_id
  11. }

To test this policy, we will create a separate Rego file that contains test cases.

example_test.rego:

  1. package authz
  2. test_post_allowed {
  3. allow with input as {"path": ["users"], "method": "POST"}
  4. }
  5. test_get_anonymous_denied {
  6. not allow with input as {"path": ["users"], "method": "GET"}
  7. }
  8. test_get_user_allowed {
  9. allow with input as {"path": ["users", "bob"], "method": "GET", "user_id": "bob"}
  10. }
  11. test_get_another_user_denied {
  12. not allow with input as {"path": ["users", "bob"], "method": "GET", "user_id": "alice"}
  13. }

Both of these files are saved in the same directory.

  1. $ ls
  2. example.rego example_test.rego

To exercise the policy, run the opa test command in the directory containing the files.

  1. $ opa test . -v
  2. data.authz.test_post_allowed: PASS (1.417µs)
  3. data.authz.test_get_anonymous_denied: PASS (426ns)
  4. data.authz.test_get_user_allowed: PASS (367ns)
  5. data.authz.test_get_another_user_denied: PASS (320ns)
  6. --------------------------------------------------------------------------------
  7. PASS: 4/4

The opa test output indicates that all of the tests passed.

Try exercising the tests a bit more by removing the first rule in example.rego.

  1. $ opa test . -v
  2. data.authz.test_post_allowed: FAIL (607ns)
  3. data.authz.test_get_anonymous_denied: PASS (288ns)
  4. data.authz.test_get_user_allowed: PASS (346ns)
  5. data.authz.test_get_another_user_denied: PASS (365ns)
  6. --------------------------------------------------------------------------------
  7. PASS: 3/4
  8. FAIL: 1/4

Test Format

Tests are expressed as standard Rego rules with a convention that the rule name is prefixed with test_.

  1. package mypackage
  2. test_some_descriptive_name {
  3. # test logic
  4. }

Test Discovery

The opa test subcommand runs all of the tests (i.e., rules prefixed with test_) found in Rego files passed on the command line. If directories are passed as command line arguments, opa test will load their file contents recursively.

Test Results

If the test rule is undefined or generates a non-true value the test result is reported as FAIL. If the test encounters a runtime error (e.g., a divide by zero condition) the test result is marked as an ERROR. Otherwise, the test result is marked as PASS.

pass_fail_error_test.rego:

  1. package example
  2. # This test will pass.
  3. test_ok {
  4. true
  5. }
  6. # This test will fail.
  7. test_failure {
  8. 1 == 2
  9. }
  10. # This test will error.
  11. test_error {
  12. 1 / 0
  13. }

By default, opa test reports the number of tests executed and displays all of the tests that failed or errored.

  1. $ opa test pass_fail_error_test.rego
  2. data.example.test_failure: FAIL (253ns)
  3. data.example.test_error: ERROR (289ns)
  4. pass_fail_error_test.rego:15: eval_builtin_error: div: divide by zero
  5. --------------------------------------------------------------------------------
  6. PASS: 1/3
  7. FAIL: 1/3
  8. ERROR: 1/3

By default, OPA prints the test results in a human-readable format. If you need to consume the test results programmatically, use the JSON output format.

  1. $ opa test --format=json pass_fail_error_test.rego
  1. [
  2. {
  3. "location": {
  4. "file": "pass_fail_error_test.rego",
  5. "row": 4,
  6. "col": 1
  7. },
  8. "package": "data.example",
  9. "name": "test_ok",
  10. "duration": 618515
  11. },
  12. {
  13. "location": {
  14. "file": "pass_fail_error_test.rego",
  15. "row": 9,
  16. "col": 1
  17. },
  18. "package": "data.example",
  19. "name": "test_failure",
  20. "fail": true,
  21. "duration": 322177
  22. },
  23. {
  24. "location": {
  25. "file": "pass_fail_error_test.rego",
  26. "row": 14,
  27. "col": 1
  28. },
  29. "package": "data.example",
  30. "name": "test_error",
  31. "error": {
  32. "code": "eval_internal_error",
  33. "message": "div: divide by zero",
  34. "location": {
  35. "file": "pass_fail_error_test.rego",
  36. "row": 15,
  37. "col": 5
  38. }
  39. },
  40. "duration": 345148
  41. }
  42. ]

Data Mocking

OPA’s with keyword can be used to replace the data document. Both base and virtual documents can be replaced. Below is a simple policy that depends on the data document.

authz.rego:

  1. package authz
  2. allow {
  3. x := data.policies[_]
  4. x.name == "test_policy"
  5. matches_role(input.role)
  6. }
  7. matches_role(my_role) {
  8. data.roles[my_role][_] == input.user
  9. }

Below is the Rego file to test the above policy.

authz_test.rego:

  1. package authz
  2. policies = [{"name": "test_policy"}]
  3. roles = {"admin": ["alice"]}
  4. test_allow_with_data {
  5. allow with input as {"user": "alice", "role": "admin"} with data.policies as policies with data.roles as roles
  6. }

To exercise the policy, run the opa test command.

  1. $ opa test -v authz.rego authz_test.rego
  2. data.authz.test_allow_with_data: PASS (697ns)
  3. --------------------------------------------------------------------------------
  4. PASS: 1/1

Below is an example to replace a rule without arguments.

authz.rego:

  1. package authz
  2. allow1 {
  3. allow2
  4. }
  5. allow2 {
  6. 2 == 1
  7. }

authz_test.rego:

  1. package authz
  2. test_replace_rule {
  3. allow1 with allow2 as true
  4. }
  1. $ opa test -v authz.rego authz_test.rego
  2. data.authz.test_replace_rule: PASS (328ns)
  3. --------------------------------------------------------------------------------
  4. PASS: 1/1

Functions with arguments cannot be replaced by the with keyword. For example, in the below policy the function cannot_replace cannot be replaced.

authz.rego:

  1. package authz
  2. invalid_replace {
  3. cannot_replace(input.label)
  4. }
  5. cannot_replace(label) {
  6. label == "test_label"
  7. }

authz_test.rego:

  1. package authz
  2. test_invalid_replace {
  3. invalid_replace with input as {"label": "test_label"} with cannot_replace as true
  4. }
  1. $ opa test -v authz.rego authz_test.rego
  2. 1 error occurred: authz_test.rego:4: rego_compile_error: with keyword cannot replace functions

Coverage

In addition to reporting pass, fail, and error results for tests, opa test can also report coverage for the policies under test.

The coverage report includes all of the lines evaluated and not evaluated in the Rego files provided on the command line. When a line is not covered it indicates one of two things:

  • If the line refers to the head of a rule, the body of the rule was never true.
  • If the line refers to an expression in a rule, the expression was never evaluated.

If we run the coverage report on the original example.rego file without test_get_user_allowed from example_test.rego the report will indicate that line 8 is not covered.

  1. opa test --coverage --format=json example.rego example_test.rego
  1. {
  2. "files": {
  3. "example.rego": {
  4. "covered": [
  5. {
  6. "start": {
  7. "row": 3
  8. },
  9. "end": {
  10. "row": 5
  11. }
  12. },
  13. {
  14. "start": {
  15. "row": 9
  16. },
  17. "end": {
  18. "row": 11
  19. }
  20. }
  21. ],
  22. "not_covered": [
  23. {
  24. "start": {
  25. "row": 8
  26. },
  27. "end": {
  28. "row": 8
  29. }
  30. }
  31. ]
  32. },
  33. "example_test.rego": {
  34. "covered": [
  35. {
  36. "start": {
  37. "row": 3
  38. },
  39. "end": {
  40. "row": 4
  41. }
  42. },
  43. {
  44. "start": {
  45. "row": 7
  46. },
  47. "end": {
  48. "row": 8
  49. }
  50. },
  51. {
  52. "start": {
  53. "row": 11
  54. },
  55. "end": {
  56. "row": 12
  57. }
  58. }
  59. ]
  60. }
  61. }
  62. }

Profiling

In addition to testing and coverage reporting, you can also profile your policies using opa eval. The profiler is useful if you need to understand why policy evaluation is slow.

The opa eval command provides the following profiler options:

OptionDetailDefault
—profileEnables expression profiling and outputs profiler results.off
—profile-sortCriteria to sort the expression profiling results. This options implies —profile.total_time_ns => num_eval => num_redo => file => line
—profile-limitDesired number of profiling results sorted on the given criteria. This options implies —profile.10

Sort criteria for the profile results

  • total_time_ns - Results are displayed is decreasing order of expression evaluation time
  • num_eval - Results are displayed is decreasing order of number of times an expression is evaluated
  • num_redo - Results are displayed is decreasing order of number of times an expression is re-evaluated(redo)
  • file - Results are sorted in reverse alphabetical order based on the rego source filename
  • line - Results are displayed is decreasing order of expression line number in the source file

When the sort criteria is not provided total_time_ns has the highest priority while line has the lowest.

Example Policy

The different profiling examples shown later on this page use the below sample policy.

  1. package rbac
  2. # Example input request
  3. input = {
  4. "subject": "bob",
  5. "resource": "foo123",
  6. "action": "write",
  7. }
  8. # Example RBAC configuration.
  9. bindings = [
  10. {
  11. "user": "alice",
  12. "roles": ["dev", "test"],
  13. },
  14. {
  15. "user": "bob",
  16. "roles": ["test"],
  17. },
  18. ]
  19. roles = [
  20. {
  21. "name": "dev",
  22. "permissions": [
  23. {"resource": "foo123", "action": "write"},
  24. {"resource": "foo123", "action": "read"},
  25. ],
  26. },
  27. {
  28. "name": "test",
  29. "permissions": [{"resource": "foo123", "action": "read"}],
  30. },
  31. ]
  32. # Example RBAC policy implementation.
  33. default allow = false
  34. allow {
  35. some role_name
  36. user_has_role[role_name]
  37. role_has_permission[role_name]
  38. }
  39. user_has_role[role_name] {
  40. binding := bindings[_]
  41. binding.user == input.subject
  42. role_name := binding.roles[_]
  43. }
  44. role_has_permission[role_name] {
  45. role := roles[_]
  46. role_name := role.name
  47. perm := role.permissions[_]
  48. perm.resource == input.resource
  49. perm.action == input.action
  50. }

Example: Display ALL profile results with default ordering criteria

  1. opa eval --data rbac.rego --profile --format=pretty 'data.rbac.allow'

Sample Output

  1. false
  2. +----------+----------+----------+-----------------+
  3. | TIME | NUM EVAL | NUM REDO | LOCATION |
  4. +----------+----------+----------+-----------------+
  5. | 47.148µs | 1 | 1 | data.rbac.allow |
  6. | 28.965µs | 1 | 1 | rbac.rego:11 |
  7. | 24.384µs | 1 | 1 | rbac.rego:41 |
  8. | 23.064µs | 2 | 1 | rbac.rego:47 |
  9. | 15.525µs | 1 | 1 | rbac.rego:38 |
  10. | 14.137µs | 1 | 2 | rbac.rego:46 |
  11. | 13.927µs | 1 | 0 | rbac.rego:42 |
  12. | 13.568µs | 1 | 1 | rbac.rego:55 |
  13. | 12.982µs | 1 | 0 | rbac.rego:56 |
  14. | 12.763µs | 1 | 2 | rbac.rego:52 |
  15. +----------+----------+----------+-----------------+
  16. +------------------------------+----------+
  17. | METRIC | VALUE |
  18. +------------------------------+----------+
  19. | timer_rego_module_compile_ns | 1871613 |
  20. | timer_rego_query_compile_ns | 82290 |
  21. | timer_rego_query_eval_ns | 257952 |
  22. | timer_rego_query_parse_ns | 12337169 |
  23. +------------------------------+----------+

As seen from the above table, all results are displayed. The profile results are sorted on the default sort criteria.

Example: Display top 5 profile results

  1. opa eval --data rbac.rego --profile-limit 5 --format=pretty 'data.rbac.allow'

Sample Output

  1. +----------+----------+----------+-----------------+
  2. | TIME | NUM EVAL | NUM REDO | LOCATION |
  3. +----------+----------+----------+-----------------+
  4. | 46.329µs | 1 | 1 | data.rbac.allow |
  5. | 26.656µs | 1 | 1 | rbac.rego:11 |
  6. | 24.206µs | 2 | 1 | rbac.rego:47 |
  7. | 23.235µs | 1 | 1 | rbac.rego:41 |
  8. | 18.242µs | 1 | 1 | rbac.rego:38 |
  9. +----------+----------+----------+-----------------+

The profile results are sorted on the default sort criteria. Also --profile option is implied and does not need to be provided.

Example: Display top 5 profile results based on the number of times an expression is evaluated

  1. opa eval --data rbac.rego --profile-limit 5 --profile-sort num_eval --format=pretty 'data.rbac.allow'

Sample Profile Output

  1. +----------+----------+----------+-----------------+
  2. | TIME | NUM EVAL | NUM REDO | LOCATION |
  3. +----------+----------+----------+-----------------+
  4. | 26.675µs | 2 | 1 | rbac.rego:47 |
  5. | 9.274µs | 2 | 1 | rbac.rego:53 |
  6. | 43.356µs | 1 | 1 | data.rbac.allow |
  7. | 22.467µs | 1 | 1 | rbac.rego:41 |
  8. | 22.425µs | 1 | 1 | rbac.rego:11 |
  9. +----------+----------+----------+-----------------+

As seen from the above table, the results are arranged first in decreasing order of number of evaluations and if two expressions have been evaluated the same number of times, the default criteria is used since no other sort criteria is provided. In this case, total_time_ns => num_redo => file => line. Also --profile option is implied and does not need to be provided.

Example: Display top 5 profile results based on the number of times an expression is evaluated and number of times an expression is re-evaluated

  1. opa eval --data rbac.rego --profile-limit 5 --profile-sort num_eval,num_redo --format=pretty 'data.rbac.allow'

Sample Profile Output

  1. +----------+----------+----------+-----------------+
  2. | TIME | NUM EVAL | NUM REDO | LOCATION |
  3. +----------+----------+----------+-----------------+
  4. | 22.892µs | 2 | 1 | rbac.rego:47 |
  5. | 8.831µs | 2 | 1 | rbac.rego:53 |
  6. | 13.767µs | 1 | 2 | rbac.rego:46 |
  7. | 10.78µs | 1 | 2 | rbac.rego:52 |
  8. | 42.338µs | 1 | 1 | data.rbac.allow |
  9. +----------+----------+----------+-----------------+

As seen from the above table, result are first arranged based on number of evaluations, then number of re-evaluations and finally the default criteria is used. In this case, total_time_ns => file => line. The --profile-sort options accepts repeated or comma-separated values for the criteria. The order of the criteria on the command line determine their priority.

Another way to get the same output as above would be the following:

  1. opa eval --data rbac.rego --profile-limit 5 --profile-sort num_eval --profile-sort num_redo --format=pretty 'data.rbac.allow'