opa

command module
v0.33.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 4, 2021 License: Apache-2.0 Imports: 3 Imported by: 0

README

logo Open Policy Agent

Slack Status Build Status Go Report Card CII Best Practices Netlify Status

The Open Policy Agent (OPA) is an open source, general-purpose policy engine that enables unified, context-aware policy enforcement across the entire stack.

OPA is hosted by the Cloud Native Computing Foundation (CNCF) as a graduated project. If you are an organization that wants to help shape the evolution of technologies that are container-packaged, dynamically-scheduled and microservices-oriented, consider joining the CNCF. For details read the CNCF announcement.

Want to learn more about OPA?

Want to get OPA?

Want to integrate OPA?

  • See GoDoc to integrate OPA with services written in Go.
  • See REST API to integrate OPA with services written in other languages.

Want to contribute to OPA?

How does OPA work?

OPA gives you a high-level declarative language to author and enforce policies across your stack.

With OPA, you define rules that govern how your system should behave. These rules exist to answer questions like:

  • Can user X call operation Y on resource Z?
  • What clusters should workload W be deployed to?
  • What tags must be set on resource R before it's created?

You integrate services with OPA so that these kinds of policy decisions do not have to be hardcoded in your service. Services integrate with OPA by executing queries when policy decisions are needed.

When you query OPA for a policy decision, OPA evaluates the rules and data (which you give it) to produce an answer. The policy decision is sent back as the result of the query.

For example, in a simple API authorization use case:

  • You write rules that allow (or deny) access to your service APIs.
  • Your service queries OPA when it receives API requests.
  • OPA returns allow (or deny) decisions to your service.
  • Your service enforces the decisions by accepting or rejecting requests accordingly.

The examples below show different kinds of policies you can define with OPA as well as different kinds of queries your system can execute against OPA. The example queries are executed inside OPA's REPL which was built to make it easy to develop and test policies.

For concrete examples of how to integrate OPA with systems like Kubernetes, Terraform, Docker, SSH, and more, see openpolicyagent.org.

Example: API Authorization

This example shows how you can enforce access controls over salary information served by a simple HTTP API. In this example, users are allowed to access their own salary as well as the salary of anyone who reports to them.

The management chain is represented in JSON and stored in a file (data.json):

{
    "management_chain": {
        "bob": [
            "ken",
            "janet"
        ],
        "alice": [
            "janet"
        ]
    }
}

Start OPA and load the data.json file:

opa run data.json

Inside the REPL you can define rules and execute queries. Paste the following rules into the REPL.

default allow = false

allow {
    input.method = "GET"
    input.path = ["salary", id]
    input.user_id = id
}

allow {
    input.method = "GET"
    input.path = ["salary", id]
    managers = data.management_chain[id]
    input.user_id = managers[_]
}
Example Queries

Is someone allowed to access their own salary?

> input := {"method": "GET", "path": ["salary", "bob"], "user_id": "bob"}
> allow
true

Display the management chain for Bob:

> data.management_chain["bob"]
[
    "ken",
    "janet"
]

Is Alice allowed to access Bob's salary?

> input := {"method": "GET", "path": ["salary", "bob"], "user_id": "alice"}
> allow
false

Is Janet allowed to access Bob's salary?

> input := {"method": "GET", "path": ["salary", "bob"], "user_id": "janet"}
> allow
true
Example: App Placement

This example shows how you can enforce where apps are deployed inside a simple orchestrator. In this example, apps must be deployed onto clusters that satisfy PCI and jurisdiction requirements.

app_placement[cluster_id] {
    cluster = data.clusters[cluster_id]
    satisfies_jurisdiction(input.app, cluster)
    satisfies_pci(input.app, cluster)
}

satisfies_jurisdiction(app, cluster) {
    not app.tags["requires-eu"]
}

satisfies_jurisdiction(app, cluster) {
    app.tags["requires-eu"]
    startswith(cluster.region, "eu-")
}

satisfies_pci(app, cluster) {
    not app.tags["requires-pci-level"]
}

satisfies_pci(app, cluster) {
    level = to_number(app.tags["requires-pci-level"])
    level >= cluster.tags["pci-level"]
}
Example Queries

Where will this app be deployed?

> input := {"app": {"tags": {"requires-pci-level": "3", "requires-eu": "true"}}}
> app_placement
[
    "prod-eu"
]

