1

I am trying to validate some policies using the /opa/rego package.

The policies are evaluated as expected in this script. But, I also want to count the number of rules and the rule names evaluated as well.

I tried accessing the count and rule name as well using len(rego.ResultSet) But, though I am passing two rules, I am getting a count of one.

Here's part of Go script:

import (
        ...
        "github.com/open-policy-agent/opa/rego"
)

<snip>
    // Create Rego for query and evaluation
    regoQuery := rego.New(
        // Rego rule package
        // rego.Package("data.dockerfile_validation"),
        rego.Query("data.dockerfile_validation"),
        // rego policy file
            rego.Module("./policy/security.rego", string(regoPolicyCode)),
        rego.Input(inputData),
    )

    // Evaluate the Rego query
    rs, err := regoQuery.Eval(context.Background())

    // Get the number of policies evaluated by regoQuery
    fmt.Printf("Number of policies evaluated by regoQuery: %v\n", len(rs))

The rego policies I am passing are as follows:

    package dockerfile_validation

# Enforce a Base Image Prefix with Chainguard images:
untrusted_base_image {
    input[i].Cmd == "from"
    val := split(input[i].Value, "/")
    val[0] == "cgr.dev/chainguard/"  
}


# Avoid 'Latest' Tag for Base Images:
latest_base_image {
    input[i].Cmd == "from"
    val := split(input[i].Value[0], ":")
    not contains(lower(val[1]), "latest")
}

Can someone help me on this!

santoshdts
  • 33
  • 6
  • What's the type of the value being assigned to `rs`? – kostix Aug 18 '23 at 15:16
  • It's of type `rego.RuleSet`, a list of Result from evaluation. As described here: https://pkg.go.dev/github.com/open-policy-agent/opa@v0.54.0/rego#ResultSet – santoshdts Aug 18 '23 at 15:48
  • OK, I assume it's `ResultSet`, in fact ;-) So what does `len(rs[0].Exressions)` return? Is it 2? – kostix Aug 18 '23 at 16:33
  • Sorry, my bad that's `rego.ResultSet` indeed. I tried using the `len(rs[0].Expression)` that returns 1 as well. I think I need to check my rules again. Maybe only the first rule is evaluated? I tried defining both the rules with the same name to express them as a logical `OR`. – santoshdts Aug 18 '23 at 17:38

0 Answers0