Wilson Mar bio photo

Wilson Mar

Hello!

Email me Calendar Skype call

LinkedIn Twitter Gitter Instagram Youtube

Github Stackoverflow Pinterest

Write Rego language policies code for decision by an OPA (Open Policy Agent) within Terraform, Kubernetes, etc.

US (English)   Español (Spanish)   Français (French)   Deutsch (German)   Italiano   Português   Estonian   اَلْعَرَبِيَّةُ (Egypt Arabic)   中文 (简体) Chinese (Simplified)   日本語 Japanese   한국어 Korean

Overview

This article provides a deep-dive hands-on tour with commentary at each step along the way. NOTE: Content here are my personal opinions, and not intended to represent any employer (past or present). “PROTIP:” here highlight information I haven’t seen elsewhere on the internet because it is hard-won, little-know but significant facts based on my personal research and experience.

The Open Policy Agent (OPA, pronounced “oh-pa”), is an open-source, general-purpose (central) “engine” that makes policy decisions (separately from policy enforcement).

OPA is also pronounced by some like the Greek acclaim “oh pa!” to express enthusiasm, shock or surprise, or just after having made a mistake.

OPA and Rego was started in 2016 at Styra.com (by @sometorin) which open-sourced OPA at github.com/open-policy-agent.

The cartoon at https://www.openpolicyagent.org shows the expansiveness of OPA and Rego.

OPA is called a general purpose policy engine because it enables the answering of policy questions above as a separate concern from enforcement. OPA is used within Terraform Enterprise Cloud, Scalr Policy Enforcement for Terraform, Stackforge.com, Kubernetes Authorization, Provisioning, and Admission Control, Envoy, app microservices, CI/CD pipelines (Jenkins Job Trigger Policy Enforcement), API gateways (Flask OPA), Google Calendar, AWS CloudFormation Hook, and elsewhere.

OPA reads and processes policies written in a high-level declarative language called Rego (pronounced “ray-go”).

OPA can run within Go programs.

When applications software needs to make a policy decision, it sends a REST API query to OPA with structured data (e.g., JSON) as input. Rego was purpose-built for expressing policies over complex hierarchical data structures.

Examples of decisions OPA enables: [3:13:48]

  • Can user X do operation Y on resource Z?
  • Which annotations must be added to new Deployments?
  • Which users can SSH into production machines?
  • What invariants does workload W violate?
  • Which records should Bob be allowed to see?

  • Which users can access which resources.
  • Which times of day the system can be accessed at.

  • 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.

Rego Language written in Golang

Styra provides support and training on OPA, and the Rego language used to define policy rules.

Any language to define policies needs to be a programming language with if/then/else using variables, loops referencing arrays, functions, etc. NOTE: Rego has Python-esque import statements, no semicolons, print() functions, list comprehensions, etc. Rego extends the Datalog query language.

Vendors who use OPA and Rego include Harness and Spacelift SaaS. Spacelift built sophisticated tooling called Policy Workbench for capturing policy inputs and replaying evaluations, allowing tweaking of policies in a tight feedback loop until they reflect business needs. Unlike Terraform, Spacelift can group and filter resources to understand the architecture or look up their history to get a glimpse of the evolution of your infrastructure.

https://github.com/accurics/terrascan uses Rego policies

To create security and compliance checks on Terraform, Regula language code is processed by an OPA (Open Policy Agent).

OPA runs GitHub Actions to alert about noncompliant IaC code.

References:

  • https://www.fugue.co/blog/announcing-regula-validate-terraform-policy-compliance-with-open-policy-agent

Kubernetes

The Rego language is backed by the CNCF (Cloud-Native Foundation) and thus used in Kafka, Kubernetes, JupiterOne, etc.

OPA’s initial use case was for Kubernetes Orchestration Admission Control.

    "Declarative Authorization to Secure Kubernetes - Compliance guardrails so you can move your security from tribal knowledge to policy-as-code"

opa-all-728x424

OPA “policy enables” micro-services as a sidecar in Service Mesh/Istio for role-based fine-grained access control (VIDEO Jun 25, 2019).

