Home > Back-end >  How can I use regex in rego for OPA to identify matching paths and allow or deny admission of pods?
How can I use regex in rego for OPA to identify matching paths and allow or deny admission of pods?

Time:07-15

I have below volumes.rego file that I want to use for OPA.

package kubernetes.admission

deny[msg] {
  input.request.kind.kind == "Pod"
  path := input.request.object.spec.volumes[_].nfs.path
  allowd_paths := {
                   "/ifs/public/rw/webdevel",
                   "/ifs/public/rw/webdevel/prod1",
                   "/ifs/public/rw/webdevel/prod2",
                   "/ifs/public/rw/webdevel/prod3",
                   "/ifs/public/rw/webdevel/test1",
                   "/ifs/public/rw/webdevel/test2",
                   "/ifs/public/rw/webdevel/test3",
                   "/ifs/public/rw/webdevel/dev1",
                   "/ifs/public/rw/webdevel/dev2",
                   "/ifs/public/rw/webdevel/dev3",
                   "/ifs/public/ro/webdevel"
  }
  not allowd_paths[path]
  msg := sprintf("volume '%v' path not allowed to be mounted", [path])
}

As you might have observed, all the allowed paths start with /ifs/public/rw. Many new environments are created under this location. Instead of creating a new entry in rego and applying the changes everytime a new environment is created(like dev, test, prod, etc), can I use regex to match the path "/ifs/public/rw" and anything following that path can also be allowed by the pod to be mounted?

Any suggestions with examples if possible, please?

CodePudding user response:

Yes, you can use regex in rego. Here is a reference for it.

For example, your policy can be written as:

package kubernetes.admission

deny[msg] {
  input.request.kind.kind == "Pod"
  path := input.request.object.spec.volumes[_].nfs.path
  webdevel_regex := "^/ifs/public/rw/webdevel"
  not regex.match(webdevel_regex, path)
  msg := sprintf("volume '%v' path not allowed to be mounted", [path])
}

Of course you can always build more complicated regexes and always test your policies for inputs online at the rego-playground.

Later, if you chose to add more patterns, you can OR them together either in the evaluation expression or the regex itself. Details you can find in the docs link provided.

Hope this helps!

  • Related