The Open Policy Agent (OPA, pronounced “oh-pa”) is an open source, general-purpose policy engine that unifies policy enforcement across the stack. OPA provides a high-level declarative language that lets you specify policy as code and simple APIs to offload policy decision-making from your software. You can use OPA to enforce policies in microservices, Kubernetes, CI/CD pipelines, API gateways, and more.

OPA was originally created by Styra and is proud to be a graduated project in the Cloud Native Computing Foundation (CNCF) landscape. For details read the CNCF announcement.

Read this page to learn about the core concepts in OPA’s policy language (Rego) as well as how to download, run, and integrate OPA.

Overview

OPA decouples policy decision-making from policy enforcement. When your software needs to make policy decisions it queries OPA and supplies structured data (e.g., JSON) as input. OPA accepts arbitrary structured data as input.

Introduction - 图1

Policy Decoupling

OPA generates policy decisions by evaluating the query input against policies and data. OPA and Rego are domain-agnostic so you can describe almost any kind of invariant in your policies. For example:

  • Which users can access which resources.
  • Which subnets egress traffic is allowed to.
  • Which clusters a workload must be deployed to.
  • Which registries binaries can be downloaded from.
  • Which OS capabilities a container can execute with.
  • Which times of day the system can be accessed at.

Policy decisions are not limited to simple yes/no or allow/deny answers. Like query inputs, your policies can generate arbitrary structured data as output.

Let’s look at an example.

Example

Imagine you work for an organization with the following system:

Introduction - 图2

Example System

There are three kinds of components in the system:

  • Servers expose zero or more protocols (e.g., http, ssh, etc.)
  • Networks connect servers and can be public or private. Public networks are connected to the Internet.
  • Ports attach servers to networks.

All of the servers, networks, and ports are provisioned by a script. The script receives a JSON representation of the system as input:

  1. {
  2. "servers": [
  3. {"id": "app", "protocols": ["https", "ssh"], "ports": ["p1", "p2", "p3"]},
  4. {"id": "db", "protocols": ["mysql"], "ports": ["p3"]},
  5. {"id": "cache", "protocols": ["memcache"], "ports": ["p3"]},
  6. {"id": "ci", "protocols": ["http"], "ports": ["p1", "p2"]},
  7. {"id": "busybox", "protocols": ["telnet"], "ports": ["p1"]}
  8. ],
  9. "networks": [
  10. {"id": "net1", "public": false},
  11. {"id": "net2", "public": false},
  12. {"id": "net3", "public": true},
  13. {"id": "net4", "public": true}
  14. ],
  15. "ports": [
  16. {"id": "p1", "network": "net1"},
  17. {"id": "p2", "network": "net3"},
  18. {"id": "p3", "network": "net2"}
  19. ]
  20. }

Earlier in the day your boss told you about a new security policy that has to be implemented:

  1. 1. Servers reachable from the Internet must not expose the insecure 'http' protocol.
  2. 2. Servers are not allowed to expose the 'telnet' protocol.

The policy needs to be enforced when servers, networks, and ports are provisioned and the compliance team wants to periodically audit the system to find servers that violate the policy.

Your boss has asked you to determine if OPA would be a good fit for implementing the policy.

Rego

OPA policies are expressed in a high-level declarative language called Rego. Rego (pronounced “ray-go”) is purpose-built for expressing policies over complex hierarchical data structures. For detailed information on Rego see the Policy Language documentation.

💡 The examples below are interactive! If you edit the input data above containing servers, networks, and ports, the output will change below. Similarly, if you edit the queries or rules in the examples below the output will change. As you read through this section, try changing the input, queries, and rules and observe the difference in output.

💻 They can also be run locally on your machine using the opa eval command, here are setup instructions.

References

  1. package example

