OPA(Rego)作为Go库:如何应用外部数据?

huangapple go评论116阅读模式
英文:

OPA (Rego) as Go lib: How to apply external data?

问题

我按照https://www.openpolicyagent.org/docs/latest/#5-try-opa-as-a-go-library的示例进行了操作。重要的代码片段:

  1. r := rego.New(
  2. rego.Query("x = data.example.allow"),
  3. rego.Load([]string{"./example.rego"}, nil)
  4. ...
  5. rs, err := query.Eval(ctx, rego.EvalInput(input))
  6. ...

我该如何添加外部数据(data.json),以便在rego策略中使用,例如data.wantedName来访问它?

我尝试阅读go文档和示例,但没有找到有用的信息。

谢谢!

英文:

I followed the example of https://www.openpolicyagent.org/docs/latest/#5-try-opa-as-a-go-library. Important code snippets:

  1. r := rego.New(
  2. rego.Query("x = data.example.allow"),
  3. rego.Load([]string{"./example.rego"}, nil)
  4. ...
  5. rs, err := query.Eval(ctx, rego.EvalInput(input))
  6. ...

How can I add external data (data.json) such that I can use, e.g., data.wantedName in the rego policy to access it?

I tried to read through the go doc and the examples but I couldn't find any helpful information.

Thanks!

答案1

得分: 6

你看过rego.Store()的文档和这个示例吗?

对于简单的情况,可以按照以下方式进行操作:

  1. data := `{
  2. "example": {
  3. "users": [
  4. {
  5. "name": "alice",
  6. "likes": ["dogs", "clouds"]
  7. },
  8. {
  9. "name": "bob",
  10. "likes": ["pizza", "cats"]
  11. }
  12. ]
  13. }
  14. }`
  15. var json map[string]interface{}
  16. err := util.UnmarshalJSON([]byte(data), &json)
  17. if err != nil {
  18. // 处理错误。
  19. }
  20. store := inmem.NewFromObject(json)
  21. // 创建返回值的新查询
  22. rego := rego.New(
  23. rego.Query("data.example.users[0].likes"),
  24. rego.Store(store))

如果需要更复杂的用法,你可以自己实现存储方式,但这将会更加复杂。如果可以通过将inmem.NewFromObject()存储传递给rego.New()来解决问题,建议首先尝试这种方法。

英文:

Have you seen the docs on rego.Store() and this example?

Something along these lines should do the trick for simple cases:

  1. data := `{
  2. "example": {
  3. "users": [
  4. {
  5. "name": "alice",
  6. "likes": ["dogs", "clouds"]
  7. },
  8. {
  9. "name": "bob",
  10. "likes": ["pizza", "cats"]
  11. }
  12. ]
  13. }
  14. }`
  15. var json map[string]interface{}
  16. err := util.UnmarshalJSON([]byte(data), &json)
  17. if err != nil {
  18. // Handle error.
  19. }
  20. store := inmem.NewFromObject(json)
  21. // Create new query that returns the value
  22. rego := rego.New(
  23. rego.Query("data.example.users[0].likes"),
  24. rego.Store(store))

You could implement your own storage for more intricate uses, but that's going to be a lot more involved. If you get by with feeding inmem.NewFromObject() stores into rego.New(), you should try that first.

huangapple
  • 本文由 发表于 2021年10月8日 15:18:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/69491963.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定