【问题标题】:How to create OPA rego policy for a whitelist?如何为白名单创建 OPA rego 策略?
【发布时间】:2022-01-10 04:41:04
【问题描述】:

我正在尝试在 OPA rego 中实施白名单政策。该策略的目的是阻止除已列入白名单的属性之外的所有属性。但是,我无法让它工作。

这是我的 rego 政策:

package play

whitelisted_attributes =
{
    "foo.bar",
    "hello.from.*.world"
}

default allow = false
default not_in_whitelist = true

not_in_whitelist {
    whitelisted := {attr | attr := input.attributes[_]; glob.match(whitelisted_attributes[_], ["."], attr)}
    count(whitelisted) == 0
}

allow {
    not not_in_whitelist
}

这是我的输入:

{
    "attributes": [
        "foo.bar"
    ]
}

这是根据 Rego Playground 的输出:

{
    "allow": false,
    "not_in_whitelist": true,
    "whitelisted_attributes": [
        "foo.bar",
        "hello.from.*.world"
    ]
}

如您所见,“允许”应该为真,因为在白名单中找到了输入。此外,“not_in_whitelist”应该为 false,因为输入属性在白名单中。

【问题讨论】:

    标签: policy opa open-policy-agent rego


    【解决方案1】:

    这里发生的情况是,由于其中一个元素 is 在白名单中,not_in_whitelist 规则将评估为 undefined(因为这是一条规则不满足所有条件的计算结果为)。

    由于not_in_whitelist 评估为未定义,规则将被分配true默认值:

    default not_in_whitelist = true
    

    然后,允许规则将在 not 检查中反转它,使规则失败(因为 not true == false):

    allow {
        not not_in_whitelist
    }
    

    我建议简单地删除 not_in_whitelist 的默认分配。

    【讨论】:

      【解决方案2】:

      感谢@Devoops 的提示。我回到了 Rego Playground,经过多次尝试和错误,我想出了一个可行的政策。我将其发布在此处以供有类似需求的其他人使用。

      package play
      
      default allow = false
      default in_whitelist = false
      
      whitelist =
      {
          "foo.bar",
          "hello.from.*.world"
      }
      
      num_attributes := count(input.attributes)
      
      in_whitelist {
          glob.match(whitelist[_], ["."], input.attributes[_])
      }
      
      not_in_whitelist = result {
          num_attributes == 1
          result := (in_whitelist == false)
      }
      
      not_in_whitelist = result {
          num_attributes > 1
          whitelisted := {attr | attr := input.attributes[_]; glob.match(whitelist[_], ["."], attr)}
          result := (count(whitelisted) < num_attributes)
      }
      
      allow {
          not not_in_whitelist
      }
      
      deny[msg] {
          not_in_whitelist
          msg = sprintf("You are only allowed to modify the following whitelisted attributes: %v", [whitelist])
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多