When OPA evaluates policies it binds data provided in the query to a global variable called input. You can refer to data in the input using the . (dot) operator.

  1. input.servers
  1. [
  2. {
  3. "id": "app",
  4. "ports": [
  5. "p1",
  6. "p2",
  7. "p3"
  8. ],
  9. "protocols": [
  10. "https",
  11. "ssh"
  12. ]
  13. },
  14. {
  15. "id": "db",
  16. "ports": [
  17. "p3"
  18. ],
  19. "protocols": [
  20. "mysql"
  21. ]
  22. },
  23. {
  24. "id": "cache",
  25. "ports": [
  26. "p3"
  27. ],
  28. "protocols": [
  29. "memcache"
  30. ]
  31. },
  32. {
  33. "id": "ci",
  34. "ports": [
  35. "p1",
  36. "p2"
  37. ],
  38. "protocols": [
  39. "http"
  40. ]
  41. },
  42. {
  43. "id": "busybox",
  44. "ports": [
  45. "p1"
  46. ],
  47. "protocols": [
  48. "telnet"
  49. ]
  50. }
  51. ]

To refer to array elements you can use the familiar square-bracket syntax:

  1. input.servers[0].protocols[0]
  1. "https"

💡 You can use the same square bracket syntax if keys contain other than [a-zA-Z0-9_]. E.g., input["foo~bar"].

If you refer to a value that does not exist, OPA returns undefined. Undefined means that OPA was not able to find any results.

  1. input.deadbeef
  1. undefined decision

Expressions (Logical AND)

  1. package example

To produce policy decisions in Rego you write expressions against input and other data.

  1. input.servers[0].id == "app"
  1. true

OPA includes a set of built-in functions you can use to perform common operations like string manipulation, regular expression matching, arithmetic, aggregation, and more.

  1. count(input.servers[0].protocols) >= 1
  1. true

For a complete list of built-in functions supported in OPA out-of-the-box see the Policy Reference page.

Multiple expressions are joined together with the ; (AND) operator. For queries to produce results, all of the expressions in the query must be true or defined. The order of expressions does not matter.

  1. input.servers[0].id == "app"; input.servers[0].protocols[0] == "https"
  1. true

You can omit the ; (AND) operator by splitting expressions across multiple lines. The following query has the same meaning as the previous one:

  1. input.servers[0].id == "app"
  2. input.servers[0].protocols[0] == "https"
  1. true

If any of the expressions in the query are not true (or defined) the result is undefined. In the example below, the second expression is false:

  1. input.servers[0].id == "app"
  2. input.servers[0].protocols[0] == "telnet"
  1. undefined decision

Variables

  1. package example

You can store values in intermediate variables using the := (assignment) operator. Variables can be referenced just like input.

  1. s := input.servers[0]
  2. s.id == "app"
  3. p := s.protocols[0]
  4. p == "https"
  1. +---------+-------------------------------------------------------------------+
  2. | p | s |
  3. +---------+-------------------------------------------------------------------+
  4. | "https" | {"id":"app","ports":["p1","p2","p3"],"protocols":["https","ssh"]} |
  5. +---------+-------------------------------------------------------------------+

When OPA evaluates expressions, it finds values for the variables that make all of the expressions true. If there are no variable assignments that make all of the expressions true, the result is undefined.

  1. s := input.servers[0]
  2. s.id == "app"
  3. s.protocols[1] == "telnet"
  1. undefined decision

Variables are immutable. OPA reports an error if you try to assign the same variable twice.

  1. s := input.servers[0]
  2. s := input.servers[1]
  1. 1 error occurred: 2:1: rego_compile_error: var s assigned above

OPA must be able to enumerate the values for all variables in all expressions. If OPA cannot enumerate the values of a variable in any expression, OPA will report an error.

  1. x := 1
  2. x != y # y has not been assigned a value
  1. 2 errors occurred:
  2. 2:1: rego_unsafe_var_error: var y is unsafe
  3. 2:1: rego_unsafe_var_error: var _ is unsafe

Iteration

  1. package example

Like other declarative languages (e.g., SQL), iteration in Rego happens implicitly when you inject variables into expressions.

There are explicit iteration constructs to express FOR ALL and FOR SOME, see below.

To understand how iteration works in Rego, imagine you need to check if any networks are public. Recall that the networks are supplied inside an array:

  1. input.networks
  1. [
  2. {
  3. "id": "net1",
  4. "public": false
  5. },
  6. {
  7. "id": "net2",
  8. "public": false
  9. },
  10. {
  11. "id": "net3",
  12. "public": true
  13. },
  14. {
  15. "id": "net4",
  16. "public": true
  17. }
  18. ]

One option would be to test each network in the input:

  1. input.networks[0].public == true
  1. false
  1. input.networks[1].public == true
  1. false
  1. input.networks[2].public == true
  1. true

