Wildcard in OPA policy definition

65 Views Asked by At

I am trying to write a policy for an endpoint that looks like

/xyz/v1.0/applicationVersions?applicationName=blah&default=true&pageSize=3&pageNumber=1

What is a wildcard/regex match I can do for this endpoint ? My usecase requires me to look up some metadata based on the http endpoint match.

Rego playground link: https://play.openpolicyagent.org/p/RAqOzt9vi8

1

There are 1 best solutions below

0
Charlie Egan On BEST ANSWER

It's hard to know what the exact requirements are here but, I'd suggest:

  • more permissive regular expressions
  • a default value for when there's no match in the function

You might consider some Rego more like this:

package play

import rego.v1

# Below works
path := "/xyz/v1.0/applicationVersions/blah"

# Below does not
# path := "/xyz/v1.0/applicationVersions/applicationName=blah&default=true&pageSize=3&pageNumber=1"

# Simulating OPA auth lib method call
metadata_fetch := metadata(path, input)

default metadata(_, _) := {"no match"}

metadata(http_path, rules) := result if {
    matching_endpoints := [endpoint |
        some endpoint, endpoint_object in rules.endpoints
        regex.match(endpoint, http_path)
    ]

    count(matching_endpoints) > 0

    matching_endpoint := matching_endpoints[0]

    result := {x |
        some x in rules.endpoints[matching_endpoint].metadata
    }
}

And more relaxed regular expressions input like this:

{
    "endpoints": {
        "/xyz/v1.0/applicationVersions": {
            "metadata": [
                "123",
                "456"
            ]
        },
        "/xyz/v1.0/applicationVersions/[a-zA-Z0-9-]+": {
            "metadata": [
                "789",
                "000"
            ]
        }
    }
}