<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alin Spinu on Medium]]></title>
        <description><![CDATA[Stories by Alin Spinu on Medium]]></description>
        <link>https://medium.com/@spinualin?source=rss-7115665c4979------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9eV4yMirpZQlv6HP.</url>
            <title>Stories by Alin Spinu on Medium</title>
            <link>https://medium.com/@spinualin?source=rss-7115665c4979------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:05:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@spinualin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Universal OPA Policies Development]]></title>
            <link>https://itnext.io/universal-opa-policies-development-a3f88226e3d5?source=rss-7115665c4979------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3f88226e3d5</guid>
            <category><![CDATA[rego]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[otomi]]></category>
            <category><![CDATA[open-policy-agent]]></category>
            <dc:creator><![CDATA[Alin Spinu]]></dc:creator>
            <pubDate>Mon, 01 Mar 2021 08:43:21 GMT</pubDate>
            <atom:updated>2021-03-01T11:58:56.659Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>A story behind the trenches of writing <a href="https://www.openpolicyagent.org/docs/latest/#rego"><strong>Rego</strong></a> files and how to unravel the cumbersome process of working with <a href="https://github.com/open-policy-agent/gatekeeper"><strong>Gatekeeper</strong></a> vs <a href="https://github.com/open-policy-agent/conftest"><strong>Conftest</strong></a> for validating Kubernetes resources.</p><p>Working with policy compliant Kubernetes clusters is on the radar for a lot of companies these days, especially if you’re walking the path towards popular certifications like <strong>ISO/IEC 27001 </strong>for<strong> </strong>Information Security Management.</p><h3>Hands-on using OPA in Otomi Container Platform</h3><p>As some of you probably already know, the kubernetes native <strong>PodSecurityPolicy</strong> resource is going to be deprecated, see <a href="https://github.com/kubernetes/kubernetes/pull/97171"><em>here</em></a><em> and </em><a href="https://docs.google.com/document/d/1VKqjUlpU888OYtIrBwidL43FOLhbmOD5tesYwmjzO4E/edit#"><em>here</em></a><em> </em>— this leaves way for external projects like <a href="https://www.openpolicyagent.org/"><strong>Open Policy Agent</strong></a><strong> </strong>to be used as the new standard for developing and enforcing policy rules.</p><p><a href="https://otomi.io/">Otomi</a> is using <strong>OPA</strong> as the standard for providing policy enforcement because of the popularity and commitment to the kubernetes community, ease of use and also for the future project development plans.</p><p>The grounds for <a href="https://otomi.io/">Otomi Container Platform</a> is to be easy to use and provide clarity for integrations, allowing developers to easily extend any platform feature and provide integrated security for everything from the ground up. — Visit <a href="https://redkubes.com/">redkubes.com</a> to find out more.</p><h3>OPA ecosystem common knowledge</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wG_jBhAiDURRft61" /><figcaption>Photo by <a href="https://unsplash.com/@elisa_cb?utm_source=medium&amp;utm_medium=referral">Elisa Calvet B.</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Decisions are handled by the means of <strong>Admission Controllers</strong> such as <strong>OPA</strong> <strong>kube-mgmt</strong> project or <a href="https://github.com/open-policy-agent/gatekeeper"><strong>Gatekeeper</strong></a><strong>,</strong> which I will touch upon in a minute, but also remember that we can validate things using <a href="https://www.openpolicyagent.org/docs/latest/#rego"><strong>Rego query</strong></a><strong> </strong>language on any plain files using static analysis tools like <a href="https://github.com/open-policy-agent/conftest"><strong>Conftest</strong></a>. The list of formats conftest supports includes but is not limited to: json, yaml, Dockerfile, INI files, XML, etc.</p><p>Here’s the problem, <a href="https://github.com/open-policy-agent/conftest"><strong>Conftest</strong></a> and <strong>Gatekeeper</strong> are on the path of diverging although they speak the same <strong>REGO</strong> language, the two disagree on some aspects.</p><h3>In-cluster vs Static resources Policy Wars</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nF5HqEa-2CiLAgw_" /><figcaption>Photo by <a href="https://unsplash.com/@jwimmerli?utm_source=medium&amp;utm_medium=referral">jean wimmerlin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Working in a policy constricted environment is like having “parental controls” turned on for unprivileged users, allowing administrators to decide what kind of resources and setup are safest for their flock of Kubernetes clusters.</p><p>From an application developer’s perspective, being denied access to deploy some resources means that he/she is not adhering to the rules imposed for that environment and should decide to find and fix the missing links in this setup.</p><p>Policy administrators/developers on the other hand, struggle with finding the correct enforcement strategies and adjusting policy parameters according to desired state or allowing certain exclusions for cases where policy enforcement does not make sense (thinking about system namespaces, cloud vendor specific namespaces, anything that should avoid intervention by default). There is no golden rule for policy adoption and you are in charge of overcoming your own mistakes if something is not right.</p><p>I will start with the simple use-case of running policy checks against any kind of YAML resource, then move forward with more details about in-cluster Kubernetes admission review objects.</p><h4>Conftest in action</h4><p>With a simple command we can test if a helm chart is violating any rules in the provided policies folder.</p><pre><strong>$ </strong>helm template stable/keycloak | conftest test --policy ./policies/   --all-namespaces -</pre><pre><strong>FAIL</strong> - Policy: container-limits - container &lt;keycloak&gt; has no resource limits<br><strong>FAIL</strong> - Policy: container-limits - container &lt;keycloak-test&gt; has no resource limits</pre><pre><strong>162 tests, 160 passed, 0 warnings, 2 failures, 0 exceptions</strong></pre><p>The generated yaml files are streamed into conftest and policies are tested one by one.</p><p>By examining the log message, we find that the <strong>container-limits</strong> policy is marking two resources as failures — now all we have to do is modify the templates to provide a “sensitive” amount of resource limits to the indicated containers and our policy checks will pass successfully! hooray..</p><p>This is pretty useful if we want to adopt new helm applications, but don’t want to deploy anything to the cluster unless it’s <em>well-examined</em> for any violations.</p><p>Conftest supports passing values to the policies using the --data option, which allows policy designers to configure different settings through parameters.</p><p><strong>Parameters</strong> can help us control any aspect of creating configurable rules for resources.</p><p>I will return to that in a moment…</p><h4>Running Gatekeeper</h4><p>Gatekeeper is becoming the new standard for implementing security policies in Kubernetes, endorsing a broad ecosystem to spread ideas.</p><p>Enforcing policy decisions works by using a validating web-hook, intercepting any request authenticated by the api-server and checking if the request payload meets requirements for the defined policy — rejecting it otherwise.</p><p>Trying to create a non-conformant resource object in Gatekeeper enabled clusters, results in an error with a message to explain the rejected request.</p><pre><strong>$</strong> helm template charts/redis | kubectl apply -f -<br>                                                                                                                                                                  <br>secret/redis created<br>configmap/redis created<br>service/redis-master created</pre><pre>Error from server (</pre><pre><strong>[denied by banned-image-tags]</strong> Policy: banned-image-tags - container &lt;redis&gt; has banned image tag &lt;latest&gt;, banned tags are {&quot;latest&quot;, &quot;master&quot;}<br><strong>[denied by psp-allowed-users]</strong> Policy: psp-allowed-users - Container redis is attempting to run as disallowed user 0. Allowed runAsUser: {&quot;rule&quot;: &quot;MustRunAsNonRoot&quot;}</pre><pre>)</pre><pre>error when creating &quot;redis/templates/redis-master-statefulset.yaml&quot;: admission webhook &quot;validation.gatekeeper.sh&quot; denied the request:</pre><pre>[...]</pre><p>As we can see, some of the resources get created, but the command fails with a denial from the admission webhook.</p><p>To make this resource valid, small tweaks to the <strong>image tag</strong> and <strong>securityContext </strong>fields will do the trick.</p><p>[more on non-root / securityContext.runAsUser … ]</p><h3>Policy Development in Gatekeeper context</h3><p>Similar to plain policy files which Conftest uses, <a href="https://github.com/open-policy-agent/gatekeeper-library"><strong>Gatekeeper policy library</strong></a><strong> </strong>works by loading into memory a collection of wrapped rego files inside kubernetes <strong>CRDs </strong>called <strong>ConstraintTemplates</strong>.</p><p>To enforce a policy for certain resource types we need to instantiate a <strong>Constraint </strong>(<strong>CR </strong>resource) which is acting like the blueprint with desired values or parameters.</p><p>Example Gatekeeper setup for Config and Constraint resources:</p><pre>--- # Gatekeeper <strong>Config</strong></pre><pre>apiVersion: config.gatekeeper.sh/v1alpha1<br>kind: Config <br>metadata: <br>  name: config <br>  namespace: gatekeeper-system <br>spec: <br>  match: <br>  - excludedNamespaces: <br>    - gatekeeper-system <br>    - kube-system <br>    processes: <br>    - &#39;*&#39; <br>sync: <br>  syncOnly: <br>  - group: &quot;&quot; <br>    kind: Pod <br>    version: v1</pre><pre>--- # ContainerLimits <strong>Constraint</strong> </pre><pre>apiVersion: constraints.gatekeeper.sh/v1beta1<br>kind: ContainerLimits<br>metadata:<br>  name: containerlimits<br>spec:<br>  match:<br>    kinds:<br>    - apiGroups:<br>        - apps<br>        - &quot;&quot;<br>      kinds:<br>        - DaemonSet<br>        - Deployment<br>        - StatefulSet<br>        - Pod<br> parameters:<br>   container-limits:<br>     enabled: false<br>     cpu: &quot;2&quot;<br>     memory: 2000Mi</pre><p>So far this looks pretty easy — we decide to enable this policy for all namespaces except for “gatekeeper-system” &amp; “kube-system” and Gatekeeper will test all our containers for resource limits.</p><p>Hold on.. Where is the definition for this policy?</p><p><strong>Rego Rules</strong> are defined in CRD files called <strong>ConstraintTemplates </strong>and they need to be deployed prior to the <strong>Constraint</strong> instance.</p><pre>--- # <strong>ConstraintTemplate</strong> for container-limits policy</pre><pre>apiVersion: templates.gatekeeper.sh/v1beta1<br>kind: ConstraintTemplate<br>metadata:  <br>  name: containerlimits  <br>spec:  <br>  crd:    <br>    spec:      <br>      names:        <br>        kind: ContainerLimits      <br>      validation:        # Schema for the `parameters` field<br>        openAPIV3Schema:          <br>...<br>targets:    <br>- target<strong>:</strong> admission.k8s.gatekeeper.sh      <br>  <strong>libs:</strong><br>    - |-<br>      package lib.utils<br>      ...<br>  <strong>rego:</strong> |-        <br>    package containerlimits<br>    ...</pre><p>To simplify the example, I’ve cut out parts of our file, but you can also view it on the <a href="https://github.com/open-policy-agent/gatekeeper-library/blob/master/library/general/containerlimits/template.yaml">Gatekeeper Library repo</a>.</p><p>The &quot;rego” property is where the actual policy definition lives and any dependency libraries can be declared in the list of &quot;libs&quot;.</p><p>We won’t go into how Rego rules for violations work now, but you can enjoy all the fun of learning a powerful query language inspired by decades old <a href="https://www.openpolicyagent.org/docs/latest/policy-language/">Datalog</a>.</p><h3>Planning for unification</h3><p>While the process of creating new policies seems to bear a lot of weight, luckily there is a simple CLI tool to speed up our work called <a href="https://github.com/plexsystems/konstraint/">Konstraint</a>.</p><p>You can define the rules in <strong>Rego files </strong>and <strong>Konstraint</strong> will wrap our policy and all dependency libraries in the necessary <strong>CRD</strong> <strong>files</strong> for Gatekeeper. Konstraint has core library functions for working with all kinds of kubernetes native objects which makes it an indispensable tool for Rego development.</p><p>OK, so this means we only care about writing <strong>Rego files</strong> and we can test them in both Gatekeeper and Conftest.</p><h4>Open issues in OPA community</h4><p>While that is true, after delving deeper into the bowels of Gatekeeper and Conftest, I found conflicting design concepts which completely ruin this unified policy development mindset.</p><p>The way you can define parameters in two libraries is different, and Gatekeeper has a restrictive parser which does not allow arbitrary imports in the rego definition.</p><p>There has been an attempt to change this hard limitation in a <a href="https://github.com/open-policy-agent/gatekeeper/issues/1046">discussion here</a>!</p><h4>Current state of unified Rego</h4><blockquote>To echo the subject once again, we are interested in reducing the boilerplate and simplify the process of developing Policies.</blockquote><blockquote>[ Same Rego == different contexts ]</blockquote><p>Working with one <strong>common set Rego policy files</strong> and use the same source code for testing “static files”, generated from CI Builds or across any “Gatekeeping context”, where objects are created via the kubernetes api.</p><p>Let’s cut to the chase, and say we already made this happen and delivered a working solution in <a href="https://otomi.io/">Otomi</a>. By using the available community tools, lots of integration work and a lot of customisation additions.</p><p>We now have a rich collection of policies and utility functions defined for our Kubernetes clusters — you can browse them in the<a href="https://github.com/redkubes/otomi-core/tree/master/policies/"> otomi-core repository</a>.</p><h4>How Istio is mutating objects in the background</h4><p>So by now, we understand all the nitty gritty details about Rego policies and Gatekeeper — but there will always be external factors, changing the state of the world and you can find yourself in a closed box situation, nowhere to go.</p><p>This situation becomes a nightmare when using <a href="https://istio.io/latest/"><strong>Istio mesh</strong></a> for networking. In reality <a href="https://istio.io/"><strong>Istio</strong></a><strong> </strong>is creating a “subspace” of resources by injecting a Sidecar container to all the pods in namespaces where service mesh communication is enabled.</p><p>This kind of container is sometimes interfering with the security <strong>Constraints</strong> design strategy.</p><h3>Otomi policy features</h3><p><em>— parameters, annotations, exclusions, baseline parameters.</em></p><p>To create some flexibility, we have further extended the policy exceptions capabilities by examining granular annotation information for every resource under analysis.</p><p>Coming back to the <strong>Parameters </strong>idea described a while back, if Policy files can read kubernetes objects (or plain static files) as raw input, why not allow certain exceptions through annotating which resources we want to skip checking, similar to the <strong>excludeNamespace</strong> option for Gatekeeper.</p><p>Rego has a rich built-in library system and is a powerful language, allowing us to easily create robust utility functions for this design.</p><p>To give an example, using the following annotations will ensure that the entire pod or certain containers from the pod will be excluded from one or more policy checks:</p><pre># Ignore Annotation for entire pod<br><strong>policy.otomi.io/ignore:</strong> psp-allowed-repos</pre><pre># Ignore Annotation for Istio sidecar based containers <br><strong>policy.otomi.io/ignore-sidecar:</strong> psp-allowed-users,psp-capabilities</pre><pre># Ignore Annotation for specific container (name=app-container)<br><strong>policy.otomi.io/ignore/app-container:</strong> banned-image-tags</pre><pre># Parameters Annotation to extend policy configuration<br><strong>policy.otomi.io/parameters.psp-allowed-repos: &#39;</strong>{&quot;repos&quot;:[&quot;*&quot;]}&#39;</pre><p>Another example of exclusion is to turn of the policy entirely by disabling it from the baseline settings:</p><pre># baseline configuration</pre><pre>policies:<br>  <strong>container-limits:</strong><br>    enabled: false<br>    cpu: &#39;2&#39;<br>    memory: 2Gi<br>  <strong>banned-image-tags:</strong><br>    enabled: false<br>    tags:<br>      - latest<br>      - master<br><strong>  psp-allowed-users:</strong><br>    enabled: true<br>    runAsUser:<br>      rule: MustRunAs<br>      ranges:<br>        - min: 1<br>          max: 65535<br> <strong> psp-allowed-repos:</strong><br>    enabled: true<br>    repos:<br>      - docker.io<br>      - gke.otomi.cloud<br>      - aks.otomi.cloud<br>      - eks.otomi.cloud</pre><p>Check out the rest of our policies collection in the<a href="https://github.com/redkubes/otomi-core/tree/master/policies/"> otomi-core repository</a>.</p><h3>Conclusion</h3><p>To pin down the state of the landscape — designing kubernetes policies is still evolving towards new heights, I can image in the near future more and more projects sharing the same policies from a registry like the <a href="https://github.com/policy-hub/policy-hub-cli">policy-hub</a>.</p><p>Having spent many hours iterating through policy definitions, I think creating a common understanding about unified Rego is the key to a sunny future.</p><p>— Happy to share my thoughts, stay tuned for <strong>Part 2.</strong></p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3f88226e3d5" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/universal-opa-policies-development-a3f88226e3d5">Universal OPA Policies Development</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>