This approach is problematic because there may be too many networks to list statically, or more importantly, the number of networks may not be known in advance.

In Rego, the solution is to substitute the array index with a variable.

  1. some i; input.networks[i].public == true
  1. +---+
  2. | i |
  3. +---+
  4. | 2 |
  5. | 3 |
  6. +---+

Now the query asks for values of i that make the overall expression true. When you substitute variables in references, OPA automatically finds variable assignments that satisfy all of the expressions in the query. Just like intermediate variables, OPA returns the values of the variables.

You can substitute as many variables as you want. For example, to find out if any servers expose the insecure "http" protocol you could write:

  1. some i, j; input.servers[i].protocols[j] == "http"
  1. +---+---+
  2. | i | j |
  3. +---+---+
  4. | 3 | 0 |
  5. +---+---+

If variables appear multiple times the assignments satisfy all of the expressions. For example, to find the ids of ports connected to public networks, you could write:

  1. some i, j
  2. id := input.ports[i].id
  3. input.ports[i].network == input.networks[j].id
  4. input.networks[j].public
  1. +---+------+---+
  2. | i | id | j |
  3. +---+------+---+
  4. | 1 | "p2" | 2 |
  5. +---+------+---+

Providing good names for variables can be hard. If you only refer to the variable once, you can replace it with the special _ (wildcard variable) operator. Conceptually, each instance of _ is a unique variable.

  1. input.servers[_].protocols[_] == "http"
  1. true

Just like references that refer to non-existent fields or expressions that fail to match, if OPA is unable to find any variable assignments that satisfy all of the expressions, the result is undefined.

  1. some i; input.servers[i].protocols[i] == "ssh" # there is no assignment of i that satisfies the expression
  1. undefined decision

FOR SOME and FOR ALL

While plain iteration serves as a powerful building block, Rego also features ways to express FOR SOME and FOR ALL more explicitly.

To ensure backwards-compatibility, the keywords discussed below introduced slowly. In the first stage, users can opt-in to using the new keywords via a special import: import future.keywords introduces all future keywords, and import future.keywords.every introduces the every keyword described here. (Importing every means also importing in without an extra import statement.)

At some point in the future, the keyword will become standard, and the import will become a no-op that can safely be removed. This should give all users ample time to update their policies, so that the new keyword will not cause clashes with existing variable names.

FOR SOME (some)

some ... in ... is used to iterate over the collection (its last argument), and will bind its variables (key, value position) to the collection items. It introduces new bindings to the evaluation of the rest of the rule body.

Using some, we can express the rules introduced above in different ways:

  1. import future.keywords.in
  2. public_network[net.id] { # net.id is in the public_network set if...
  3. some net in input.networks # some network exists and..
  4. net.public # it is public.
  5. }
  6. shell_accessible[server.id] {
  7. some server in input.servers
  8. "telnet" in server.protocols
  9. }
  10. shell_accessible[server.id] {
  11. some server in input.servers
  12. "ssh" in server.protocols
  13. }
  1. shell_accessible
  1. [
  2. "app",
  3. "busybox"
  4. ]

For details on some ... in ..., see the documentation of the in operator.

FOR ALL (every)

Expanding on the examples above, every allows us to succinctly express that a condition holds for all elements of a domain.

  1. import future.keywords.every
  2. no_telnet_exposed {
  3. every server in input.servers {
  4. every protocol in server.protocols {
  5. "telnet" != protocol
  6. }
  7. }
  8. }
  9. no_telnet_exposed_alt { # alternative: every + not-in
  10. every server in input.servers {
  11. not "telnet" in server.protocols
  12. }
  13. }
  14. no_telnet_exposed_alt2 { # alternative: not + rule + some
  15. not any_telnet_exposed
  16. }
  17. any_telnet_exposed {
  18. some server in input.servers
  19. "telnet" in server.protocols
  20. }
  1. {
  2. "servers": [
  3. {
  4. "id": "busybox",
  5. "protocols": ["http", "ftp"]
  6. },
  7. {
  8. "id": "db",
  9. "protocols": ["mysql", "ssh"]
  10. },
  11. {
  12. "id": "web",
  13. "protocols": ["https"]
  14. }
  15. ]
  16. }
  1. no_telnet_exposed
  1. true

For all the details, see Every Keyword.

