### Start Local Development Server Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/contrib-docs.md Run this command after installing Node packages to start a live-updating development server for the OPA documentation. ```bash make dev ``` -------------------------------- ### Install OPA-Envoy with Quick Start Manifest Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/envoy/tutorial-istio.md Apply the quick_start.yaml manifest to install OPA-Envoy and related Kubernetes resources. This manifest sets up the AuthorizationPolicy, ServiceEntry, namespace, admission controller, and ConfigMaps for OPA. ```bash kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/opa-envoy-plugin/main/examples/istio/quick_start.yaml ``` -------------------------------- ### Install godropbox package Source: https://github.com/open-policy-agent/opa/blob/main/internal/edittree/bitvector/README.md Use the go get command to download and install the library into your Go workspace. ```bash go get github.com/dropbox/godropbox ``` -------------------------------- ### Launch Kafka Tutorial Environment Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/kafka-authorization.md This command starts the Docker containers for the Kafka tutorial environment. Ensure Docker Compose is installed and configured. ```bash docker-compose --project-name opa-kafka-tutorial up ``` -------------------------------- ### Start OPA with TLS Enabled (Minimal) Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/security.md Starts OPA in server mode with TLS enabled using specified certificate and private key files. This is a basic setup for secure API access. ```bash opa run --server --log-level debug \ --tls-cert-file public.crt \ --tls-private-key-file private.key ``` -------------------------------- ### Start Minikube Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/envoy/tutorial-gloo-edge.md Initiates a local Kubernetes cluster using Minikube. Ensure Minikube is installed and meets version requirements. ```bash minikube start ``` -------------------------------- ### Start OPA with Configuration Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/extensions.md Command to start the OPA server with the specified configuration file, enabling the custom plugin. ```bash ./opa++ run --server --config-file opa-config.yaml ``` -------------------------------- ### Git Configuration Examples Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/ocp/api-reference.md Examples for configuring OPA to load policies from Git repositories. ```APIDOC ## Basic Git Source ### Description Configure OPA to load policies from a basic Git repository. ### Request Body ```json { "git": { "repo": "https://github.com/myorg/policies.git", "reference": "refs/heads/main", "credentials": "github-token" } } ``` ## Git with Path and File Filtering ### Description Configure OPA to load policies from a Git repository with specific paths and file filtering. ### Request Body ```json { "git": { "repo": "git@github.com:myorg/monorepo.git", "reference": "refs/heads/production", "commit": "abc123def456789", "path": "services/auth/policies", "included_files": ["*.rego", "*.json"], "excluded_files": ["*.test.rego", "examples/*"], "credentials": "ssh-key" } } ``` ``` -------------------------------- ### Database Configuration Example Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/ocp/guide-deploy-as-a-service.md Example YAML configuration for connecting OPA to a PostgreSQL database. ```yaml database: sql: driver: postgres dsn: "postgres://opactl:password@postgres-service:5432/opactl?sslmode=disable" ``` -------------------------------- ### Start OPA as Server with Bundle Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/management-bundles/index.md Command to start OPA in server mode, serving decisions from loaded bundles. ```bash opa run --server --set default_decision=policies -c configuration.yaml ``` -------------------------------- ### Install Node Packages for Local Development Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/contrib-docs.md Navigate to the `docs/` directory and install the necessary Node packages to run the documentation locally. ```bash cd docs make install ``` -------------------------------- ### Start OPA Interactive REPL Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/index.md Initiates the OPA Read-Eval-Print-Loop (REPL) for interactive policy experimentation. No setup is required beyond having the OPA binary. ```bash ./opa run ``` -------------------------------- ### Install and Run OPA on EC2 using Bash Script Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/deploy/aws/ec2.mdx This bash script automates the installation of the OPA binary, sets up its configuration file for a service (e.g., acmecorp) and bundles, and configures OPA to run as a systemd service. It downloads the latest OPA version for Linux AMD64, places the configuration in /etc/credstore, and starts OPA listening on port 8181. ```bash #!/bin/bash REPO=https://github.com/open-policy-agent/opa curl -L -o /usr/local/bin/opa $REPO/releases/download/v{{version}}/opa_linux_amd64 chmod 755 /usr/local/bin/opa cat < /etc/credstore/opa.service/config # example configuration services: acmecorp: url: https://example.com/control-plane-api/v1 response_header_timeout_seconds: 5 credentials: bearer: token: "{{token}}" labels: app: myapp region: west environment: production bundles: authz: service: acmecorp resource: bundles/http/example/authz.tar.gz EOF cat < /etc/systemd/system/opa.service [Unit] Description=Open Policy Agent After=network.target StartLimitInterval=60 StartLimitBurst=4 [Service] ExecStart=/usr/local/bin/opa run --server --addr=0.0.0.0:8181 --config-file=$CREDENTIALS_DIRECTORY/config LoadCredential=config:/etc/credstore/opa.service/config RuntimeDirectory=opa WorkingDirectory=/run/opa Restart=always RestartSec=5 Restart=on-failure DynamicUser=yes ProtectSystem=full PrivateTmp=yes [Install] WantedBy=multi-user.target EOF systemctl daemon-reload systemctl enable opa.service systemctl start opa.service ``` -------------------------------- ### OPA REPL Output Example Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/management-bundles/index.md Example output from the OPA REPL showing successful bundle loading and the initial data state. ```text > {"level":"info","msg":"Bundle loaded and activated successfully.","name":"authz","plugin":"bundle","time":"2022-06-15T16:50:53+03:00"} > data { "policies": { "play": { "hello": false } } } > exit ``` -------------------------------- ### List Bundles Response Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/ocp/api-reference.md Example response for GET /v1/bundles showing bundle details and pagination cursor. ```json { "result": [ { "name": "main-bundle", "labels": { "env": "production", "team": "platform" }, "object_storage": { "aws": { "bucket": "my-policy-bundles", "key": "bundles/my-app/bundle.tar.gz", "region": "us-east-1", "credentials": "aws-creds" } }, "requirements": [ { "source": "my-app-policies" }, { "source": "shared-policies", "path": "library", "prefix": "shared.lib" } ], "excluded_files": [ "*.test.rego", ".git/*" ] } ], "next_cursor": "eyJpZCI6IjEyMyIsInRzIjoxNjkwMjM0NTY3fQ==" } ``` -------------------------------- ### Example Request to Initialize Document Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/rest-api.md An example request to initialize a document using PUT with the If-None-Match header to prevent overwriting. ```http PUT /v1/data/us-west/servers HTTP/1.1 Content-Type: application/json If-None-Match: * ``` -------------------------------- ### HTTP GET Request for Ready Check Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/rest-api.md Example HTTP request to check the readiness of the OPA service. ```http GET /health/ready HTTP/1.1 ``` -------------------------------- ### Datasource Examples Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/ocp/api-reference.md Examples for configuring OPA to use external data sources. ```APIDOC ## HTTP Datasource ### Description Configure OPA to fetch data from an HTTP endpoint. ### Request Body ```json { "datasources": [ { "name": "user-directory", "path": "external/users", "type": "http", "config": { "url": "https://api.company.com/users", "headers": { "Accept": "application/json", "User-Agent": "OPA-Control-Plane/1.0" } }, "credentials": "api-credentials", "transform_query": "{user.id: user | user := input.users[_]}" } ] } ``` ``` -------------------------------- ### Example OPA Configuration Response Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/rest-api.md An example JSON response containing OPA's active configuration details. ```json { "result": { "services": { "acmecorp": { "url": "https://example.com/control-plane-api/v1" } }, "labels": { "id": "test-id", "version": "0.27.0" }, "keys": { "global_key": { "scope": "read" } }, "decision_logs": { "service": "acmecorp" }, "status": { "service": "acmecorp" }, "bundles": { "authz": { "service": "acmecorp" } }, "default_authorization_decision": "/system/authz/allow", "default_decision": "/system/main" } } ``` -------------------------------- ### Rego Linter Configuration Example Source: https://github.com/open-policy-agent/opa/blob/main/docs/projects/regal/rules/idiomatic/equals-pattern-matching.md Example of how to configure the equals-pattern-matching linter rule in a Rego project. ```yaml rules: idiomatic: equals-pattern-matching: # one of "error", "warning", "ignore" level: error ``` -------------------------------- ### Example Data Definition Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/policy-language.md Defines sample data structures for 'sites', 'apps', and 'containers' used in policy examples. ```rego package example sites := [ { "region": "east", "name": "prod", "servers": [ { "name": "web-0", "hostname": "hydrogen" }, { "name": "web-1", "hostname": "helium" }, { "name": "db-0", "hostname": "lithium" } ] }, { "region": "west", "name": "smoke", "servers": [ { "name": "web-1000", "hostname": "beryllium" }, { "name": "web-1001", "hostname": "boron" }, { "name": "db-1000", "hostname": "carbon" } ] }, { "region": "west", "name": "dev", "servers": [ { "name": "web-dev", "hostname": "nitrogen" }, { "name": "db-dev", "hostname": "oxygen" } ] } ] apps := [ { "name": "web", "servers": ["web-0", "web-1", "web-1000", "web-1001", "web-dev"] }, { "name": "mysql", "servers": ["db-0", "db-1000"] }, { "name": "mongodb", "servers": ["db-dev"] } ] containers := [ { "image": "redis", "ipaddress": "10.0.0.1", "name": "big_stallman" }, { "image": "nginx", "ipaddress": "10.0.0.2", "name": "cranky_euclid" } ] ``` -------------------------------- ### Install opa-docker-authz Plugin Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/docker-authorization.md Command to install the OPA Docker authorization plugin, specifying the configuration file path. ```shell docker plugin install --alias opa-docker-authz ghcr.io/open-policy-agent/opa-docker-authz:v0.10 opa-args="-config-file /opa/config/opa-config.yaml" ``` -------------------------------- ### Basic OPA Integration with Go SDK Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/integration.md Demonstrates creating an OPA instance with a mock bundle server and fetching a policy decision. This example sets up OPA configuration, loads a policy, and queries it with specific input. ```go package main import ( "bytes" "context" "fmt" "github.com/open-policy-agent/opa/v1/sdk" sdktest "github.com/open-policy-agent/opa/v1/sdk/test" ) func main() { ctx := context.Background() // create a mock HTTP bundle server server, err := sdktest.NewServer(sdktest.MockBundle("/bundles/bundle.tar.gz", map[string]string{ "example.rego": " package authz default allow := false allow if input.open == \"sesame\" ", })) if err != nil { // handle error. } defer server.Stop() // provide the OPA configuration which specifies // fetching policy bundles from the mock server // and logging decisions locally to the console config := []byte(fmt.Sprintf(`{ \"services\": { \"test\": { \"url\": %q } }, \"bundles\": { \"test\": { \"resource\": \"/bundles/bundle.tar.gz\" } }, \"decision_logs\": { \"console\": true } }`, server.URL())) // create an instance of the OPA object opa, err := sdk.New(ctx, sdk.Options{ ID: "opa-test-1", Config: bytes.NewReader(config), }) if err != nil { // handle error. } defer opa.Stop(ctx) // get the named policy decision for the specified input if result, err := opa.Decision(ctx, sdk.DecisionOptions{Path: "/authz/allow", Input: map[string]any{"open": "sesame"}}); err != nil { // handle error. } else if decision, ok := result.Result.(bool); !ok || !decision { // handle error. } } ``` -------------------------------- ### Example Request Body for Get Document Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/rest-api.md The JSON payload for the example request to get a document. ```json { "example": { "flag": true } } ``` -------------------------------- ### Example Response Body for Get Document Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/rest-api.md The JSON payload of a successful response when getting a document. ```json true ``` -------------------------------- ### Get Latest Bundle Status Response Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/ocp/api-reference.md Example response for GET /v1/bundles/{bundle}/status/latest. ```json { "result": { "bundle_name": "my-app-bundle", "revision": "1.0.0", "phase": "BUILD", "status": "SUCCESS", "created_at": "2025-08-07T10:30:00Z" } } ``` -------------------------------- ### Example Request to Get Document Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/rest-api.md An example HTTP request to fetch a document using the webhook API. ```http POST /v0/data/opa/examples/allow_request HTTP/1.1 Content-Type: application/json ``` -------------------------------- ### Get Specific Bundle Response Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/ocp/api-reference.md Example response for GET /v1/bundles/{bundle} retrieving a single bundle configuration. ```json { "result": { "name": "my-app-bundle", "labels": { "env": "production", "version": "1.0.0" }, "object_storage": { "filesystem": { "path": "/bundles/my-app/bundle.tar.gz" } }, "requirements": [ { "source": "my-app-policies" }, { "git": { "commit": "abc123def456" } } ], "excluded_files": [ "*.md", "docs/*" ] } } ``` -------------------------------- ### Example Response for Get Document Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/rest-api.md A successful HTTP response indicating the retrieved document. ```http HTTP/1.1 200 OK Content-Type: application/json ``` -------------------------------- ### Avoid get_ and list_ Prefixes in Rego Functions and Rules Source: https://github.com/open-policy-agent/opa/blob/main/docs/projects/regal/rules/style/avoid-get-and-list-prefix.md Demonstrates the Rego style guide's recommendation to avoid 'get_' and 'list_' prefixes for functions and partial rules. The 'Avoid' examples show the prefixed versions, while the 'Prefer' examples show the recommended, cleaner alternatives. ```rego package policy get_first_name(user) := split(user.name, " ")[0] # Partial rule, so a set of users is to be expected list_developers contains user if { some user in data.application.users user.type == "developer" } ``` ```rego package policy # "get" is implied first_name(user) := split(user.name, " ")[0] # Partial rule, so a set of users is to be expected developers contains user if { some user in data.application.users user.type == "developer" } ``` -------------------------------- ### Manifest File Example Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/management-bundles/index.md Specifies the root policies and required built-ins for the bundle. ```json { "roots": ["policies"], "metadata": { "required_builtins": { "builtin1": [] } } } ``` -------------------------------- ### Example Response for GET Document Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/rest-api.md A successful response (200 OK) for a GET request to the Data API. The 'result' field contains the requested document data. If the path is undefined, the 'result' field will be omitted. ```json { "result": [ { "id": "s1", "name": "app", "ports": [ "p1", "p2", "p3" ], "protocols": [ "https", "ssh" ] }, { "id": "s4", "name": "dev", "ports": [ "p1", "p2" ], "protocols": [ "http" ] } ] } ``` -------------------------------- ### HTTP GET Request for Live Check Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/rest-api.md Example HTTP request to check the liveness of the OPA service. ```http GET /health/live HTTP/1.1 ``` -------------------------------- ### Create Directories for Policy Files Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/kafka-authorization.md Sets up the necessary directories for storing policy files, built bundles, and the OPA authorizer plugin. ```bash mkdir policies bundles plugin ``` -------------------------------- ### Superfluous Object Get Rule Configuration Source: https://github.com/open-policy-agent/opa/blob/main/docs/projects/regal/rules/idiomatic/superfluous-object-get.md Example configuration for the `superfluous-object-get` linter rule, specifying the severity level. ```yaml rules: idiomatic: superfluous-object-get: # one of "error", "warning", "ignore" level: error ``` -------------------------------- ### Build a Basic Bundle Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/management-bundles/index.md Use the `opa build -b` command to create a bundle from a directory. The bundle will be named `bundle.tar.gz` by default. ```console $ ls foo/ example.rego $ opa build -b foo/ ``` -------------------------------- ### Define and use a simple custom built-in function Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/extensions.md This example shows how to declare and implement a custom built-in function named 'hello' that accepts a string and returns a greeting. It demonstrates preparing and evaluating a query with the custom function. ```Go r := rego.New( rego.Query(`x = hello("bob")`), rego.Function1( ®o.Function{ Name: "hello", Decl: types.NewFunction(types.Args(types.S), types.S), }, func(_ rego.BuiltinContext, a *ast.Term) (*ast.Term, error) { if str, ok := a.Value.(ast.String); ok { return ast.StringTerm("hello, " + string(str)), nil } return nil, nil }), ) query, err := r.PrepareForEval(ctx) if err != nil { // handle error. } rs, err := query.Eval(ctx) if err != nil { // handle error. } // Do something with result. fmt.Println(rs[0].Bindings["x"]) ``` -------------------------------- ### Example OCP Sources Configuration Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/ocp/concepts.md This example demonstrates configuring OCP to source policy from a Git repository, data from a local file, and additional data via HTTP from Amazon S3. It also shows how to reference credentials for authentication. ```yaml sources: app-policy: git: repo: https://github.com/example/app-policy.git reference: refs/heads/main excluded_files: - ".*/*" credentials: github-token global-data: paths: - global/common.json s3-data: datasources: - name: s3-datasource type: http path: data/from/s3 config: url: https://my-bucket.s3.my-region.amazonaws.com/s3-data.json credentials: aws_auth ``` -------------------------------- ### Install OPA using GitHub Action Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/cicd/index.md This snippet shows how to add an OPA installation step to a GitHub Actions workflow. It uses the `open-policy-agent/setup-opa` action to make the `opa` command available. ```yaml - name: Download OPA uses: open-policy-agent/setup-opa with: version: latest # install the latest version ``` -------------------------------- ### Mounting All Content with a Prefix Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/ocp/concepts.md This example shows how to mount all content from an external source under a specified prefix, creating a new namespace for the imported policies and data. ```yaml requirements: - source: external-policies prefix: external.policies ``` -------------------------------- ### Neovim LSP Configuration with none-ls for Regal Diagnostics Source: https://github.com/open-policy-agent/opa/blob/main/docs/projects/regal/editor-support.md Minimal installation and setup for none-ls in Neovim using VimPlug to integrate Regal for diagnostics. This injects LSP diagnostics and code actions. ```vim Plug 'nvim-lua/plenary.nvim' Plug 'nvimtools/none-ls.nvim' lua < scope: read caching: inter_query_builtin_cache: max_size_bytes: 10000000 forced_eviction_threshold_percentage: 70 stale_entry_eviction_period_seconds: 3600 distributed_tracing: type: grpc address: localhost:4317 service_name: opa sample_percentage: 50 encryption: "off" resource: service_namespace: "my-namespace" service_version: "1.1" service_instance_id: "1" deployment_environment: "prod" server: decoding: max_length: 134217728 gzip: max_length: 268435456 encoding: gzip: min_length: 1024 compression_level: 9 ``` -------------------------------- ### OPA Linter Configuration for 'use-in-operator' Source: https://github.com/open-policy-agent/opa/blob/main/docs/projects/regal/rules/idiomatic/use-in-operator.md Example YAML configuration for the OPA linter rule 'use-in-operator'. This allows setting the severity level (error, warning, ignore) for violations of the 'in' operator style guide. ```yaml rules: idiomatic: use-in-operator: # one of "error", "warning", "ignore" level: error ``` -------------------------------- ### Register and Execute OPA with Plugin Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/extensions.md This Go code snippet shows how to register the custom plugin factory with OPA's runtime and then execute the OPA command. This is the entry point for an OPA executable that includes custom plugins. ```go import ( "github.com/open-policy-agent/opa/cmd" "github.com/open-policy-agent/opa/runtime" ) func main() { runtime.RegisterPlugin(PluginName, Factory{}) if err := cmd.RootCommand.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } ``` -------------------------------- ### Unification Operator Behavior: Assignment vs. Comparison Source: https://github.com/open-policy-agent/opa/blob/main/docs/projects/regal/rules/idiomatic/prefer-equals-comparison.md Explains how the Rego unification operator (`=`) can act as either assignment or comparison based on context. This example shows how `x = input.x` is an assignment if `x` is unassigned, but a comparison if `x` has been previously assigned. ```rego rule if { x = input.x # assignment, provided that `x` is not assigned elsewhere } rule if { x := 5 x = input.x # comparison, as `x` is assigned above and unassignable here } ``` -------------------------------- ### Create OPA Policy ConfigMap Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/deploy/docker/index.md Command to create a Kubernetes ConfigMap named 'example-policy' from the 'example.rego' policy file. ```bash kubectl create configmap example-policy --from-file example.rego ``` -------------------------------- ### Build and Test OPA Project Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/contrib-development.md Run 'make' to build the OPA binary, execute all tests, and perform static analysis checks. A successful build produces an executable binary in the top directory. ```bash make ``` -------------------------------- ### Verify OPA installation Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/index.md Checks the installed OPA version to confirm a successful installation. This command can be run from any directory after adding OPA to your PATH. ```shell opa version ``` -------------------------------- ### Automate OPA Installation and Service Configuration on GCE Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/deploy/google-cloud/gce.mdx A bash script designed for GCE startup metadata to download the OPA binary, write a configuration file to the credstore, and register OPA as a systemd service. It requires a bundle service token and specific OPA version to function correctly. ```bash #!/bin/bash REPO=https://github.com/open-policy-agent/opa curl -L -o /usr/local/bin/opa $REPO/releases/download/v{{version}}/opa_linux_amd64 chmod 755 /usr/local/bin/opa cat < /etc/credstore/opa.service/config # example configuration services: acmecorp: url: https://example.com/control-plane-api/v1 response_header_timeout_seconds: 5 credentials: bearer: token: "{{token}}" labels: app: myapp region: west environment: production bundles: authz: service: acmecorp resource: bundles/http/example/authz.tar.gz EOF cat < /etc/systemd/system/opa.service [Unit] Description=Open Policy Agent After=network.target StartLimitInterval=60 StartLimitBurst=4 [Service] ExecStart=/usr/local/bin/opa run --server --addr=0.0.0.0:8181 --config-file=$CREDENTIALS_DIRECTORY/config LoadCredential=config:/etc/credstore/opa.service/config RuntimeDirectory=opa WorkingDirectory=/run/opa Restart=always RestartSec=5 Restart=on-failure DynamicUser=yes ProtectSystem=full PrivateTmp=yes [Install] WantedBy=multi-user.target EOF systemctl daemon-reload systemctl enable opa.service systemctl start opa.service ``` -------------------------------- ### Test Bob's GET Request Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/envoy/tutorial-gloo-edge.md Tests a GET request with Bob's token, expecting a 200 OK response, verifying authorization for GET requests. ```bash curl -XGET -Is -H "Authorization: Bearer $BOB_TOKEN" localhost:8080/get HTTP/1.1 200 OK ``` -------------------------------- ### Test Alice's GET Request Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/envoy/tutorial-gloo-edge.md Tests a GET request with Alice's token, expecting a 200 OK response, verifying authorization for GET requests. ```bash curl -XGET -Is -H "Authorization: Bearer $ALICE_TOKEN" localhost:8080/get HTTP/1.1 200 OK ``` -------------------------------- ### Accessing example.com with System Cert Pool Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/policy-reference/builtins/http.mdx Use this snippet to make an HTTP GET request to example.com, utilizing the system's certificate pool for TLS verification. ```rego http.send({ "method": "get", "url": "https://www.example.com", "tls_use_system_certs": true, }) ``` -------------------------------- ### Run OPA with Bundle in REPL Mode Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/management-bundles/index.md Command to start OPA CLI in interactive REPL mode with the specified configuration, showing loaded bundles. ```bash opa run -c configuration.yaml ``` -------------------------------- ### Example Rego Policy Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/rest-api.md An example Rego policy used for demonstrating the Compile API. ```rego package example allow if { input.subject.clearance_level >= data.reports[_].clearance_level } ``` -------------------------------- ### Preparing a Query with Rego Options Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/integration.md Construct a prepared query using rego.New with options for query, module, and data. This avoids repeated parsing and compilation. ```go module := ` package example.authz default allow := false allow if { input.method == "GET" input.path == ["salary", input.subject.user] } allow if is_admin is_admin if "admin" in input.subject.groups ` ctx := context.TODO() query, err := rego.New( rego.Query("x = data.example.authz.allow"), rego.Module("example.rego", module), ).PrepareForEval(ctx) if err != nil { // Handle error. } ``` -------------------------------- ### Run OPA with a Remote Bundle Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/debugging/index.md Start a local OPA instance and load a bundle from a remote URL. This is useful for debugging by replicating a production environment locally. ```shell opa run -s https://example.com/bundles/bundle.tar.gz ``` -------------------------------- ### Example Request to Delete Document Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/rest-api.md An example HTTP request to delete the 'servers' document. ```http DELETE /v1/data/servers HTTP/1.1 ``` -------------------------------- ### Info Log Output Example Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/deploy/docker/index.md Example of OPA log output when the log level is set to 'info'. Shows basic server startup and request/response information. ```json {"addrs":[":8181"],"insecure_addr":"","level":"info","msg":"First line of log stream.","time":"2019-05-08T17:25:26-07:00"} {"level":"info","msg":"Starting decision log uploader.","plugin":"decision_logs","time":"2019-05-08T17:25:26-07:00"} {"client_addr":"[::1]:63902","level":"info","msg":"Received request.","req_body":"","req_id":1,"req_method":"GET","req_params":{},"req_path":"/v1/data","time":"2019-05-08T17:25:41-07:00"} {"client_addr":"[::1]:63902","level":"info","msg":"Sent response.","req_id":1,"req_method":"GET","req_path":"/v1/data","resp_body":"{\"decision_id\":\"f4b41501-2408-4a14-8269-1c1085abeda4\",\"result\":{}}","resp_bytes":66,"resp_duration":2.545972,"resp_status":200,"time":"2019-05-08T17:25:41-07:00"} ``` -------------------------------- ### Example Input Document Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/management-decision-logs.md This is an example of an input document that might contain sensitive data. ```json { "resource": "user", "name": "bob", "password": "passw0rd" } ``` -------------------------------- ### Build OPA Bundle Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/ocp/index.md Run the build command to create an OPA bundle. This command is executed in your working directory. ```shell opactl build ``` -------------------------------- ### Install Gloo Edge with Helm Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/envoy/tutorial-gloo-edge.md Installs Gloo Edge on the Kubernetes cluster using Helm. This command adds the Gloo Edge Helm repository and upgrades or installs the Gloo Edge chart in the 'gloo-system' namespace. ```bash helm repo add gloo https://storage.googleapis.com/solo-public-helm helm upgrade --install --namespace gloo-system --create-namespace gloo gloo/gloo kubectl config set-context $(kubectl config current-context) --namespace=gloo-system ``` -------------------------------- ### Example Request Body for Initialize Document Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/rest-api.md An empty JSON object as the request body for initializing a document. ```json {} ``` -------------------------------- ### Example RBAC Policy in Rego Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/policy-performance.md This Rego policy defines roles, permissions, and rules for an example Role-Based Access Control (RBAC) system. It includes example input, bindings, roles, and the core 'allow' rule. ```rego package rbac # Example input request inp := { "subject": "bob", "resource": "foo123", "action": "write", } # Example RBAC configuration. bindings := [ { "user": "alice", "roles": ["dev", "test"], }, { "user": "bob", "roles": ["test"], }, ] roles := [ { "name": "dev", "permissions": [ {"resource": "foo123", "action": "write"}, {"resource": "foo123", "action": "read"}, ], }, { "name": "test", "permissions": [{"resource": "foo123", "action": "read"}], }, ] # Example RBAC policy implementation. default allow := false allow if { some role_name user_has_role[role_name] role_has_permission[role_name] } user_has_role contains role_name if { binding := bindings[_] binding.user == inp.subject role_name := binding.roles[_] } role_has_permission contains role_name if { role := roles[_] role_name := role.name perm := role.permissions[_] perm.resource == inp.resource perm.action == inp.action } ``` -------------------------------- ### Exercise OPA Policy for Bob Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/envoy/tutorial-istio.md Test access for user 'bob' to '/productpage' and '/api/v1/products' (both should succeed). ```bash curl --user bob:password -i http://$SERVICE_HOST/productpage curl --user bob:password -i http://$SERVICE_HOST/api/v1/products ``` -------------------------------- ### Compile API Example Response Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/rest-api.md An example HTTP response from the Compile API after partial evaluation. ```http HTTP/1.1 200 OK Content-Type: application/json ``` ```json { "result": { "queries": [ [ { "index": 0, "terms": [ { "type": "ref", "value": [ { "type": "var", "value": "gte" } ] }, { "type": "number", "value": 4 }, { "type": "ref", "value": [ { "type": "var", "value": "data" }, { "type": "string", "value": "reports" }, { "type": "var", "value": "i1" }, { "type": "string", "value": "clearance_level" } ] } ] } ] ] } } ``` -------------------------------- ### Compile API Example Request Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/rest-api.md An example HTTP request to the Compile API for partial evaluation. ```http POST /v1/compile HTTP/1.1 Content-Type: application/json ``` ```json { "query": "data.example.allow == true", "input": { "subject": { "clearance_level": 4 } }, "options": { "disableInlining": [] }, "unknowns": [ "data.reports" ] } ``` -------------------------------- ### Build an Optimized Bundle with Entrypoint Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/management-bundles/index.md Optimize a bundle by specifying the `--optimize` flag and defining an entrypoint using the `--entrypoint` flag. ```console opa build -b foo/ --optimize=1 --entrypoint authz/allow ``` -------------------------------- ### Run OPA with US Configuration Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/management-discovery.md Command to run OPA with the specified configuration file. This will initiate the bundle download process. ```bash opa run -s -c opa-config.yaml ``` -------------------------------- ### Example JSON Document for Partitioning Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/storage.md Illustrates how a sample JSON document is structured and how different partitioning strategies affect the resulting keys and values stored in the key-value store. ```json { "users": { "alice": { "roles": ["admin"] }, "bob": { "roles": ["viewer"] } } } ``` -------------------------------- ### Start Minikube Tunnel Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/envoy/tutorial-istio.md Start a Minikube tunnel to send traffic to your Istio Ingress Gateway. ```bash minikube tunnel ``` -------------------------------- ### Import Go SDK Package Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/integration.md Import the SDK package to start using OPA within your Go programs. ```go import "github.com/open-policy-agent/opa/v1/sdk" ``` -------------------------------- ### Custom Annotation Example Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/policy-language.md Provides an example of the 'custom' metadata annotation for storing arbitrary user-defined data. ```rego # METADATA # custom: # my_int: 42 # my_string: Some text # my_bool: true # my_list: # - a # - b # my_map: # a: 1 # b: 2 allow if { ... } ``` -------------------------------- ### Build and Evaluate Wasm Policy from Bundle Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/management-bundles/index.md Shows how to build a Wasm binary from a Rego policy within a bundle and then evaluate it using `opa eval`. ```bash $ cat -p bundle/http/example/authz/authz.rego package http.example.authz allow := true $ opa build -t wasm -e http/example/authz/allow bundle $ tar tzf bundle.tar.gz /data.json /bundle/http/example/authz/authz.rego /policy.wasm /.manifest $ opa eval -b bundle.tar.gz data --format=raw {"http":{"example":{"authz":{"allow":true}}}} ``` -------------------------------- ### Example AdmissionReview Response Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/kubernetes/primer.md An example AdmissionReview response from OPA, indicating a denied request with a specific reason. ```yaml apiVersion: admission.k8s.io/v1 kind: AdmissionReview response: uid: 8d836dfd-e0c0-4490-93ba-85ed4a04261e allowed: false status: message: "image fails to come from trusted registry: nginx" ``` -------------------------------- ### Verify OPA Build Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/contrib-development.md After a successful build, verify the OPA binary by running it. Replace and with your system's operating system and architecture. ```bash ./opa__ run ``` -------------------------------- ### Example API Response for Bundles Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/ocp/guide-deploy-as-a-service.md This is an example of the JSON output you can expect when retrieving bundles from the OCP API. ```json { "result": [ { "object_storage": { "aws": { "bucket": "my-aws-bucket-name", "key": "bundles/my-alpha-app/bundle.tar.gz", "region": "us-east-2" } }, "requirements": [ { "source": "my-alpha-app", "git": {} }, { "source": "my-shared-datasource", "git": {} } ] }, { "object_storage": { "filesystem": { "path": "bundles/my-beta-app/bundle.tar.gz" } }, "requirements": [ { "source": "my-beta-app", "git": {} }, { "source": "my-shared-datasource", "git": {} } ] } ] } ``` -------------------------------- ### Configure Kubectl Context for OPA Namespace Source: https://github.com/open-policy-agent/opa/blob/main/docs/docs/kubernetes/tutorial.md Sets up a kubectl context named 'opa-tutorial' to use the 'opa' namespace and then switches to this context. ```bash kubectl config set-context opa-tutorial --user minikube --cluster minikube --namespace opa kubectl config use-context opa-tutorial ```