Display clusters in EU region:

> startswith(data.clusters[cluster_id].region, "eu-")
+------------+
| cluster_id |
+------------+
| "prod-eu"  |
| "test-eu"  |
+------------+

Display all clusters:

> data.clusters[cluster_id]
+------------+------------------------------------------------+
| cluster_id |           data.clusters[cluster_id]            |
+------------+------------------------------------------------+
| "prod-eu"  | {"region":"eu-central","tags":{"pci-level":2}} |
| "prod-us"  | {"region":"us-east"}                           |
| "test-eu"  | {"region":"eu-west","tags":{"pci-level":4}}    |
| "test-us"  | {"region":"us-west"}                           |
+------------+------------------------------------------------+
Example: SSH Auditing

This example shows how you can audit who has SSH access to hosts within different clusters. We will assume that SSH access is granted via group access in LDAP.

import data.ldap
import data.clusters

ssh_access[[cluster_name, host_id, user_id]] {
    host_id = clusters[cluster_name].hosts[_]
    group_id = ldap.users[user_id].groups[_]
    group_id = clusters[cluster_name].groups[_]
}

prod_users = {user_id | ssh_access[["prod", _, user_id]]}
Example Queries

Who can access production hosts?

> prod_users
[
  "alice",
  "bob"
]

Display all LDAP users:

> data.ldap.users[user_id]
+-------------------------------+---------+
|   data.ldap.users[user_id]    | user_id |
+-------------------------------+---------+
| {"groups":["dev","platform"]} | "alice" |
| {"groups":["dev","ops"]}      | "bob"   |
| {"groups":["dev"]}            | "janet" |
+-------------------------------+---------+

Display all cluster/group pairs:

> data.clusters[cluster_id].groups[_] = group_id
+------------+------------+
| cluster_id |  group_id  |
+------------+------------+
| "test"     | "dev"      |
| "test"     | "ops"      |
| "prod"     | "ops"      |
| "prod"     | "platform" |
+------------+------------+

Does Janet have access to the test cluster?

> ssh_access[["test", _, "janet"]]
true

What are the addresses of the hosts in the test cluster that Janet can access?

> ssh_access[["test", host_id, "janet"]]; addr = data.hosts[host_id].addr
+------------+------------+
|    addr    |  host_id   |
+------------+------------+
| "10.0.0.1" | "host-abc" |
| "10.0.0.2" | "host-cde" |
| "10.0.0.3" | "host-efg" |
+------------+------------+

Further Reading

Presentations
  • Open Policy Agent Introduction @ CloudNativeCon EU 2018: video, slides
  • Rego Deep Dive @ CloudNativeCon EU 2018: video, slides
  • How Netflix Is Solving Authorization Across Their Cloud @ CloudNativeCon US 2017: video, slides.
  • Policy-based Resource Placement in Kubernetes Federation @ LinuxCon Beijing 2017: slides, screencast.
  • Enforcing Bespoke Policies In Kubernetes @ KubeCon US 2017: video, slides.
  • Istio's Mixer: Policy Enforcement with Custom Adapters @ CloudNativeCon US 2017: video, slides.

Security

Security Audit

A third party security audit was performed by Cure53, you can see the full report here

Reporting Security Vulnerabilities