Rules

Rego lets you encapsulate and re-use logic with rules. Rules are just if-then logic statements. Rules can either be “complete” or “partial”.

Complete Rules

Complete rules are if-then statements that assign a single value to a variable. For example:

  1. package example.rules
  2. any_public_networks := true { # is true if...
  3. net := input.networks[_] # some network exists and..
  4. net.public # it is public.
  5. }

Every rule consists of a head and a body. In Rego we say the rule head is true if the rule body is true for some set of variable assignments. In the example above any_public_networks = true is the head and net := input.networks[_]; net.public is the body.

You can query for the value generated by rules just like any other value:

  1. any_public_networks
  1. true

All values generated by rules can be queried via the global data variable.

  1. data.example.rules.any_public_networks
  1. true

💡 You can query the value of any rule loaded into OPA by referring to it with an absolute path. The path of a rule is always: data.<package-path>.<rule-name>.

If you omit the = <value> part of the rule head the value defaults to true. You could rewrite the example above as follows without changing the meaning:

  1. package example.rules
  2. any_public_networks {
  3. net := input.networks[_]
  4. net.public
  5. }

To define constants, omit the rule body. When you omit the rule body it defaults to true. Since the rule body is true, the rule head is always true/defined.

  1. package example.constants
  2. pi = 3.14

Constants defined like this can be queried just like any other values:

  1. pi > 3
  1. true

If OPA cannot find variable assignments that satisfy the rule body, we say that the rule is undefined. For example, if the input provided to OPA does not include a public network then any_public_networks will be undefined (which is not the same as false.) Below, OPA is given a different set of input networks (none of which are public):

  1. {
  2. "networks": [
  3. {"id": "n1", "public": false},
  4. {"id": "n2", "public": false}
  5. ]
  6. }
  1. any_public_networks
  1. undefined decision

Partial Rules

Partial rules are if-then statements that generate a set of values and assign that set to a variable. For example:

  1. package example.rules
  2. public_network[net.id] { # net.id is in the public_network set if...
  3. net := input.networks[_] # some network exists and...
  4. net.public # it is public.
  5. }

In the example above public_network[net.id] is the rule head and net := input.networks[_]; net.public is the rule body. You can query for the entire set of values just like any other value:

  1. public_network
  1. [
  2. "net3",
  3. "net4"
  4. ]

You can iterate over the set of values by referencing the set elements with a variable:

  1. some n; public_network[n]
  1. +--------+-------------------+
  2. | n | public_network[n] |
  3. +--------+-------------------+
  4. | "net3" | "net3" |
  5. | "net4" | "net4" |
  6. +--------+-------------------+

Lastly, you can check if a value exists in the set using the same syntax:

  1. public_network["net3"]
  1. "net3"

In addition to partially defining sets, You can also partially define key/value pairs (aka objects). See Rules in the language guide for more information.

Logical OR

When you join multiple expressions together in a query you are expressing logical AND. To express logical OR in Rego you define multiple rules with the same name. Let’s look at an example.

Imagine you wanted to know if any servers expose protocols that give clients shell access. To determine this you could define a complete rule that declares shell_accessible to be true if any servers expose the "telnet" or "ssh" protocols:

  1. package example.logical_or
  2. default shell_accessible = false
  3. shell_accessible := true {
  4. input.servers[_].protocols[_] == "telnet"
  5. }
  6. shell_accessible := true {
  7. input.servers[_].protocols[_] == "ssh"
  8. }
  1. {
  2. "servers": [
  3. {
  4. "id": "busybox",
  5. "protocols": ["http", "telnet"]
  6. },
  7. {
  8. "id": "web",
  9. "protocols": ["https"]
  10. }
  11. ]
  12. }
  1. shell_accessible
  1. true

💡 The default keyword tells OPA to assign a value to the variable if all of the other rules with the same name are undefined.

