2

Getting error while running test for my rego files. Rego file :

package authz
import abc.def

default can_tigger = false

can_tigger = true{
    needs_one_of := ["trigger_access_allowed"]
    access.allowed_for_triger(input.appId, input.user, needs_one_of[_],input.resource)
}

Rego test file :

package authz

test_can_trigger_command_when_projectId_is_valid {
    can_tigger
    with input as {"projectId": "5fdf4ab1-acf6-4d5f-9604-79bda49d9431", "user": {"sub": "testUser"}}    
}

If I set the value in test file for can_tigger:= true/false then my test would pass, but doing is not a proper way to write tests.

Devoops
  • 2,018
  • 8
  • 21
Sunny Jha
  • 21
  • 3
  • Looks like you are using both `input.appId` and `input.resource` in your `allowed_for_triger` call, yet none of them are included when you mock the input using `with` – Devoops Feb 08 '21 at 11:32

1 Answers1

1

The OPA Gatekeeper Library is a great way to learn how to write tests for Rego.

From the k8sallowedrepos test:

test_input_allowed_container {
    input := { "review": input_review(input_container_allowed), "parameters": {"repos": ["allowed"]}}
    results := violation with input as input
    count(results) == 0
}
...
input_init_review(containers) = output {
    output = {
      "object": {
        "metadata": {
            "name": "nginx"
        },
        "spec": {
            "initContainers": containers,
        }
      }
     }
}

input_container_allowed = [
{
    "name": "nginx",
    "image": "allowed/nginx",
}]

Note that in the test, violation with input as input is a Rego idiom that passes the local "input" variable to the violation defined here using as "input". It's much cleaner than doing it inline.

In your case, you could rewrite your test as:

test_can_trigger_command_when_projectId_is_valid {
    input := {"projectId": "5fdf4ab1-acf6-4d5f-9604-79bda49d9431", "user": {"sub": "testUser"}}
    results := violation with input as input
    count(results) == 0
}
Will Beason
  • 3,417
  • 2
  • 28
  • 46