opa-usage-2382x966

OPA can be initiated as a host-level daemon via SSH to ensure that container executions are performed according to rules.

VIDEO: Netflix was an early adopter for RBAC (Role-Based Access Control).

https://github.com/open-policy-agent/gatekeeper Gatekeeper - Policy Controller for Kubernetes

Questions about OPA are in the CKS (Certified Kubernetes Security Specialist) exam.

In BOOK: “Certified Kubernetes Security Specialist (CKS) Study Guide” November 2023 by Benjamin Muschko

The “AdmissionReview” sample request in the Rego Playground “fakecode”


Ways to run Rego policy code

  1. In the Rego Playground online on a browser
  2. SaaS scan online on a browser
  3. Within a local interactive terminal
  4. As a local background service listening for REST API calls from applications
  5. As a service in AWS/Azure/GCP, etc. listening for REST API calls from applications

Playground

  1. In an internet browser (Chrome), go to Sytra’s Rego Playground default “hello world” Rego policy file:

    https://play.openpolicyagent.org

    It is the simplest example, which simply outputs static text within the code to a JSON file.

  2. Each keyword is like a program, and needs to be imported. Rego has more than 150 built-in functions to compare, numbers (round), aggregates (count, min, max), arrays, sets, objects, strings, regex, glob, conversions, types (is_number), encoding, (jwt) token signing & verification, PEM certs, crypto, time, graphs, GraphQL, HTTP, AWS Request Signing, Azure net (CIDR), Debugging, Tracing, etc.

  3. Click the blue “Evaluate” button to see OUTPUT generated.

    {
    "hello": true
    }
    

    “hello” is the key (variable) and “true” is the value. true/false values are called binary data types.

    But policies can also output other data types: arbitrary data structures such as lists.

    Rego is called a declarative language so that policy authors can focus on what queries should return rather than how queries should be executed.

    “If then else” programmatic logic are carried out by keywords such as “if” are imported by statements such as:

    import future.keywords.if

    That “if” keyword can then be invoked in Rego statements such as:

    hello if input.message == "world"

    Varible key “message” is an attribute of “input”, which is a global variable bound to the data sent to OPA by Kubernetes.

    In Rego, the dot “.” operator selects keys from objects.

  4. To make it real, change </tt>hello</tt> to doit on lines 23 and 25, then press “Evaluate” again.

    The main objective of Rego programming is to create OUTPUT JSON which define whether the reader of OUTPUT should:

    a). perform an action such as “doit”, or
    b). realize the value of some condition.

    PROTIP: For each error message, create a web page to show how to fix the error.

    Enforce Tagging: first, most used policy

    PROTIP: Checking for a valid tag is often the first policy to be added to control cloud usage in resources in a shared environment (cloud by a team using Terraform).

  5. Click “Examples” at the top for a list of other starter samples.
  6. Click “Kubernetes”, then Label Existence.
  7. Click “Evaluate” to get this “deny” flag with error message output:

        "deny": [
        "Every resource must have a costcenter label"
    ]
    

    The Rego policy expects a valid value for cost center when it executes this:

    value := input.request.object.metadata.labels.costcenter
    

    PROTIP: Rather than the “value” key name, a better name may be “costcenter”.

    PROTIP: Provide to workers example standard coding of the above hierarchy in their Kubernetes yaml so that Rego validation code can find them.

    "kind": "AdmissionReview",
    "request": {
        "kind": {
            "kind": "Pod",
            "version": "v1"
        },
        "object": {
            "metadata": {
                "name": "myapp",
                "labels": {
                    "costcenter": "cccode-12345"
                }
            },
     ...
    

    REMEMBER: When adding an item to the end of a list (such as after the metadata.name), make sure a comma is added.

  8. Click “Kubernetes”, then Label Existence.

    To enable multiple policies to deny, the example makes use of double negative logic:

    deny contains msg if {
        not input.request.object.metadata.labels.costcenter
        msg := "Every resource must have a costcenter label"
    }
    

    A blog at Fugue suggests use of Augustus De Morgan’s laws (Set Theory) to write policies using the negation of a compound statement. In this silly example:

    cannot_cut_pizza {
     input.people[_].profession != "mathematician"
    }
    

    That sets up use of a double negative to make a policy that’s easier to write and understand:

    default allow = false
    allow {
      not cannot_cut_pizza
    }
    

    For a better understanding, use truth table of granular values.

    Unique across all media

    PROTIP: Define tags that are unique across all media (Slack, emails, GitHub, etc.) so that chatter about each particular policy can be aggregated together.

    Evaulation of Conditionls

  9. This example ensures that, when PUT methods are used, the user and owner are the same when value “pets” is somewhere within the path:

    allow if {
    input.method == "PUT"
    some petid
    input.path = ["pets", petid]
    input.user == input.owner
    }
    

    All the “==” must resolve to true for allow to be true.

    Reserved words

    REMEMBER: Being declarative means some petid is specified before
    input.path = [“pets”, petid]

    some is one of the Rego language’s reserved words which cannot be defined as a variable or function:

    • as
    • default
    • else
    • true, false
    • import
    • package
    • not
    • null
    • some
    • with

  10. Achieve “allow”: true by changing one email to be the same as the other email:

    {
    "method": "PUT",
    "owner": "bob@hooli.com",
    "path": [
        "pets",
        "pet113-987"
    ],
    "user": "bob@hooli.com"
    }
    

    BTW, In Real Life, emails would not be hard-coded.

In Rego, the vertical bar continues a line (like \ breaks a line in Bash script).

SaaS Terraform scan

Straya can scan Terraform or Kubernetes configuration files on-line. on their SaaS scanner

  1. Fork (the main branch of) Straya’s repo containing deliberately bad (“dummy”) Terraform and Kubernetes resources to trigger violations with a default reposcan:

    https://github.com/StyraInc/sample-scan-repository

    The example has Terraform to establish AWS resources.

    Later, consider: https://github.com/StyraInc/das-opa-samples and https://github.com/StyraInc/das-opa-samples

  2. In a browser, sign-up for a free account for their Styra DAS (Declarative Authorization Service) at

    https://www.styra.com/styra-das/

    Straya offers “free forever” scans using up to 100 rules on 4 systems. See Pricing.

  3. At your page, such as https://2lvejj.svc.styra.com/
  4. Authorize public repos for read-only.
  5. Search for “sample-scan-repository”.
  6. Click “Scan Repository”.
  7. In the Instruqt GUI, click the “>” to the right of each violation found.
  8. Analyze and resolve each finding (with others) by editing the Terraform.

  9. QUESTION: How to tell some policies to not prevent findings for some Terraform (such as “this is public”)?
  10. PROTIP: When you figure it out, review the solution with your whole team and the broader Straya/Terraform communities so they save time based on your efforts.

NOTE: There are others who also evaluate Terraform HCL statically:

  • https://github.com/terraform-linters/tflint-ruleset-opa by Kazuma Watanabe (in Tokyo, Japan)
  • HashiCorp, the company that created and maintains Terraform and its providers, offers their own cloud SaaS service and on-prem software to custom-code policies written in both Rego and their own language called “Sentinel”.
  • Regula checks infrastructure as code templates (Terraform, CloudFormation, k8s manifests) for AWS, Azure, Google Cloud, and Kubernetes
  • TFSec
  • Aqua Security


Configure Editor for Rego code

  1. See https://www.openpolicyagent.org/docs/latest/editor-and-ide-support/ by Torin Sandall, VP of Open Source at Styra (living in Vancouver).

  2. In your policy repository, add file .editorconfig to tell GitHub (and other tools) your preferences for displaying Rego language files:

    [*.rego]
    end_of_line = lf
    insert_final_newline = true
    charset = utf-8
    indent_style = tab
    indent_size = 4
    

https://github.com/tsandall/vim-rego

Visual Studio Code extension for writing Terrascan Rego policies at https://github.com/tenable/terrascan-rego-editor

Emacs major mode for OPA’s rego language at https://github.com/psibi/rego-mode

CLI bits

With 2,600 stars and 79 contributors as of October 13, 2019, https://github.com/open-policy-agent/opa/releases has releases for Mac, Linux, and Windows.

Note it not at version 1.0 yet, with 126 issues to go.

TODO: Run my script from GitHub to install all, including sample code

  • On macOS (64-bit) using Homebrew

    brew install opa

    In the response, notice it’s from https://www.openpolicyagent.org

    ==> Fetching opa
    ==> Downloading https://ghcr.io/v2/homebrew/core/opa/manifests/0.48.0
    ######################################################################## 100.0%
    ==> Downloading https://ghcr.io/v2/homebrew/core/opa/blobs/sha256:6c75b8d49cc561867cf3f49d
    ==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:6c75b
    ######################################################################## 100.0%
    ==> Pouring opa--0.48.0.arm64_monterey.bottle.tar.gz
    ==> Caveats
    zsh completions have been installed to:
    /opt/homebrew/share/zsh/site-functions
    ==> Summary
    🍺  /opt/homebrew/Cellar/opa/0.48.0: 24 files, 28.2MB
    ==> Running `brew cleanup opa`...
    Disable this behaviour by setting HOMEBREW_NO_INSTALL_CLEANUP.
    Hide these hints with HOMEBREW_NO_ENV_HINTS (see `man brew`).
     

    Alternately:

    curl -L -o opa https://openpolicyagent.org/downloads/v0.48.0/opa_darwin_amd64
     
  • On Linux (64-bit):

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

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

     curl -L -o opa_darwin_amd64 https://openpolicyagent.org/downloads/v0.48.0/opa_darwin_amd64
     curl -L -o opa_darwin_amd64.sha256 https://openpolicyagent.org/downloads/v0.48.0/opa_darwin_amd64.sha256
     shasum -c opa_darwin_amd64.sha256
     
  1. Set permissions on the OPA executable:

    chmod 755 "$(which opa)"
    

    On an macOS M1 or M2 laptop with an ARM chip, brew installs to: /opt/homebrew/bin//opa

  2. To extract just the version number (on the first line), such as “0.48.0”:

    opa version | head -n 1 | awk '{print $2}'
    

Logs

OPA has a Log service API for emitting audit logs.

OPA has a Status service API to report its service status, available from its CLI:

    
       opa check
       

OPA has a VS Code plugin for tracing, profiling.

OPA references data (in JSON)

Policy is logic applied to data.

OPA accepts policy & data from other programs via its Bundle service API.

OPA maintains both policies and data in memory (for fast access). So it operates as a host-local “cache” for policy decisions.

based on Policy definitions , with no external run-time dependencies.

https://github.com/open-policy-agent/frameworks/tree/master/constraint Enforcement Points are places where constraints can be enforced. Examples are Git hooks and Kubernetes admission controllers and audit systems.

Target is an abstract concept. It represents a coherent set of objects sharing a common identification and/or selection scheme, generic purpose, and can be analyzed in the same validation context.

Previous rules engines such as Drools were designed with a “backward chaining inference”, which was too strange and complicated. The rules were static logic.

CLI Tutorials

Take the “Terraform Policy Enforcement with OPA” to learn to use the Styra CLI and its embedded OPA to run OPA policies against your terraform plans.

https://github.com/itaysk/regogo Go package for querying arbitrary JSON by Itay Shakury (http://blog.itaysk.com/) in Aqua Security Israel

https://www.openpolicyagent.org/docs/latest/#5-try-opa-as-a-go-library

Rego Style Guide & Labs

This section is about looking at others’ Rego code which have been optimized for readability and obviousness (rather than cleverness for performance).

  1. Navigate to the folder holding sample Rego repositories obtained from GitHub:

    mkdir ~/rego
    cd /rego
    
  2. Download the Style Guide repo from Rego originators anderseknert and Charlie Egan (Developer Advocate):

    git clone https://github.com/StyraInc/rego-style-guide  --depth 1
    cd rego-style-guide
    

    Alternately, first fork the repo and clone under your GitHub user name instead of “StyraInc”.

  3. Sample Rego code for labs from Straya’s FREE Academy on Policy Authoring:

    git clone https://github.com/StyraInc/academy-samples --depth 1
    

    https://academy.styra.com/courses/opa-performance

    https://academy.styra.com/courses/microservice

Sample Rego with metadata

This example Rego file presents a standard for metadata:

# METADATA
# title: Example
# description: Example package with documentation
package example

import future.keywords.contains
import future.keywords.if

# METADATA
# title: Deny non admin users
# description: Only admin users are allowed to access these resources
# related_resources:
# - https://docs.example.com/policy/rule/E123
# custom:
#   code: 401
#   error_id: E123  
deny contains {
	"code": metadata.custom.code,
	"message": sprintf("Unauthorized due to policy rule (%s, %s)", [
		metadata.custom.error_id,
		concat(",", [ref | ref := metadata.related_resources[_].ref]),
	]),
} if {
	input.admin == false

	metadata := rego.metadata.rule()
}

https://www.openpolicyagent.org/docs/latest/policy-reference/#grammar

https://www.openpolicyagent.org/docs/latest/aws-cloudformation-hooks/

Other Rego code examples:

https://github.com/brendanjryan/ccheck CLI app (in Go) to apply Rego deny and warn rules against kubernetes config files, by Brendan Ryan (at Stripe)

https://cloudjourney.medium.com/rego-examples-978b1dd7c3b4

https://medium.com/@agarwalshubhi17/rego-cheat-sheet-5e25faa6eee8
by Googler <a target="_blank" href="https://www.linkedin.com/in/shubhi-agarwal-0895/">Shubhi Agarwal</a>
who has her code at https://github.com/shubhi-8/RegoCheatSheetExamples

https://docs.datadoghq.com/security/cloud_security_management/guide/writing_rego_rules/

https://snyk.io/blog/opa-rego-usage-for-policy-as-code/ describes APPLICATION POLICIES

  • Certain web service contexts can only be accessed by internal users.
  • Regional features will only be shown for requests by users with IP addresses in the same geo-location.
  • Transactions over certain amounts are only allowed for users with managerial roles.

BUILD & DEPLOY POLICIES:

  • All open source application libraries must use one of the approved licenses.
  • All container images must be pulled from specific registries.
  • No Kubernetes Pod should ever run in Privileged mode.
  • A ServiceAccount’s default token should not be auto-mounted into a container.

Pipeline

https://github.com/anderseknert/pre-commit-opa Pre-commit git hooks for Open Policy Agent (OPA) and Rego development

Add to your pipeline:

  1. Reformat:

    opa fmt

  2. Check for common mistakes like redundant imports, unused variables, etc.:

    opa check –strict path/to/polices

Basic OPA CLI commands

  1. Get a menu of all that opa program can do:

    opa
    An open source project to policy-enable your service.
     
    Usage:
      opa [command]
     
    Available Commands:
      bench        Benchmark a Rego query
      build        Build an OPA bundle
      capabilities Print the capabilities of OPA
      check        Check Rego source files
      completion   Generate the autocompletion script for the specified shell
      deps         Analyze Rego query dependencies
      eval         Evaluate a Rego query
      exec         Execute against input files
      fmt          Format Rego source files
      help         Help about any command
      inspect      Inspect OPA bundle(s)
      parse        Parse Rego source file
      run          Start OPA in interactive or server mode
      sign         Generate an OPA bundle signature
      test         Execute Rego test cases
      version      Print the version of OPA
     
    Flags:
      -h, --help   help for opa
     
    Use "opa [command] --help" for more information about a command.
    
  2. Expand the Terminal window to see the wide menu of flags:

    opa eval
    Error: specify query argument or --stdin
    Usage:
      opa eval  [flags]
     
    Flags:
      -b, --bundle string                                     set bundle file(s) or directory path(s). This flag can be repeated.
       --capabilities string                               set capabilities version or capabilities.json file path
       --count int                                         number of times to repeat each benchmark (default 1)
       --coverage                                          report coverage
      -d, --data string                                       set policy or data file(s). This flag can be repeated.
       --disable-early-exit                                disable 'early exit' optimizations
       --disable-indexing                                  disable indexing optimizations
       --disable-inlining stringArray                      set paths of documents to exclude from inlining
      -e, --entrypoint string                                 set slash separated entrypoint path
       --explain {off,full,notes,fails,debug}              enable query explanations (default off)
       --fail                                              exits with non-zero exit code on undefined/empty result and errors
       --fail-defined                                      exits with non-zero exit code on defined/non-empty result and errors
      -f, --format {json,values,bindings,pretty,source,raw}   set output format (default json)
      -h, --help                                              help for eval
       --ignore strings                                    set file and directory names to ignore during loading (e.g., '.*' excludes hidden files)
       --import string                                     set query import(s). This flag can be repeated.
      -i, --input string                                      set input file path
       --instrument                                        enable query instrumentation metrics (implies --metrics)
       --metrics                                           report query performance metrics
      -O, --optimize int                                      set optimization level
       --package string                                    set query package
      -p, --partial                                           perform partial evaluation
       --pretty-limit int                                  set limit after which pretty output gets truncated (default 80)
       --profile                                           perform expression profiling
       --profile-limit int                                 set number of profiling results to show (default 10)
       --profile-sort string                               set sort order of expression profiler results
      -s, --schema string                                     set schema file path or directory path
       --shallow-inlining                                  disable inlining of rules that depend on unknowns
       --show-builtin-errors                               collect and return all encountered built-in errors, built in errors are not fatal
       --stdin                                             read query from stdin
      -I, --stdin-input                                       read input document from stdin
      -S, --strict                                            enable compiler strict mode
       --strict-builtin-errors                             treat the first built-in function error encountered as fatal
      -t, --target {rego,wasm}                                set the runtime to exercise (default rego)
       --timeout duration                                  set eval timeout (default unlimited)
      -u, --unknowns stringArray                              set paths to treat as unknown during partial evaluation (default [input])
    </pre>
    
    

In-memory

OPA maintains both policies and data in memory (for fast access). So it operates as a host-local “cache” for policy decisions.


Start OPA Server Mode

opa can run in interactive mode, but most use OPA as a service listening for API calls.

  1. To run the opa executable in server mode, configured to use any decision as the default decision:

    opa --server --set=default_decision=example/allow
    

    Alternately, to process a single Rego file and exit:

    opa --server --set=default_decision=example/allow \
    service1.rego
    

    REMEMBER: By default OPA listens for HTTP connections on 0.0.0.0:8181

  2. View process

    ps -al | grep opa
    
  3. Push data file to the server:

    curl -X PUT http://localhost:8181/v1/data/{myData} --data-binary @{myData}.json
    
  4. Push rego file to the server

curl -X PUT http://localhost:8181/v1/policies/{mypolicy} --data-binary @{mypolicy}.rego
    
  1. Execute the rules

    curl --location --request POST 'http://localhost:8181/v1/data/$policyPath$/{ruleName}' \
     --header 'Content-Type: text/plain' \
     --data-raw '{Input_Json}'
     
  2. Pretend to be an application program:

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

See https://www.openpolicyagent.org/docs/latest/policy-testing/


Search for Rego on GitHub

The PolicyHub CLI makes policies searchable by providing a standard format for policy creators to share their policies. Users of the CLI can search our registry for specific tags or descriptions contributed.

Here are GitHub repositories containing Rego code:

  • Red Hat’s Gatekeeper (Kubernetes Operator) keeps its Rego policies at

    https://github.com/redhat-cop/rego-policies/blob/master/POLICIES.md

  • Dockerfile security checker

    https://github.com/madhuakula/docker-security-checker

  • An OPA library to develop IT Control policies, for the IBM Cloud

    https://github.com/IBM-Cloud/terraform-opa-ibm

  • Evaluate the RBAC permissions of Kubernetes identities through policies written in Rego

    https://github.com/PaloAltoNetworks/rbac-police

  • Golang library which provides functionality to evaluate GCP resources against Rego-based policies

    https://github.com/GoogleCloudPlatform/config-validator

  • https://github.com/madhuakula/docker-security-checker

  • https://github.com/google/gke-policy-automation

  • https://github.com/kubescape/regolibrary contains the controls Kubescape uses for detecting misconfigurations in Kubernetes manifests.

Other programs

OPA accepts policy & data from other programs via its Bundle service API.

based on Policy definitions , with no external run-time dependencies.

https://github.com/open-policy-agent/frameworks/tree/master/constraint Enforcement Points are places where constraints can be enforced. Examples are Git hooks and Kubernetes admission controllers and audit systems.

Target is an abstract concept. It represents a coherent set of objects sharing a common identification and/or selection scheme, generic purpose, and can be analyzed in the same validation context.

Previous rules engines such as Drools were designed with a “backward chaining inference”, which was too strange and complicated. The rules were static logic.

Rego rule declarations

But OPA’s rules are dynamic over time and defined using a declarative syntax rather than a programmatic if-then-else logic referencing object classes, methods, and binary trees.

OPA declares Policy definitions in “Rego” text format, so they can be stored in GitHub.

OPA can respond with not just Boolean yes/no but also collections of values such as numbers (e.g. rate-limits), strings (e.g. hostnames), arrays (e.g. servers), or dictionaries (microservice route-mappings). For more examples, see the Open Policy Agent tutorials.

It’s the policy author that knows what the data means in the real world and writes logic to make a policy decision.

impact analysis?

In Terraform Cloud

References

https://www.openpolicyagent.org/docs/latest/

https://www.openpolicyagent.org/docs/latest/policy-language

OPA was originally created by Styra and is a graduated project in the Cloud Native Computing Foundation (CNCF) landscape.

BOOK: “Hacking Kubernetes” October 2021 by Andrew Martin and Michael Hausenblas

BOOK: “Opa: Up and Running” February 2013 by Henri Binsztok, Adam Koprowski, Ida Swarczewskaja

7h 50m Audiobook: “The OPA! Way” November 2014 by Alex Pattakos and Elaine Dundon


Social

The Styra-run @openpolicyagent Twitter account had 1,268 followers as of October 13, 2019.

Organizations providing speakers at the Styra-run OPA Summit (#OPASummit2019) colocated (12–5PM Nov 18, 2019) at Kubecon San Diego also include Pinterest, TripAdvisor, Atlassian, Chef, Capital One.

In March 2018, OPA was donated to the CNCF (Cloud Native Computing Foundation), which also manages Kubernetes and Istio.

References

[1] VIDEO: “Securing Kubernetes with Admission Control” with Ash Narka, #ashtalk SSE (Styra, Inc.) May 17, 2019 [25:28]

[2] VIDEO: Securing Kubernetes With Admission Controllers - Dave Strebel, Microsoft CNCF [Cloud Native Computing Foundation]

[3] https://www.youtube.com/watch?v=XEHeexPpgrA OPA: The Cloud Native Policy Engine</a> May 4, 2018</a> by Torin Sandall of Styra (Intermediate Skill Level)

Shanghai, November 14-15 (http://bit.ly/kccncchina18).

https://spacelift.io/blog/what-is-open-policy-agent-and-how-it-works

More on Security

This is one of a series on Security in DevSecOps:

  1. SOC2
  2. CAIQ (Consensus Assessment Initiative Questionnaire) by cloud vendors

  3. Git Signing
  4. Hashicorp Vault
  5. OPA

  6. WebGoat known insecure PHP app and vulnerability scanners
  7. Test for OWASP using ZAP on the Broken Web App

  8. Encrypt all the things

  9. AWS Security (certification exam)
  10. AWS IAM (Identity and Access Management)

  11. Cyber Security
  12. Security certifications