When you use logical OR with partial rules, each rule definition contributes to the set of values assigned to the variable. For example, the example above could be modified to generate a set of servers that expose "telnet" or "ssh".

  1. package example.logical_or
  2. shell_accessible[server.id] {
  3. server := input.servers[_]
  4. server.protocols[_] == "telnet"
  5. }
  6. shell_accessible[server.id] {
  7. server := input.servers[_]
  8. server.protocols[_] == "ssh"
  9. }
  1. {
  2. "servers": [
  3. {
  4. "id": "busybox",
  5. "protocols": ["http", "telnet"]
  6. },
  7. {
  8. "id": "db",
  9. "protocols": ["mysql", "ssh"]
  10. },
  11. {
  12. "id": "web",
  13. "protocols": ["https"]
  14. }
  15. ]
  16. }
  1. shell_accessible
  1. [
  2. "busybox",
  3. "db"
  4. ]

Putting It Together

The sections above explain the core concepts in Rego. To put it all together let’s review the desired policy (in English):

  1. 1. Servers reachable from the Internet must not expose the insecure 'http' protocol.
  2. 2. Servers are not allowed to expose the 'telnet' protocol.

At a high-level the policy needs to identify servers that violate some conditions. To implement this policy we could define rules called violation that generate a set of servers that are in violation.

For example:

  1. package example
  2. import future.keywords # we want "every" and "in"
  3. allow := true { # allow is true if...
  4. count(violation) == 0 # there are zero violations.
  5. }
  6. violation[server.id] { # a server is in the violation set if...
  7. some server in public_servers # it exists in the 'public_servers' set and...
  8. "http" in server.protocols # it contains the insecure "http" protocol.
  9. }
  10. violation[server.id] { # a server is in the violation set if...
  11. some server in input.servers # it exists in the input.servers collection and...
  12. "telnet" in server.protocols # it contains the "telnet" protocol.
  13. }
  14. public_servers[server] { # a server exists in the public_servers set if...
  15. some server in input.servers # it exists in the input.servers collection and...
  16. some port in server.ports # it references a port in the input.ports collection and...
  17. some input_port in input.ports
  18. port == input_port.id
  19. some input_network in input.networks # the port references a network in the input.networks collection and...
  20. input_port.network == input_network.id
  21. input_network.public # the network is public.
  22. }
  1. some x; violation[x]
  1. +-----------+--------------+
  2. | x | violation[x] |
  3. +-----------+--------------+
  4. | "busybox" | "busybox" |
  5. | "ci" | "ci" |
  6. +-----------+--------------+

Running OPA

This section explains how you can query OPA directly and interact with it on your own machine.

1. Download OPA

To get started download an OPA binary for your platform from GitHub releases:

On macOS (64-bit):

  1. curl -L -o opa https://openpolicyagent.org/downloads/v0.40.0/opa_darwin_amd64

On Linux (64-bit):

  1. curl -L -o opa https://openpolicyagent.org/downloads/v0.40.0/opa_linux_amd64_static

Windows users can obtain the OPA executable from here. The steps below are the same for Windows users except the executable name will be different.

Set permissions on the OPA executable:

  1. chmod 755 ./opa

You can also download and run OPA via Docker. The latest stable image tag is openpolicyagent/opa:latest.

Checksums

Checksums for all binaries are available in the download path by appending .sha256 to the binary filename. Verify the macOS binary checksum:

  1. curl -L -o opa_darwin_amd64 https://openpolicyagent.org/downloads/v0.40.0/opa_darwin_amd64
  2. curl -L -o opa_darwin_amd64.sha256 https://openpolicyagent.org/downloads/v0.40.0/opa_darwin_amd64.sha256
  3. shasum -c opa_darwin_amd64.sha256

2. Try opa eval

The simplest way to interact with OPA is via the command-line using the opa eval sub-command. It is a swiss-army knife that you can use to evaluate arbitrary Rego expressions and policies. opa eval supports a large number of options for controlling evaluation. Commonly used flags include:

FlagShortDescription
—bundle-bLoad a bundle file or directory into OPA. This flag can be repeated.
—data-dLoad policy or data files into OPA. This flag can be repeated.
—input-iLoad a data file and use it as input. This flag cannot be repeated.
—format-fSet the output format to use. The default is json and is intended for programmatic use. The pretty format emits more human-readable output.
—failn/aExit with a non-zero exit code if the query is undefined.
—fail-definedn/aExit with a non-zero exit code if the query is not undefined.

For example:

input.json:

  1. {
  2. "servers": [
  3. {"id": "app", "protocols": ["https", "ssh"], "ports": ["p1", "p2", "p3"]},
  4. {"id": "db", "protocols": ["mysql"], "ports": ["p3"]},
  5. {"id": "cache", "protocols": ["memcache"], "ports": ["p3"]},
  6. {"id": "ci", "protocols": ["http"], "ports": ["p1", "p2"]},
  7. {"id": "busybox", "protocols": ["telnet"], "ports": ["p1"]}
  8. ],
  9. "networks": [
  10. {"id": "net1", "public": false},
  11. {"id": "net2", "public": false},
  12. {"id": "net3", "public": true},
  13. {"id": "net4", "public": true}
  14. ],
  15. "ports": [
  16. {"id": "p1", "network": "net1"},
  17. {"id": "p2", "network": "net3"},
  18. {"id": "p3", "network": "net2"}
  19. ]
  20. }

example.rego:

  1. package example
  2. default allow = false # unless otherwise defined, allow is false
  3. allow := true { # allow is true if...
  4. count(violation) == 0 # there are zero violations.
  5. }
  6. violation[server.id] { # a server is in the violation set if...
  7. some server
  8. public_server[server] # it exists in the 'public_server' set and...
  9. server.protocols[_] == "http" # it contains the insecure "http" protocol.
  10. }
  11. violation[server.id] { # a server is in the violation set if...
  12. server := input.servers[_] # it exists in the input.servers collection and...
  13. server.protocols[_] == "telnet" # it contains the "telnet" protocol.
  14. }
  15. public_server[server] { # a server exists in the public_server set if...
  16. some i, j
  17. server := input.servers[_] # it exists in the input.servers collection and...
  18. server.ports[_] == input.ports[i].id # it references a port in the input.ports collection and...
  19. input.ports[i].network == input.networks[j].id # the port references a network in the input.networks collection and...
  20. input.networks[j].public # the network is public.
  21. }
  1. # Evaluate a trivial expression.
  2. ./opa eval "1*2+3"
  3. # Evaluate a policy on the command line.
  4. ./opa eval -i input.json -d example.rego "data.example.violation[x]"
  5. # Evaluate a policy on the command line and use the exit code.
  6. ./opa eval --fail-defined -i input.json -d example.rego "data.example.violation[x]"
  7. echo $?

3. Try opa run (interactive)

OPA includes an interactive shell or REPL (Read-Eval-Print-Loop) accessible via the opa run sub-command. You can use the REPL to experiment with policies and prototype new ones.

To start the REPL just:

  1. ./opa run

When you enter statements in the REPL, OPA evaluates them and prints the result.

  1. > true
  2. true
  3. > 3.14
  4. 3.14
  5. > ["hello", "world"]
  6. [
  7. "hello",
  8. "world"
  9. ]

Most REPLs let you define variables that you can reference later on. OPA allows you to do something similar. For example, you can define a pi constant as follows:

  1. > pi := 3.14

Once “pi” is defined, you query for the value and write expressions in terms of it:

  1. > pi
  2. 3.14
  3. > pi > 3
  4. true

Quit out of the REPL by pressing Control-D or typing exit:

  1. > exit

You can load policy and data files into the REPL by passing them on the command line. By default, JSON and YAML files are rooted under data.

  1. opa run input.json

Run a few queries to poke around the data:

  1. > data.servers[0].protocols[1]
  1. > data.servers[i].protocols[j]
  1. > net := data.networks[_]; net.public

To set a data file as the input document in the REPL prefix the file path:

  1. opa run example.rego repl.input:input.json
  1. > data.example.public_server[s]

Prefixing file paths with a reference controls where file is loaded under data. By convention, the REPL sets the input document that queries see by reading data.repl.input each time a statement is evaluated. See help input for details in the REPL.

Quit out of the REPL by pressing Control-D or typing exit:

  1. > exit

4. Try opa run (server)

To integrate with OPA you can run it as a server and execute queries over HTTP. You can start OPA as a server with -s or --server:

  1. ./opa run --server ./example.rego

By default OPA listens for HTTP connections on 0.0.0.0:8181. See opa run --help for a list of options to change the listening address, enable TLS, and more.

Inside of another terminal use curl (or a similar tool) to access OPA’s HTTP API. When you query the /v1/data HTTP API you must wrap input data inside of a JSON object:

  1. {
  2. "input": <value>
  3. }

Create a copy the input file for sending via curl:

  1. cat <<EOF > v1-data-input.json
  2. {
  3. "input": $(cat input.json)
  4. }
  5. EOF