Please report vulnerabilities by email to open-policy-agent-security. We will send a confirmation message to acknowledge that we have received the report and then we will send additional messages to follow up once the issue has been investigated.

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis
ast
Package ast declares Rego syntax tree types and also includes a parser and compiler for preparing policies for execution in the policy engine.
Package ast declares Rego syntax tree types and also includes a parser and compiler for preparing policies for execution in the policy engine.
location
Package location defines locations in Rego source code.
Package location defines locations in Rego source code.
build
Package bundle implements bundle loading.
Package bundle implements bundle loading.
Package cmd contains the entry points for OPA commands.
Package cmd contains the entry points for OPA commands.
Package compile implements bundles compilation and linking.
Package compile implements bundles compilation and linking.
Package config implements OPA configuration file parsing and validation.
Package config implements OPA configuration file parsing and validation.
Package cover reports coverage on modules.
Package cover reports coverage on modules.
Package dependencies provides functions for determining the set of ast.Refs that AST elements depend on.
Package dependencies provides functions for determining the set of ast.Refs that AST elements depend on.
Package download implements low-level OPA bundle downloading.
Package download implements low-level OPA bundle downloading.
features
wasm
Import this package to enable evaluation of rego code using the built-in wasm engine.
Import this package to enable evaluation of rego code using the built-in wasm engine.
Package format implements formatting of Rego source files.
Package format implements formatting of Rego source files.
internal
cidr/merge
Package merge provides helper functions for merging a list of IP addresses and subnets into the smallest possible list of CIDRs.
Package merge provides helper functions for merging a list of IP addresses and subnets into the smallest possible list of CIDRs.
compiler/wasm
Package wasm contains an IR->WASM compiler backend.
Package wasm contains an IR->WASM compiler backend.
compiler/wasm/opa
Package opa contains bytecode for the OPA-WASM library.
Package opa contains bytecode for the OPA-WASM library.
config
Package config implements helper functions to parse OPA's configuration.
Package config implements helper functions to parse OPA's configuration.
file/url
Package url contains helpers for dealing with file paths and URLs.
Package url contains helpers for dealing with file paths and URLs.
gojsonschema
nolint: goconst // String duplication will be handled later by using errors.Is.
nolint: goconst // String duplication will be handled later by using errors.Is.
ir
Package ir defines an intermediate representation (IR) for Rego.
Package ir defines an intermediate representation (IR) for Rego.
jwx/buffer
Package buffer provides a very thin wrapper around []byte buffer called `Buffer`, to provide functionalities that are often used within the jwx related packages
Package buffer provides a very thin wrapper around []byte buffer called `Buffer`, to provide functionalities that are often used within the jwx related packages
jwx/jwk
Package jwk implements JWK as described in https://tools.ietf.org/html/rfc7517
Package jwk implements JWK as described in https://tools.ietf.org/html/rfc7517
jwx/jws
Package jws implements the digital Signature on JSON based data structures as described in https://tools.ietf.org/html/rfc7515 If you do not care about the details, the only things that you would need to use are the following functions: jws.SignWithOption(Payload, algorithm, key) jws.Verify(encodedjws, algorithm, key) To sign, simply use `jws.SignWithOption`.
Package jws implements the digital Signature on JSON based data structures as described in https://tools.ietf.org/html/rfc7515 If you do not care about the details, the only things that you would need to use are the following functions: jws.SignWithOption(Payload, algorithm, key) jws.Verify(encodedjws, algorithm, key) To sign, simply use `jws.SignWithOption`.
leb128
Package leb128 implements LEB128 integer encoding.
Package leb128 implements LEB128 integer encoding.
merge
Package merge contains helpers to merge data structures frequently encountered in OPA.
Package merge contains helpers to merge data structures frequently encountered in OPA.
planner
Package planner contains a query planner for Rego queries.
Package planner contains a query planner for Rego queries.
presentation
Package presentation prints results of an expression evaluation in json and tabular formats.
Package presentation prints results of an expression evaluation in json and tabular formats.
ref
Package ref implements internal helpers for references
Package ref implements internal helpers for references
report
Package report provides functions to report OPA's version information to an external service and process the response.
Package report provides functions to report OPA's version information to an external service and process the response.
runtime
Package runtime contains utilities to return runtime information on the OPA instance.
Package runtime contains utilities to return runtime information on the OPA instance.
runtime/init
Package init is an internal package with helpers for data and policy loading during initialization.
Package init is an internal package with helpers for data and policy loading during initialization.
semver
Package semver has been vendored from: https://github.com/coreos/go-semver/tree/e214231b295a8ea9479f11b70b35d5acf3556d9b/semver A number of the original functions of the package have been removed since they are not required for our built-ins.
Package semver has been vendored from: https://github.com/coreos/go-semver/tree/e214231b295a8ea9479f11b70b35d5acf3556d9b/semver A number of the original functions of the package have been removed since they are not required for our built-ins.
storage/mock
Package mock defines a fake storage implementation for use in testing.
Package mock defines a fake storage implementation for use in testing.
strvals
Package strvals provides tools for working with strval lines.
Package strvals provides tools for working with strval lines.
version
Package version implements helper functions for the stored version.
Package version implements helper functions for the stored version.
wasm/constant
Package constant contains WASM constant definitions.
Package constant contains WASM constant definitions.
wasm/encoding
Package encoding implements WASM module reading and writing.
Package encoding implements WASM module reading and writing.
wasm/instruction
Package instruction defines WASM instruction types.
Package instruction defines WASM instruction types.
wasm/opcode
Package opcode contains constants and utilities for working with WASM opcodes.
Package opcode contains constants and utilities for working with WASM opcodes.
wasm/types
Package types defines the WASM value type constants.
Package types defines the WASM value type constants.
Package loader contains utilities for loading files into OPA.
Package loader contains utilities for loading files into OPA.
Package metrics contains helpers for performance metric management inside the policy engine.
Package metrics contains helpers for performance metric management inside the policy engine.
Package plugins implements plugin management for the policy engine.
Package plugins implements plugin management for the policy engine.
bundle
Package bundle implements bundle loading.
Package bundle implements bundle loading.
discovery
Package discovery implements configuration discovery.
Package discovery implements configuration discovery.
logs
Package logs implements decision log buffering and uploading.
Package logs implements decision log buffering and uploading.
rest
Package rest implements a REST client for communicating with remote services.
Package rest implements a REST client for communicating with remote services.
status
Package status implements status reporting.
Package status implements status reporting.
Package profiler computes and reports on the time spent on expressions.
Package profiler computes and reports on the time spent on expressions.
Package refactor implements different refactoring operations over Rego modules.
Package refactor implements different refactoring operations over Rego modules.
Package rego exposes high level APIs for evaluating Rego policies.
Package rego exposes high level APIs for evaluating Rego policies.
Package repl implements a Read-Eval-Print-Loop (REPL) for interacting with the policy engine.
Package repl implements a Read-Eval-Print-Loop (REPL) for interacting with the policy engine.
Package runtime contains the entry point to the policy engine.
Package runtime contains the entry point to the policy engine.
sdk
Package sdk contains a high-level API for embedding OPA inside of Go programs.
Package sdk contains a high-level API for embedding OPA inside of Go programs.
Package server contains the policy engine's server handlers.
Package server contains the policy engine's server handlers.
authorizer
Package authorizer provides authorization handlers to the server.
Package authorizer provides authorization handlers to the server.
identifier
Package identifier provides handlers for associating an identity with incoming requests.
Package identifier provides handlers for associating an identity with incoming requests.
types
Package types contains request/response types and codes for the server.
Package types contains request/response types and codes for the server.
writer
Package writer contains utilities for writing responses in the server.
Package writer contains utilities for writing responses in the server.
Package storage exposes the policy engine's storage layer.
Package storage exposes the policy engine's storage layer.
disk
Package disk provides disk-based implementation of the storage.Store interface.
Package disk provides disk-based implementation of the storage.Store interface.
inmem
Package inmem implements an in-memory version of the policy engine's storage layer.
Package inmem implements an in-memory version of the policy engine's storage layer.
internal/errors
Package errors contains reusable error-related code for the storage layer.
Package errors contains reusable error-related code for the storage layer.
internal/ptr
Package ptr provides utilities for pointer operations using storage layer paths.
Package ptr provides utilities for pointer operations using storage layer paths.
test
authz
Package authz contains unit and benchmark tests for authz use-cases The public (non-test) APIs are meant to be used as helpers for other tests to build off of.
Package authz contains unit and benchmark tests for authz use-cases The public (non-test) APIs are meant to be used as helpers for other tests to build off of.
cases
Package cases contains utilities for evaluation test cases.
Package cases contains utilities for evaluation test cases.
e2e
Package tester contains utilities for executing Rego tests.
Package tester contains utilities for executing Rego tests.
Package topdown provides low-level query evaluation support.
Package topdown provides low-level query evaluation support.
builtins
Package builtins contains utilities for implementing built-in functions.
Package builtins contains utilities for implementing built-in functions.
cache
Package cache defines the inter-query cache interface that can cache data across queries
Package cache defines the inter-query cache interface that can cache data across queries
Package types declares data types for Rego values and helper functions to operate on these types.
Package types declares data types for Rego values and helper functions to operate on these types.
Package util provides generic utilities used throughout the policy engine.
Package util provides generic utilities used throughout the policy engine.
test
Package test contains utilities used in the policy engine's test suite.
Package test contains utilities used in the policy engine's test suite.
Package version contains version information that is set at build time.
Package version contains version information that is set at build time.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL