运行 regos 测试时遇到错误说“rego_unsafe_var_error”

问题描述

对我的 rego 文件运行测试时出错。 注册文件

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 测试文件

package authz

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

如果我在测试文件中为 can_tigger:= true/false 设置值,那么我的测试将通过,但这样做不是编写测试的正确方法

解决方法

OPA Gatekeeper Library 是学习如何为 Rego 编写测试的好方法。

来自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",}]

请注意,在测试中,violation with input as input 是一个 Rego 习语,它将本地“输入”变量传递给 violation defined here 用作“输入”。它比内联要干净得多。

在您的情况下,您可以将测试重写为:

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
}