open-policy-agent / opa

Open Policy Agent (OPA) is an open source, general-purpose policy engine.
https://www.openpolicyagent.org
Apache License 2.0
9.31k stars 1.29k forks source link

AST: `text` element in location for annotations just says `#METADATA` #6779

Closed anderseknert closed 3 weeks ago

anderseknert commented 1 month ago

For applications working on the Rego AST, like Regal, it would be helpful if the text attribute in the location of a metadata annotation contained the full text of the annotation as provided in the policy. Currently this gives only # METADATA, which isn't that useful. Similar to the text element of a rule body, I expect to get the full text representation of the whole metadata block.

The reason we want this is because some attributes like scope may either have been provided an explicit value by the user, or been set to a default. Without having the original text, we can't say for sure which one it is, as the AST doesn't tell us that.

We can work around this in the meantime by looking at the original source file and map the location to the text, but since this deviates from what the text attribute normally provides, I think this should be fixed in OPA.

p.rego

package policy

import rego.v1

# METADATA
# title: foo
allow := true
❯ opa parse --format json --json-include locations,-comments p.rego

partial output with just annotations

{
  "annotations": [
    {
      "location": {
        "file": "p.rego",
        "row": 5,
        "col": 1,
        "text": "IyBNRVRBREFUQQ=="
      },
      "scope": "rule",
      "title": "foo"
    }
  ],
  "rules": [
    {
      "annotations": [
        {
          "location": {
            "file": "p.rego",
            "row": 5,
            "col": 1,
            "text": "IyBNRVRBREFUQQ=="
          },
          "scope": "rule",
          "title": "foo"
        }
      ],
      "body": [ ],
      "head": {
        "name": "allow",
       }
    }
  ]
}
echo 'IyBNRVRBREFUQQ==' | base64 -d
# METADATA