go-opa-validate
go-opa-validate is an open-source lib that evaluates OPA (open policy agent) policy against JSON or YAML data.
Installation
go install github.com/chen-keinan/go-opa-validate
Usage
(support json and yaml formats)
json data example: data.json
{
"kind": "AdmissionReview",
"request": {
"kind": {
"kind": "Pod",
"version": "v1"
},
"object": {
"metadata": {
"name": "myapp"
},
"spec": {
"containers": [
{
"image": "hooli.com/mysql",
"name": "mysql-backend"
}
]
}
}
}
}
OPA policy example : denyPolicy
package example
default deny = false
deny {
some i
input.request.kind.kind == "Pod"
image := input.request.object.spec.containers[i].image
not startswith(image, "hooli.com/")
}
Full code example
package main
import (
"fmt"
"github.com/chen-keinan/go-opa-validate/validator"
"io/ioutil"
"os"
)
func main() {
data, err := ioutil.ReadFile("./example/data.json")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
policy, err := ioutil.ReadFile("./example/denyPolicy")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
validateResult, err := validator.NewPolicyEval().EvaluatePolicy([]string{"deny"}, string(policy), string(data))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if len(validateResult) > 0 {
fmt.Println(fmt.Sprintf("eval result for property %v with value %v",validateResult[0].ExpressionValue[0].Text ,validateResult[0].ExpressionValue[0].Value))
}
}
Contribution
code contribution is welcome ! contribution with passing tests and linter is more than welcome :)