Execute a few curl requests and inspect the output:

  1. curl localhost:8181/v1/data/example/violation -d @v1-data-input.json -H 'Content-Type: application/json'
  2. curl localhost:8181/v1/data/example/allow -d @v1-data-input.json -H 'Content-Type: application/json'

By default data.system.main is used to serve policy queries without a path. When you execute queries without providing a path, you do not have to wrap the input. If the data.system.main decision is undefined it is treated as an error:

  1. curl localhost:8181 -i -d @input.json -H 'Content-Type: application/json'

You can restart OPA and configure to use any decision as the default decision:

  1. ./opa run --server --set=default_decision=example/allow ./example.rego

Re-run the last curl command from above:

  1. curl localhost:8181 -i -d @input.json -H 'Content-Type: application/json'

5. Try OPA as a Go library

OPA can be embedded inside Go programs as a library. The simplest way to embed OPA as a library is to import the github.com/open-policy-agent/opa/rego package.

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

Call the rego.New function to create an object that can be prepared or evaluated:

  1. r := rego.New(
  2. rego.Query("x = data.example.allow"),
  3. rego.Load([]string{"./example.rego"}, nil))

The rego.Rego supports several options that let you customize evaluation. See the GoDoc page for details. After constructing a new rego.Rego object you can call PrepareForEval() to obtain an executable query. If PrepareForEval() fails it indicates one of the options passed to the rego.New() call was invalid (e.g., parse error, compile error, etc.)

  1. ctx := context.Background()
  2. query, err := r.PrepareForEval(ctx)
  3. if err != nil {
  4. // handle error
  5. }

The prepared query object can be cached in-memory, shared across multiple goroutines, and invoked repeatedly with different inputs. Call Eval() to execute the prepared query.

  1. bs, err := ioutil.ReadFile("./input.json")
  2. if err != nil {
  3. // handle error
  4. }
  5. var input interface{}
  6. if err := json.Unmarshal(bs, &input); err != nil {
  7. // handle error
  8. }
  9. rs, err := query.Eval(ctx, rego.EvalInput(input))
  10. if err != nil {
  11. // handle error
  12. }

The policy decision is contained in the results returned by the Eval() call. You can inspect the decision and handle it accordingly:

  1. // In this example we expect a single result (stored in the variable 'x').
  2. fmt.Println("Result:", rs[0].Bindings["x"])

You can combine the steps above into a simple command-line program that evaluates policies and outputs the result:

main.go:

  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. "os"
  8. "github.com/open-policy-agent/opa/rego"
  9. )
  10. func main() {
  11. ctx := context.Background()
  12. // Construct a Rego object that can be prepared or evaluated.
  13. r := rego.New(
  14. rego.Query(os.Args[2]),
  15. rego.Load([]string{os.Args[1]}, nil))
  16. // Create a prepared query that can be evaluated.
  17. query, err := r.PrepareForEval(ctx)
  18. if err != nil {
  19. log.Fatal(err)
  20. }
  21. // Load the input document from stdin.
  22. var input interface{}
  23. dec := json.NewDecoder(os.Stdin)
  24. dec.UseNumber()
  25. if err := dec.Decode(&input); err != nil {
  26. log.Fatal(err)
  27. }
  28. // Execute the prepared query.
  29. rs, err := query.Eval(ctx, rego.EvalInput(input))
  30. if err != nil {
  31. log.Fatal(err)
  32. }
  33. // Do something with the result.
  34. fmt.Println(rs)
  35. }

Run the code above as follows:

  1. go run main.go example.rego 'data.example.violation' < input.json

Next Steps

Congratulations on making it through the introduction to OPA. If you made it this far you have learned the core concepts behind OPA’s policy language as well as how to get OPA and run it on your own.

If you have more questions about how to write policies in Rego check out:

If you want to try OPA for a specific use case check out:

  • The Ecosystem page which showcases various of OPA integrations.

Some popular tutorials include:

  • The Kubernetes page for how to use OPA as an admission controller in Kubernetes.
  • The Envoy page for how to use OPA as an external authorizer with Envoy.
  • The Terraform page for how to use OPA to validate Terraform plans.

Don’t forget to install the OPA (Rego) Plugin for your favorite IDE or Text Editor