【问题标题】:Encountering error running the test for regos saying "rego_unsafe_var_error"运行 regos 测试时遇到错误说“rego_unsafe_var_error”
【发布时间】:2021-02-02 06:20:15
【问题描述】:

为我的 rego 文件运行测试时出错。 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 设置值,那么我的测试会通过,但这样做不是编写测试的正确方法。

【问题讨论】:

  • 看起来您在allowed_for_triger 调用中同时使用了input.appIdinput.resource,但是当您使用with 模拟输入时,它们都不包括在内

标签: .net unit-testing open-policy-agent rego


【解决方案1】:

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
}

【讨论】:

    猜你喜欢
    • 2020-07-06
    • 1970-01-01
    • 2017-02-16
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    相关资源
    最近更新 更多