GithubHelp home page GithubHelp logo

plexsystems / konstraint Goto Github PK

View Code? Open in Web Editor NEW
373.0 8.0 45.0 1.29 MB

A policy management tool for interacting with Gatekeeper

License: MIT License

Go 92.43% Makefile 3.66% Shell 1.07% Open Policy Agent 1.21% Dockerfile 0.54% Smarty 1.10%
gatekeeper policy conftest opa kubernetes rego open-policy-agent

konstraint's People

Contributors

aalexandru avatar anderseknert avatar artis3n avatar delamart avatar dependabot[bot] avatar dulltz avatar fukubaka0825 avatar garethahealy avatar hnts avatar jalseth avatar josh-reed avatar jpreese avatar kitagry avatar mattes83 avatar minchao avatar mrueg avatar prasadkatti avatar rawc0der avatar rjbrown57 avatar stek29 avatar szarny avatar tillepille avatar twendt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

konstraint's Issues

Weird out-of-order creation of policy documentation

I don't think this is a bug with Konstraint, more of a user error or possible feature request. I'd like the documentation generated from our policies to be alphabetized - by either the title or by the policy ID if that is provided, since Konstraint auto-adds the policyID to the title when generating the documentation.

Right now, I have several policies under different directories and they generate into this, which is confusing to look at.
image

I would like that to be:

Violations
- RALLY-0001
- RALLY-0002
- RALLY-0004
Warnings
- RALLY-0003

Any way I can make that happen? If not, what type of feature request is this? :)

Only imports from the policy are included in the generated ConstraintTemplate.

Now that we have split the k8s library into multiple libraries, it is more likely that someone may import a library that depends on another library which means we could be generating invalid resources. For example, if a policy imports lib.workloads and uses containers[container] or similar but does not import lib.core, the policy will not work when Gatekeeper attempts to load it.

We should recursively parse the imports of the policies and libraries until all are located.

libs get wrapped

Hi, some of our templates get libs that are minified, resulting in long strings that we can't post-process.

My assumption is that konstraint shrinks output based on some limit.

Example:

  - libs:
    - "package lib.core\n\ndefault is_gatekeeper = false\n\nis_gatekeeper {\n\thas_field(input,
      \"review\")\n\thas_field(input.review, \"object\")\n}\n\nresource = input.review.object
      {\n\tis_gatekeeper\n}\n\nresource = input {\n\tnot is_gatekeeper\n}\n\nreview
      = input.review {\n\tis_gatekeeper\n}\n\nreview = {\"object\": resource, \"kind\":
      {\"group\": group, \"kind\": kind, \"version\": version}} {\n\tnot is_gatekeeper\n}\n\nparameters
      = input.parameters {\n\ttrace(sprintf(\"has input.parameters: %v\", [input.parameters]))\n\tis_gatekeeper\n}\n\nopa_upstream_bug_1046
      := true\n\nparameters = data.parameters {\n\ttrace(sprintf(\"has data.parameters:
      %v\", [data.parameters]))\n\tnot is_gatekeeper\n}\n\nformat(msg) = {\"msg\":
      msg}\n\nformat_with_id(msg, id) = msg_fmt {\n\tmsg_fmt := {\n\t\t\"msg\": sprintf(\"%s:
      %s\", [id, msg]),\n\t\t\"details\": {\"policyID\": id},\n\t}\n}\n\napiVersion
      := resource.apiVersion\n\nname := resource.metadata.name\n\ngv := split(apiVersion,
      \"/\")\n\ngroup = gv[0] {\n\tcontains(apiVersion, \"/\")\n}\n\ngroup = \"core\"
      {\n\tnot contains(apiVersion, \"/\")\n}\n\nversion := gv[minus(count(gv), 1)]\n\nkind
      := resource.kind\n\nlabels := resource.metadata.labels\n\nannotations := resource.metadata.annotations\n\nhas_field(obj,
      field) {\n\tnot object.get(obj, field, \"N_DEFINED\") == \"N_DEFINED\"\n}\n\nmissing_field(obj,
      field) {\n\tobj[field] == \"\"\n}\n\nmissing_field(obj, field) {\n\tnot has_field(obj,
      field)\n}"

If that is the case we would like to turn off this behaviour as we have the need to strip out certain lines because those interfere with gatekeeper parser which does not allow data.parameters refs to pass. (See issue open-policy-agent/gatekeeper#1046). If you need this shrinking behaviour, then please allow us to run it a as a post-step.

Feature Request: annotating rule for namespaces/excludedNamespaces

Like #93, I'd like to support annotating rules that generate spec.match.namespaces and spec.match.excludedNamespaces.

Examples

# @namespaces kube-system gatekeeper-system
package foo

import data.lib.core
...

โ†“

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: Foo
metadata:
  name: foo
spec:
  match:
    namespaces:
      - kube-system
      - gatekeeper-system

# @ excludednamespaces kube-system gatekeeper-system
package foo

import data.lib.core
...

โ†“

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: Foo
metadata:
  name: foo
spec:
  match:
    excludedNamespaces:
      - kube-system
      - gatekeeper-system

Question: What value does the current doc format give?

The current doc format is as follows:

API Groups Kinds Description
apps, core DaemonSet, Deployment, StatefulSet, Pod Container images can not use the latest tag.
apps, core DaemonSet, Deployment, StatefulSet, Pod EmptyDir volume mounts must specify a size limit.

But am not sure what value that gives you, since that table could be interpreted as:

All of these API Groups, support all of these Kinds. i.e.:
apps -> DaemonSet, Deployment, StatefulSet, Pod
core -> DaemonSet, Deployment, StatefulSet, Podcore

Which is not true. Wouldnt it be easier if the table just listed the whole apiVersion/kind? i.e.:

API Groups/Kinds Description
apps/DaemonSet, apps/Deployment, apps/StatefulSet, core/Pod Container images can not use the latest tag.
apps/DaemonSet, apps/Deployment, apps/StatefulSet, core/Pod EmptyDir volume mounts must specify a size limit.

This is just my view, maybe I am missing the benefit of splitting them out.

data.parameters generates errors while loading the YAML template in Gatekeeper

The data.parameters generates an error while loading the generated YAML template in Gatekeeper.

parameters = data.parameters {
not is_gatekeeper
}

- errors:
    - code: create_error
      message: 'check refs failed on module {libs.admission.k8s.gatekeeper.sh.K8sValidPodDisruptionBudget["lib_0"]}:
        disallowed ref data.parameters'

I think we need to update to use replicate data

Bug: Comments interpreted in policy documentation generation

I have a

# @title ATitle
#
# A paragraph description
#
# @enforcement deny

setup on a rego policy but Konstraint is adding the comments inside my rego to the policy documentation, which I do not want.

For example:

image

This comment is included in the generated policy documentation:

image

That seems like a bug

Reproduce:

  • Write an arbitrary policy
  • Include the Konstraint policy doc stuff above the package declaration
  • Add a # comment inside the rego code
  • Observe the generated policy markdown includes the comment in the documentation description.

Error: parse policies: imported library not found

I am trying to create the constraints for:

But, hitting an issue:

$ konstraint create
Error: parse policies: imported library not found: data.utils.kubernetes
Usage:
  konstraint create <dir> [flags]

Flags:
  -h, --help   help for create

Global Flags:
      --ignore string   A regex pattern which can be used for ignoring directories and files (default "^$")
      --lib string      The name of the folder where the Rego librarie(s) are (default "lib")

From the error message, it seems to be complaining about:

which lives here:

conftest doesn't complain, so I presume its valid rego. Any idea?

Fix indentation of generated constraints and templates

Generated constraints and templates should be indented so that they pass linting. Currently, they fail with:

yamllint .
./constraint.yaml
  1:1       warning  missing document start "---"  (document-start)
  8:5       error    wrong indentation: expected 6 but found 4  (indentation)
  9:7       error    wrong indentation: expected 8 but found 6  (indentation)
  12:7      error    wrong indentation: expected 8 but found 6  (indentation)

./template.yaml
  1:1       warning  missing document start "---"  (document-start)
  12:3      error    wrong indentation: expected 4 but found 2  (indentation)
  13:5      error    wrong indentation: expected 6 but found 4  (indentation)
  75:81     error    line too long (110 > 80 characters)  (line-length)
  131:81    error    line too long (139 > 80 characters)  (line-length)

konstraint create fails on pseudo-import "future.keywords.in"

When running "konstraint create my-policy-dir," I get the following error:

Error: get violations: parse directory: getRecursiveImportPaths: import not found: future.keywords.in

Several of my .rego files contain "import future.keywords.in" which is necessary to enable the Rego keyword "in". However, konstraint appears to be treating that as an actual import and is looking for a file. As I understand it, there is no file to be found, just a change of internal state in Opa's parsing of Rego input.

https://www.openpolicyagent.org/docs/latest/policy-language/#membership-and-iteration-in documents that Opa uses the notation "import future.keywords" in this way. That link also shows a sample Rego file that uses the "in" keyword. I believe konstraint needs to handle this without generating an error.

Thanks.

No constraint.yaml created

Hi,

Just started using konstraint abit as I'm evaluating OPA. I'm having a hard time gettinng these constraint.yaml files to be created when creating the policies. I get the constraint template, but not the constraint.yaml file.

But I've tested building the policy files you have in this repo under examples/ and that seems to work fine.

I haven't really done anything special, I've just added some kinds to the policy.
# @kinds apps/DaemonSet apps/Deployment apps/StatefulSet core/Pod

but this does not generate the constraint.yaml file.

Support parsing policyID from the Rego

Many teams assign a unique policy identifier to each policy which ties to their best practices, hardening standards, and other guidance documentation. We should support parsing this from the Rego and including it in the generated documentation. Additionally, we may want to support adding it in the details object so it can easily be programmatically parsed during policy testing and deployment.

Parameters issue.

Greetings,,

I want to have a ContraintTemplate with the following parameters:

  parameters:
    limits:
      cpu: "4"
      memory: "8Gi"
    requests:
      cpu: "2"
      memory: "4Gi"

I have tried adding at the top of my rego file:

# @parameter limits.cpu string
# @parameter limits.memory string
# @parameter rquests.cpu string
# @parameter requests.memory string

But I get the following error:
Error: get violations: parse directory: count of @parameter tags does not match parameter count

Perhaps I am doing something wrong... am I on the right track with this?

Not able to find flag for --partial-constriants in latest release version 0.17.0

Hi @jalseth In relation to this #225 PR, I am not able to find the option for --partial-constriants flag while using konstraint create cmd. I am using 0.17.0 version.

$ konstraint --version
Version: 0.17.0

konstraint create --help
Create Gatekeeper constraints from Rego policies

Usage:
  konstraint create <dir> [flags]

Examples:
Create constraints in the same directories as the policies
        konstraint create examples

Save the constraints in a specific directory
        konstraint create examples --output generated-constraints

Create constraints with the Gatekeeper enforcement action set to dryrun
        konstraint create examples --dryrun

Flags:
      --constraint-template-version string   Set the version of ConstraintTemplates (default "v1beta1")
  -d, --dryrun                               Sets the enforcement action of the constraints to dryrun, overriding the @enforcement tag
  -h, --help                                 help for create
  -o, --output string                        Specify an output directory for the Gatekeeper resources
      --skip-constraints                     Skip generation of constraints

Is this something missing from the target build version?

Make konstraint doc allow to skip rego code in output

So there's this cool konstraint doc command, but what if target user do not need rego code in docs? It would nice to be still able to generate docs from metadata, but just skip rego code. Do you guys think it's possible?

Bug: .spec.match.kinds[]kinds is duplicated when the same kinds are given

When specify multi targets with a same kind at @kinds annotating rule, konstraint creates duplicated item at constraint.spec.match.kinds[]kinds.

Example

# @title example
#
# @kinds networking.k8s.io/Ingress extensions/Ingress
package example
...

From the above rego code, konstraint create generates the following YAML.

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: Example
metadata:
  name: example
spec:
  match:
    kinds:
    - apiGroups:
      - networking.k8s.io
      - extensions
      kinds:
      - Ingress
      - Ingress # ๐Ÿ‘ˆ duplicated item

Expected behavior

When a duplicate kind is specified, I want to remove the duplicate from the example.spec.match.kinds[]kinds.

Request: Add type of rego to docs

It would be nice if the docs included the type of constraint being violented in the docs, i.e.: if it's a deny/warn/etc

i.e.:

Type API Groups Kinds Description
DENY apps, core DaemonSet, Deployment, StatefulSet, Pod Container images can not use the latest tag.
WARN apps, core DaemonSet, Deployment, StatefulSet, Pod Containers must have resource constraints specified.

Ideally, this would be worked out from the rego and not from the comment.

`doc` output is not consistently in the same order

The order of the policies in the doc command not consistent, causing the documentation to be slightly different each time. This is because we are iterating over a map which does not necessarily happen in the same order. This was introduced in #20.

We can either sort the keys first, or switch from passing around a map[string]string to a struct with the file name and contents.

Feature Request: Add support for extracting parameters from Annotations

Currently the library allows extracting parameters from Gatekeeper's Constraint resources using input.parameters and data passed to Conftest tool as data.parameters fields.
I would like to propose adding an extra layer of parameterisation, which can be simply extracted from the resource level annotations.

Example usage for annotation level parameters:

kind: Deployment
metadata:
  name: MyDeployment
spec:
....
  template:
    metadata:
      annotations:
          konstraint.policies/parameters.policyID: '{"json":"custom-data"}'
          konstraint.policies/ignore: "policyID1,policyID2"
import data.lib.parameters
parameters = parameters.parameters(policyID)

Using policyID as a key here, because multiple policies can have the same input and will keep the data in distinct values for each policy.

This feature serves multiple use-cases, one which is very interesting is allowing to exclude policies from evaluation if there is a kill switch in the annotations/parameters.
I am submitting a corresponding PR and am open to respond to any reviews and adjust code accordingly.

constraint not generated

I'm using konstraint create to generate template.yaml and constraint.yaml from a simple rego file.

# @enforcement deny
# @kinds core/Namespace
# @parameter protected array string
package gnamespaceprotect

violation[{"msg": msg, "details": {}}] {
    input.review.operation == "DELETE"
    input.review.object.metadata.name == input.parameters.protected[_]
    msg := "This namespace is protected and cannot be deleted"
}

The resulting template.yaml is fine

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  creationTimestamp: null
  name: namespaceprotect
spec:
  crd:
    spec:
      names:
        kind: NamespaceProtect
      validation:
        openAPIV3Schema:
          properties:
            protected:
              items:
                type: string
              type: array
  targets:
  - rego: |-
      package gnamespaceprotect

      violation[{"msg": msg, "details": {}}] {
          input.review.operation == "DELETE"
          input.review.object.metadata.name == input.parameters.protected[_]
          msg := "This namespace is protected and cannot be deleted"
      }
    target: admission.k8s.gatekeeper.sh
status: {}

Sadly no constaint.yaml is generated.
The create command completes without any error... Am I missing something obvious?

Re-generation of existing ConstraintTemplates and Constraints overwrites fields

Hello, great tool and idea btw.

When running konstraint create on rules that already have a template.yaml and a constraint.yaml, certain fields are removed or overwritten, namely

  • the validation.openAPIV3Schema field for templates
  • the spec.match.kinds and spec.parameters fields for constraints

It'd be great if these fields could be left alone.

A cursory glance at getConstraintTemplate in create.go seems to show the validation field isn't included in the schema, though I'm a bit uncertain what's going on with getConstraint.

I've yet to write any golang, but I might be able to take a stab at a PR for this maybe next week or the following once work gets less busy

Generated constraints are incompatible with Gatekeeper-3.6.0

Gatekeeper-3.6.0 included the v1 version of ConstraintTemplate which requires the Constraint schema to be structural (see https://open-policy-agent.github.io/gatekeeper/website/docs/constrainttemplates/).

As Konstraint currently only produces v1beta1 compatible templates, these result on the following Violations on the CRD itself:

  - lastTransitionTime: "2021-10-29T09:32:06Z"
    message: '[spec.validation.openAPIV3Schema.properties[metadata].type: Invalid
      value: "": must be object, spec.validation.openAPIV3Schema.properties[metadata].type:
      Required value: must not be empty for specified object fields, spec.validation.openAPIV3Schema.properties[spec].properties[match].properties[kinds].items.properties[apiGroups].type:
      Required value: must not be empty for specified object fields, spec.validation.openAPIV3Schema.properties[spec].properties[match].properties[kinds].items.properties[kinds].type:
      Required value: must not be empty for specified object fields, spec.validation.openAPIV3Schema.properties[spec].properties[match].properties[kinds].items.type:
      Required value: must not be empty for specified array items, spec.validation.openAPIV3Schema.properties[spec].properties[match].properties[labelSelector].properties[matchExpressions].items.type:
      Required value: must not be empty for specified array items, spec.validation.openAPIV3Schema.properties[spec].properties[match].properties[labelSelector].type:
      Required value: must not be empty for specified object fields, spec.validation.openAPIV3Schema.properties[spec].properties[match].properties[namespaceSelector].properties[matchExpressions].items.type:
      Required value: must not be empty for specified array items, spec.validation.openAPIV3Schema.properties[spec].properties[match].properties[namespaceSelector].type:
      Required value: must not be empty for specified object fields, spec.validation.openAPIV3Schema.properties[spec].properties[match].type:
      Required value: must not be empty for specified object fields, spec.validation.openAPIV3Schema.properties[spec].type:
      Required value: must not be empty for specified object fields, spec.validation.openAPIV3Schema.type:
      Required value: must not be empty at the root]'
    reason: Violations
    status: "True"
    type: NonStructuralSchema

Convert doc generator to use template

The current documentation generating just builds up a string. While effective, it would serve us better to use templates as more and more documentation configurations are requested.

Publish a Docker Image

Publishing a Docker image can make it easier to get started with Konstraint and use it in certain deployment flows where Go is not available or the version of Go available is not the version that we test with.

Better error message on missing library

When using the create command on a specific directory, and a rego policy in that directory depends on a library that is in a parent directory, the error states:

Error: get libraries: load files: walk path: lstat : no such file or directory

It took a moment to figure out what was going on--we should expand on this and say which library it could not find.

Core kind do not get any kind

In core.rego

ressource = input.review.object
kind = resource.kind

But the kind for a gatekeeper object is

{
    "kind": "AdmissionReview",
    "parameters": {},
    "review": {
        "kind": {
            "kind": "Pod",
            "version": "v1"
        },
        "object": {
            "metadata": {
                "name": "myapp",
                "namespace": ""
            },
            "spec": {
                "containers": []
            }
        }
    }
}

So kind should be

kind = input.review.kind.kind

Add templating support

It would be awesome if we could have a user supplied template for constraints and constrainttemplate.

Mainly this would provide the ability to add custom labels and annotations (which could be added here as well) but probably other settings and variables could be transferred as well.

doc generation expects only 1 slash in the api/kind string

The doc generation expects there to be only 1 slash in the api/kind:

  • for _, kindGroup := range kindGroups {
    kindTokens := strings.Split(kindGroup, "/")
    if !contains(apiGroups, kindTokens[0]) {
    apiGroups = append(apiGroups, kindTokens[0])
    }
    kinds = append(kinds, kindTokens[1])
    }

But this is not true for most projects, i.e.: istio

Comment:

# Test
# @Kinds networking.istio.io/v1alpha3/VirtualService

Generates:

|API Groups|Kinds|Description|
|---|---|---|
|networking.istio.io|v1alpha3|Test|

Parameter abstraction causes constraint validation errors

With the parameter abstraction introduced recently #80 I get validation errors when using kpt's gatekeeper validation function to validate a set of manifests validate constraints:

kpt fn run ./configs --image gcr.io/kpt-functions/gatekeeper-validate
Error: check refs failed on module {libs.admission.k8s.gatekeeper.sh.PodDenyHostNetwork["lib_0"]}: disallowed ref data.parameters
error: exit status 1

I'm not sure if this is konstraint's responsibility (I'm very new to rego, so I don't really understand why the error is happening), but I thought it was as it seems to break backwards compatibility.

Feature request: Add support for policies that use Gatekeeper's input parameters

Hey Guys,
sorry for bothering you with this question.

If I currently have something like this here.
How is it possible to have those parameters defined in a costrainttemplate?

package blacklist_label

default deny = false
default system_regex = "^system:.*" 
system_regex = input.parameters.system_regex

default system_auth = "^system:authenticated$"

label_regex := input.parameters.label_regex

matching_label_keys = value {
    some key
    value := count({key | _ = input.review.object.metadata.labels[key]; re_match(label_regex, key)})
}

user_is_authenticated = value {
    value := count({group | group = input.review.userInfo.groups[_]; re_match(system_auth, group)})
}

# user_is_system is true if regex matches...
user_is_system = value {
    value := count({group | group = input.review.userInfo.groups[_]; re_match(system_regex, group)})
}

deny {
    matching_label_keys > 0
    not user_is_system > 0
}

violation[{"msg": msg, "details": details}] {
    deny
    details := input.review.object.metadata.labels
    msg := sprintf("Please ensure that the label key does not match the regex: %v", [label_regex])
}

The Template should generate something like this here.

---
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: blacklist_label
spec:
  crd:
    spec:
      names:
        kind: BlacklistLabel
      validation:
        # Schema for the `parameters` field
        openAPIV3Schema:
          properties:
            label_regex:
              type: string
            system_regex:
              type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |

Add logging

In some scenarios, it is useful to know what Konstraint does during its runs and the decisions it makes. This is especially useful when running Konstraint in CI to be able to troubleshoot unexpected behavior without having to attempt to replicate the issue in CI locally.

Panic when @kinds line ends in a space

If the @kinds line in the header block ends in a space, the konstraint doc command panics. This should be trimmed before splitting on the space character to avoid this.

$ konstraint doc policy -o policies.md                   
panic: runtime error: index out of range [1] with length 1

goroutine 1 [running]:
github.com/plexsystems/konstraint/internal/commands.getKindMatchers(0xc00002ea50, 0x42, 0x17d2db2, 0x6, 0x1)
        /Users/james/Code/go/pkg/mod/github.com/plexsystems/[email protected]/internal/commands/gatekeeper.go:48 +0x29c
github.com/plexsystems/konstraint/internal/commands.GetMatchersFromComments(0xc00017f9e8, 0x1, 0x1, 0x6, 0x1, 0x17d1eb8)
        /Users/james/Code/go/pkg/mod/github.com/plexsystems/[email protected]/internal/commands/gatekeeper.go:24 +0x10c
github.com/plexsystems/konstraint/internal/commands.getHeader(0xc000154600, 0x6, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ...)
        /Users/james/Code/go/pkg/mod/github.com/plexsystems/[email protected]/internal/commands/document.go:159 +0x590
github.com/plexsystems/konstraint/internal/commands.getDocumentation(0x7ffeefbff967, 0x6, 0x17d1e95, 0x1, 0xb, 0xc000192f60, 0x17d22ff)
        /Users/james/Code/go/pkg/mod/github.com/plexsystems/[email protected]/internal/commands/document.go:100 +0x1de
github.com/plexsystems/konstraint/internal/commands.runDocCommand(0x7ffeefbff967, 0x6, 0x3, 0x18b3a20)
        /Users/james/Code/go/pkg/mod/github.com/plexsystems/[email protected]/internal/commands/document.go:70 +0x79
github.com/plexsystems/konstraint/internal/commands.newDocCommand.func1(0xc0001aa000, 0xc0001931a0, 0x1, 0x3, 0x0, 0x0)
        /Users/james/Code/go/pkg/mod/github.com/plexsystems/[email protected]/internal/commands/document.go:58 +0x293
github.com/spf13/cobra.(*Command).execute(0xc0001aa000, 0xc000193170, 0x3, 0x3, 0xc0001aa000, 0xc000193170)
        /Users/james/Code/go/pkg/mod/github.com/spf13/[email protected]/command.go:842 +0x47c
github.com/spf13/cobra.(*Command).ExecuteC(0xc0001398c0, 0x0, 0xffffffff, 0xc000078058)
        /Users/james/Code/go/pkg/mod/github.com/spf13/[email protected]/command.go:950 +0x375
github.com/spf13/cobra.(*Command).Execute(...)
        /Users/james/Code/go/pkg/mod/github.com/spf13/[email protected]/command.go:887
main.main()
        /Users/james/Code/go/pkg/mod/github.com/plexsystems/[email protected]/main.go:10 +0x2a

Does konstraint support input like Conftest's --data flag?

I have an import data.thing in my policy which is read in via conftest verify --data file.yml --policy ....

The file.yml looks like:

thing:
  - 'test1'
  - 'test2'

such that import data.thing - thing matches the array in the yaml file being imported as data.

When I run konstraint docs with this policy, I receive the following error:

Error: get documentation: get all severities: parse directory: getRecursiveImportPaths: import not found: data.thing

How do I tell konstraint about the data file for it to resolve the import correctly?

Request: Generate the sync gatekeeper config based on policies with data.inventory

Use case: I want to be able to auto-generate the sync config (https://github.com/open-policy-agent/gatekeeper#replicating-data) for any kinds which are used via data.inventory.

For example, i have a policy which checks all Services have a ServiceMonitor, i.e.:
data.inventory.namespace[service.metadata.namespace]["monitoring.coreos.com/v1"]["ServiceMonitor"]

Firstly, does it sound like a good fit for konstraint? and secondly, possible?

Question: Is there any support for passing parameters & namespace selectors into the constraint from the src.rego file?

I don't see any examples in this repo which clearly show how parameters or namespace selectors could be passed from the src.rego file into the constraint.yaml.

Is this something that's possible? Or should I be going about this in a different way?

A basic example I have of the functionality I'd like to use would be to use a list of required labels to enforce on resources created in a cluster. An example constraint file similar to what I described would be - https://github.com/open-policy-agent/gatekeeper/blob/master/example/constraints/all_pod_must_have_gatekeeper_namespaceselector.yaml

Don't strip formatting when generating docs

Hello,

Love the project as it's super helpful.

One thing I am wanting to do is embed a valid example of a kubernetes manifest to illustrate how someone can fix a warning or a violation, e.g. if the rule is to check that the container is not running as root, I would like the policy documentation to look something like this:

# @title Containers should not run as root
#
# Containers should not run as root.
#
#  The following snippet is an example of how to satisfy this requirement:
#
# ```
# apiVersion: apps/v1
# kind: Deployment
# metadata:
#   name: redis
# spec:
#   template:
#     spec:
#       containers:
#         - name: redis
#           image: redis:6.2
#           securityContext:
#             runAsNonRoot: true
#             runAsUser: 1000
# ```
#
# @kinds apps/DaemonSet apps/Deployment apps/StatefulSet core/Pod

I can do this just fine, but the resulting markdown loses all formatting and renders the following snippet:

apiVersion: apps/v1
kind: Deployment
metadata:
name: redis
spec:
template:
spec:
containers:
- name: redis
image: redis:6.2
securityContext:
allowPrivilegeEscalation: false
runAsNonRoot: true
runAsUser: 1000

I'm not sure what is reasonable as I am fairly new to the tool, so any guidance would be appreciated.

examples: Breakdown kubernetes library into smaller pieces

The kubernetes.rego file in the examples folder contains all rules for every potential use case. Importing the entire library into every ConstraintTemplate is a bit heavy-handed.

One approach could be:

  • Break up the library such that the rules relate to specific workloads / concerns. To make Gatekeeper compliant with Conftest, the only requirements are the is_gatekeeper and object rules. The remainders are nice to haves. This could be kubernetes.core.

  • All of the memory/size conversions are only needed in some container policies. This could be kubernetes.conversions.

This enables policy writers to opt-in to specific rulesets and keep the imported rules small.

[Feature Request] Konstraint to create Constraint resource when policy uses parameters

What

This is the feature request to enable the creation of Constraint resources when policy uses parameters. I know this has been there in the past but recently Konstraint removed this feature in light that this will be a user-managed field but I think if Konstraint provides this feature to just create a Constraint resources file with the necessary block of field then users can use any automation tool for example Kustomize to patch this file for all necessary input field.

Error:
WARN[0000] skipping constraint generation due to use of parameters name=Image_tag src=policy/image_tag/src.rego

Why

At present, because this feature is not there, I have to generate this file manually and keep them somewhere so that I can embed this with my Constraint Template file which will be generated by Konstraint on the fly from my source rego. This becomes overhead & remove the ability to achieve end-to-end automation.

Scenario

In my case, I am trying to utilise Konstraint to create the necessary Constraint template and Constraint on the fly from my source rego for the Gatekeeper and will use the same source rego for Conftest. At present, our workload does include a couple of Constraint template which has rego with parameters and we're expecting this list to grow. If Konstraint does manage the creation of these Constraint resources on the fly as well for parameters, I can use Kustomize to chip in and do the necessary patch on this file on the go as we're heavily using it for the rest of the templates by using Helm rendering.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.