├── aws ├── example.rego ├── test_example.rego ├── input.rego └── library.rego ├── docker ├── test_host_mounts.rego ├── host_mounts.rego └── example.rego ├── Makefile ├── .github └── workflows │ └── build.yaml ├── kubernetes ├── admission │ ├── test_antiaffinity.rego │ ├── test_alwayspullimages.rego │ ├── antiaffinity.rego │ ├── test_persistentvolumeclaimresize.rego │ ├── persistentvolumeclaimresize.rego │ ├── alwayspullimages.rego │ ├── test_loadbalancer.rego │ ├── example_loadbalancer2.rego │ ├── example_fluxinterval.rego │ ├── example_loadbalancer.rego │ ├── loadbalancer.rego │ ├── test_fluxinterval.rego │ └── input │ │ ├── input_pod_nginx.rego │ │ └── input_service.rego ├── audit │ ├── deployments.rego │ ├── pvcs.rego │ └── pods.rego ├── lib │ ├── sar_test.rego │ └── sar.rego ├── inputs │ ├── persistentvolumeclaims.rego │ └── pods.rego └── mutating-admission │ ├── example_validation.rego │ ├── example_mutation.rego │ ├── test_validation.rego │ ├── README.md │ ├── main.rego │ ├── test_mutation.rego │ └── data_kubernetes.rego ├── istio └── audit │ ├── audit.rego │ ├── util.rego │ ├── service_ports.rego │ ├── pods_in_mesh.rego │ ├── mtls_probes.rego │ └── mesh_version.rego ├── terraform ├── test_example.rego ├── example.rego ├── test_library.rego ├── library.rego └── input.rego ├── README.md ├── .regal └── config.yaml └── LICENSE /aws/example.rego: -------------------------------------------------------------------------------- 1 | package aws.example 2 | 3 | import data.aws.library 4 | 5 | import input as aws 6 | 7 | output = {"SecurityGroupScore": library.score_for_sg} 8 | -------------------------------------------------------------------------------- /docker/test_host_mounts.rego: -------------------------------------------------------------------------------- 1 | package docker 2 | 3 | test_host_mounts { 4 | paths = host_volume_paths({"Binds": ["/root:", "/root", "/", "root", "root/:"]}) 5 | paths = {"root", ""} 6 | } 7 | -------------------------------------------------------------------------------- /docker/host_mounts.rego: -------------------------------------------------------------------------------- 1 | package docker 2 | 3 | host_volume_paths(host_config) = {trimmed | 4 | host_config.Binds[_] = bind 5 | split(bind, ":", parts) 6 | trim(parts[0], "/", trimmed) 7 | } 8 | -------------------------------------------------------------------------------- /aws/test_example.rego: -------------------------------------------------------------------------------- 1 | package aws.test.example 2 | 3 | import data.aws.example 4 | import data.aws.inputs 5 | 6 | test_simple_sg { 7 | i = inputs.simple_example 8 | results = example.output with input as i 9 | results.SecurityGroupScore["sg-1"] = 21 10 | } 11 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | VERSION ?= latest 2 | REPOSITORY ?= openpolicyagent/opa 3 | IMAGE := $(REPOSITORY):$(VERSION) 4 | 5 | all: test check 6 | 7 | .PHONY: test 8 | test: 9 | @./build/test.sh --docker-image=$(IMAGE) --base-dir=$(PWD) 10 | 11 | .PHONY: check 12 | check: 13 | @./build/check.sh --docker-image=$(IMAGE)-debug --base-dir=$(PWD) 14 | -------------------------------------------------------------------------------- /.github/workflows/build.yaml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | pull_request: 5 | branches: [ master ] 6 | push: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | name: Build 12 | runs-on: ubuntu-20.04 13 | steps: 14 | - name: Check out code 15 | uses: actions/checkout@v2 16 | 17 | - name: Make 18 | run: make 19 | -------------------------------------------------------------------------------- /kubernetes/admission/test_antiaffinity.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.test_antiaffinity 2 | 3 | import data.library.kubernetes.admission.antiaffinity 4 | import data.library.kubernetes.inputs.pods 5 | 6 | test_admit { 7 | r = pods.affinity1 8 | antiaffinity.admit = true with input as r 9 | } 10 | 11 | test_nonadmit { 12 | r = pods.affinity2 13 | antiaffinity.admit = false with input as r 14 | } 15 | -------------------------------------------------------------------------------- /istio/audit/audit.rego: -------------------------------------------------------------------------------- 1 | package istio.audit 2 | 3 | import data.istio.audit.vetter 4 | 5 | all[result] { 6 | info[result] 7 | } 8 | 9 | all[result] { 10 | warning[result] 11 | } 12 | 13 | all[result] { 14 | error[result] 15 | } 16 | 17 | info[result] { 18 | vetter[_].info[result] 19 | } 20 | 21 | warning[result] { 22 | vetter[_].warning[result] 23 | } 24 | 25 | error[result] { 26 | vetter[_].error[result] 27 | } 28 | -------------------------------------------------------------------------------- /kubernetes/audit/deployments.rego: -------------------------------------------------------------------------------- 1 | package kubernetes.audit.deployments 2 | 3 | import data.kubernetes.deployments 4 | 5 | warning[result] { 6 | deployment = deployments[namespace][name] 7 | volume = deployment.spec.template.spec.volumes[_] 8 | volume.persistent_volume_claim 9 | not deployment.spec.strategy.type = "Recreate" 10 | result = { 11 | "type": "bad-update-strategy", 12 | "name": name, 13 | "namespace": namespace, 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /kubernetes/admission/test_alwayspullimages.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.test_alwayspullimages 2 | 3 | import data.library.kubernetes.admission.alwayspullimages 4 | import data.library.kubernetes.inputs.pods 5 | 6 | test_admit { 7 | r = pods.nginx_busybox 8 | alwayspullimages.admit = false with input as r 9 | } 10 | 11 | test_overwrites { 12 | r = pods.nginx_busybox 13 | overwrites = alwayspullimages.overwrite with input as r 14 | count(overwrites, 2) 15 | } 16 | -------------------------------------------------------------------------------- /kubernetes/audit/pvcs.rego: -------------------------------------------------------------------------------- 1 | package kubernetes.audit.pvcs 2 | 3 | import data.kubernetes.pods 4 | 5 | warning[result] { 6 | pod = pods[namespace][name] 7 | volume = pod.volumes[_] 8 | volume.persistent_volume_clain 9 | container = pod.spec.containers[_] 10 | mount = container.volume_mounts[_] 11 | mount.name = volume.name 12 | not mount.sub_path 13 | result = { 14 | "type": "missing-pvc-sub-path", 15 | "name": name, 16 | "container_name": container.name, 17 | "namespace": namespace, 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /istio/audit/util.rego: -------------------------------------------------------------------------------- 1 | package istio.audit.util 2 | 3 | import data.kubernetes.pods 4 | 5 | system_namespaces = { 6 | "kube-system", 7 | "kube-public", 8 | "istio-system", 9 | } 10 | 11 | sidecar_injected_pods[namespace] = result { 12 | pods_in_namespace = pods[namespace] 13 | result = {name: pod | pods_in_namespace[name] = pod; is_sidecar_injected(pod)} 14 | } 15 | 16 | is_sidecar_injected(pod) { 17 | pod.metadata.annotations["sidecar.istio.io/status"] 18 | pod.spec.containers[_].name = "istio-proxy" 19 | } 20 | -------------------------------------------------------------------------------- /terraform/test_example.rego: -------------------------------------------------------------------------------- 1 | package terraform.test.example 2 | 3 | import data.terraform.example 4 | import data.terraform.inputs 5 | 6 | test_small_create { 7 | i = inputs.lineage0 8 | example.authz = true with input as i 9 | example.score = 11 with input as i 10 | } 11 | 12 | test_large_create { 13 | i = inputs.large_create 14 | example.authz = false with input as i 15 | example.score = 31 with input as i 16 | } 17 | 18 | test_mix { 19 | i = inputs.lineage1 20 | example.authz = true with input as i 21 | example.score = 12 with input as i 22 | } 23 | -------------------------------------------------------------------------------- /kubernetes/lib/sar_test.rego: -------------------------------------------------------------------------------- 1 | # These tests are commented out as they require kubectl proxy auth 2 | # and the gate currently can not test against it. 3 | # They are useful still for folks that want to manually test. 4 | 5 | package kubernetes.lib_test 6 | 7 | #import data.kubernetes.lib 8 | # 9 | #test_sar_unknown { 10 | # allowed := lib.sar_allowed({"namespace": "default", "verb": "*", "resource": "*"}, "root", ["foo", "bar"]) 11 | # allowed == false 12 | #} 13 | # 14 | #test_sar_ok { 15 | # allowed := lib.sar_allowed({"namespace": "default", "verb": "*", "resource": "*"}, "minikube-user", ["system:masters"]) 16 | # allowed == true 17 | #} 18 | -------------------------------------------------------------------------------- /kubernetes/admission/antiaffinity.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.antiaffinity 2 | 3 | # https://github.com/kubernetes/kubernetes/blob/master/plugin/pkg/admission/antiaffinity/admission.go 4 | # https://github.com/kubernetes/kubernetes/blob/master/plugin/pkg/admission/antiaffinity/admission_test.go 5 | 6 | default admit = false 7 | 8 | admit { 9 | not invalid_anti_affinity 10 | } 11 | 12 | invalid_anti_affinity { 13 | input.kind = "Pod" 14 | terms = input.spec.affinity.podAntiAffinity.requiredDuringSchedulingIgnoredDuringExecution 15 | key = terms[_][_].topologyKey 16 | not allowed_topology_keys[key] 17 | } 18 | 19 | allowed_topology_keys = {"kubernetes.io/hostname"} 20 | -------------------------------------------------------------------------------- /istio/audit/service_ports.rego: -------------------------------------------------------------------------------- 1 | package istio.audit.vetter.service_ports 2 | 3 | import data.kubernetes.services 4 | 5 | warning[result] { 6 | service = services[namespace][name] 7 | port = service.spec.ports[_] 8 | not port.protocol = "udp" 9 | not is_prefixed(port) 10 | result = { 11 | "type": "missing-service-port-prefix", 12 | "service_name": name, 13 | "service_namespace": namespace, 14 | } 15 | } 16 | 17 | is_prefixed(port) { 18 | prefix = service_port_prefixes[port.name] 19 | startswith(port.name, prefix) 20 | } 21 | 22 | service_port_prefixes = { 23 | "http": "http-", 24 | "http2": "http2-", 25 | "grpc": "grpc-", 26 | "mongo": "mongo-", 27 | "redis": "redis-", 28 | "tcp": "tcp-", 29 | } 30 | -------------------------------------------------------------------------------- /istio/audit/pods_in_mesh.rego: -------------------------------------------------------------------------------- 1 | package istio.audit.vetter.pods_in_mesh 2 | 3 | import data.istio.audit.util 4 | import data.kubernetes.pods 5 | 6 | info[result] { 7 | counts = [num | num = count(pods[namespace]); util.system_namespaces[namespace]] 8 | num_system_pods = sum(counts) 9 | result = { 10 | "type": "system-pod-count", 11 | "num_system_pods": num_system_pods, 12 | } 13 | } 14 | 15 | info[result] { 16 | total_counts = [num | num = count(pods[namespace]); not util.system_namespaces[namespace]] 17 | in_mesh_counts = [num | num = count(util.sidecar_injected_pods[namespace])] 18 | num_total_pods = sum(total_counts) 19 | num_in_mesh_pods = sum(in_mesh_counts) 20 | result = { 21 | "type": "user-pod-count", 22 | "num_user_pods": num_total_pods, 23 | "num_in_mesh_pods": num_in_mesh_pods, 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /kubernetes/inputs/persistentvolumeclaims.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.inputs.persistentvolumeclaims 2 | 3 | attributes = { 4 | "plugin": "AWS", 5 | "old": {"pvc": { 6 | "spec": {"size": 10}, 7 | "status": {"phase": "ClaimBound"}, 8 | }}, 9 | "new": {"pvc": {"spec": {"size": 100}}}, 10 | } 11 | 12 | attributes_fail_1 = { 13 | "plugin": "SomethingElse", 14 | "metadata": { 15 | "name": "nginx", 16 | "namespace": "default", 17 | }, 18 | } 19 | 20 | attributes_fail_2 = { 21 | "plugin": "AWS", 22 | "old": {"pvc": { 23 | "spec": {"size": 1000}, 24 | "status": {"phase": "ClaimBound"}, 25 | }}, 26 | "new": {"pvc": {"spec": {"size": 100}}}, 27 | } 28 | 29 | attributes_fail_3 = { 30 | "plugin": "AWS", 31 | "old": {"pvc": { 32 | "spec": {"size": 1000}, 33 | "status": {"phase": "Unbound"}, 34 | }}, 35 | } 36 | -------------------------------------------------------------------------------- /kubernetes/admission/test_persistentvolumeclaimresize.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.test_persistentvolumeclaimresize 2 | 3 | import data.library.kubernetes.admission.persistentvolumeclaimresize 4 | import data.library.kubernetes.inputs.persistentvolumeclaims 5 | 6 | test_verify { 7 | r = persistentvolumeclaims.attributes 8 | persistentvolumeclaimresize.verify with input as r 9 | } 10 | 11 | # check resize support policy 12 | test_fail1 { 13 | r = persistentvolumeclaims.attributes_fail_1 14 | not persistentvolumeclaimresize.supportsResize with input as r 15 | } 16 | 17 | # check resize increase policy 18 | test_fail2 { 19 | r = persistentvolumeclaims.attributes_fail_2 20 | not persistentvolumeclaimresize.allowSizeIncrease with input as r 21 | } 22 | 23 | # check claimbound policy 24 | test_fail3 { 25 | r = persistentvolumeclaims.attributes_fail_3 26 | not persistentvolumeclaimresize.boundClaim with input as r 27 | } 28 | -------------------------------------------------------------------------------- /kubernetes/admission/persistentvolumeclaimresize.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.persistentvolumeclaimresize 2 | 3 | # https://github.com/kubernetes/kubernetes/tree/master/plugin/pkg/admission/persistentvolume/resize/admission.go 4 | # https://github.com/kubernetes/kubernetes/tree/master/plugin/pkg/admission/persistentvolume/resize/admission_test.go 5 | 6 | # plugins supporting resize 7 | plugins = {"GlusterFS", "Cinder", "AWS", "GCE", "RDS"} 8 | 9 | # volume plugin needs to support resize 10 | supportsResize { 11 | plugins[input.plugin] 12 | } 13 | 14 | # we can only expand the size of a pvc 15 | allowSizeIncrease { 16 | oldSize = input.old.pvc.spec.size 17 | newSize = input.new.pvc.spec.size 18 | oldSize <= newSize 19 | } 20 | 21 | # Only bound persistent volume claims can be expanded 22 | boundClaim { 23 | input.old.pvc.status.phase = "ClaimBound" 24 | } 25 | 26 | verify { 27 | supportsResize 28 | allowSizeIncrease 29 | boundClaim 30 | } 31 | -------------------------------------------------------------------------------- /docker/example.rego: -------------------------------------------------------------------------------- 1 | package docker.example 2 | 3 | import data.docker.host_volume_paths 4 | 5 | valid_volume_mapping_whitelist { 6 | paths = host_volume_paths(input.Body.HostConfig) 7 | invalid_paths = paths - valid_host_volume_paths 8 | count(invalid_paths, 0) 9 | } 10 | 11 | valid_volume_mapping_blacklist { 12 | paths = host_volume_paths(input.Body.HostConfig) 13 | invalid_paths = paths & invalid_host_volume_paths 14 | count(invalid_paths, 0) 15 | } 16 | 17 | valid_host_volume_paths[host_path] { 18 | paths = host_volume_paths(input.Body.HostConfig) 19 | paths[host_path] 20 | startswith(host_path, valid_host_path_prefixes[_]) 21 | } 22 | 23 | invalid_host_volume_paths[host_path] { 24 | paths = host_volume_paths(input.Body.HostConfig) 25 | paths[host_path] 26 | startswith(host_path, invalid_host_path_prefixes[_]) 27 | } 28 | 29 | valid_host_path_prefixes = {"allowed", "also/allowed"} 30 | 31 | invalid_host_path_prefixes = {"forbidden", "also/forbidden"} 32 | -------------------------------------------------------------------------------- /istio/audit/mtls_probes.rego: -------------------------------------------------------------------------------- 1 | package istio.audit.vetter.mtls_probes 2 | 3 | import data.istio.audit.util 4 | import data.kubernetes.configmaps 5 | 6 | error[result] { 7 | mtls_enabled 8 | pod = util.sidecar_injected_pods[namespace][name] 9 | container = pod.spec.containers[_] 10 | container.livenessProbe 11 | not container.livenessProbe.exec 12 | result = { 13 | "type": "mtls-probes-incompatible", 14 | "probe": "liveness", 15 | "name": name, 16 | "namespace": namespace, 17 | } 18 | } 19 | 20 | error[result] { 21 | mtls_enabled 22 | pod = util.sidecar_injected_pods[namespace][name] 23 | container = pod.spec.containers[_] 24 | container.readinessProbe 25 | not container.readinessProbe.exec 26 | result = { 27 | "type": "mtls-probes-incompatible", 28 | "probe": "readiness", 29 | "name": name, 30 | "namespace": namespace, 31 | } 32 | } 33 | 34 | mtls_enabled { 35 | cm = configmaps["istio-system"].istio 36 | mesh_config = yaml.unmarshal(cm.data.mesh) 37 | mesh_config.authPolicy = "MUTUAL_TLS" 38 | } 39 | -------------------------------------------------------------------------------- /kubernetes/lib/sar.rego: -------------------------------------------------------------------------------- 1 | package kubernetes.lib 2 | 3 | # These functions are intended to be used with the kubernetes proxy doing authentication for you. 4 | # Run something like: 5 | # kubectl proxy --accept-paths='^/apis/authorization.k8s.io/v1/subjectaccessreviews$' 6 | 7 | import data.kubernetes.lib 8 | 9 | sar_raw(resourceAttributes, user, groups) = output { 10 | body := { 11 | "apiVersion": "authorization.k8s.io/v1", 12 | "kind": "SubjectAccessReview", 13 | "spec": { 14 | "resourceAttributes": resourceAttributes, 15 | "user": user, 16 | "groups": groups, 17 | }, 18 | } 19 | 20 | req := { 21 | "method": "post", 22 | "url": "http://127.0.0.1:8001/apis/authorization.k8s.io/v1/subjectaccessreviews", 23 | "headers": {"Content-Type": "application/json"}, 24 | "body": body, 25 | } 26 | 27 | http.send(req, output) 28 | } 29 | 30 | sar_allowed(resourceAttributes, user, groups) = allowed { 31 | output := sar_raw(resourceAttributes, user, groups) 32 | output.status_code == 201 33 | allowed = output.body.status.allowed 34 | } 35 | -------------------------------------------------------------------------------- /kubernetes/mutating-admission/example_validation.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.mutating 2 | 3 | ############################################################ 4 | # DENY rules 5 | ############################################################ 6 | 7 | # Check for bad dogs 8 | deny[msg] { 9 | isCreateOrUpdate 10 | input.request.kind.kind = "Dog" 11 | input.request.object.spec.isGood = false 12 | msg = sprintf("%s is a good dog, Brent", [input.request.object.spec.name]) 13 | } 14 | 15 | # Don't allow container images with no version tag, or a version tag that doesn't contain at least one digit 16 | 17 | missingImageVersion(imageName) { 18 | not re_match(`.*:.*\d.*$`, imageName) 19 | } 20 | 21 | deny[msg] { 22 | input.request.kind.kind = "Deployment" 23 | badImages = {image | 24 | image = input.request.object.spec.template.spec.containers[_].image 25 | missingImageVersion(image, true) 26 | } 27 | 28 | count(badImages) > 0 29 | names = concat(", ", badImages) 30 | msg = sprintf("Container images must specify a version (%s)", [names]) 31 | } 32 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Library 2 | This repository is a community-owned policy library for the Open Policy Agent. 3 | The goal is to provide a place where the community can find and share logic for 4 | analyzing common JSON documents like Terraform plans and Kubernetes API objects. 5 | 6 | The basic premise is to provide a library of Rego helper functions that 7 | other people can reuse and modify when writing their own policies 8 | along with example policies built using those functions, and 9 | tests that the example policies and helper functions operate as they should. 10 | OPA will be outfitted to pull in libraries and push/contribute helper functions 11 | to the library. 12 | 13 | The basic format of each library is: 14 | 15 | * Any number of .rego files within a directory constitute a library. 16 | * Files beginning with `example` are example policies demonstrating how to use the library. 17 | * Files beginning with `test` are tests either of the library or of the examples. 18 | * Files beginning with `input` are sample inputs used for tests or just as examples. 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /.regal/config.yaml: -------------------------------------------------------------------------------- 1 | rules: 2 | bugs: 3 | constant-condition: 4 | level: ignore 5 | rule-shadows-builtin: 6 | # a few rules called "all" 7 | level: ignore 8 | idiomatic: 9 | custom-in-construct: 10 | level: ignore 11 | no-defined-entrypoint: 12 | level: ignore 13 | use-some-for-output-vars: 14 | level: ignore 15 | imports: 16 | prefer-package-imports: 17 | level: ignore 18 | style: 19 | avoid-get-and-list-prefix: 20 | level: ignore 21 | external-reference: 22 | level: ignore 23 | file-length: 24 | level: ignore 25 | function-arg-return: 26 | level: ignore 27 | line-length: 28 | level: ignore 29 | no-whitespace-comment: 30 | level: ignore 31 | prefer-some-in-iteration: 32 | level: ignore 33 | prefer-snake-case: 34 | level: ignore 35 | rule-length: 36 | level: ignore 37 | todo-comment: 38 | level: ignore 39 | unconditional-assignment: 40 | level: ignore 41 | use-assignment-operator: 42 | level: ignore 43 | testing: 44 | file-missing-test-suffix: 45 | level: ignore 46 | print-or-trace-call: 47 | level: ignore 48 | test-outside-test-package: 49 | level: ignore -------------------------------------------------------------------------------- /kubernetes/admission/alwayspullimages.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.alwayspullimages 2 | 3 | # https://github.com/kubernetes/kubernetes/blob/master/plugin/pkg/admission/alwayspullimages/admission.go 4 | # https://github.com/kubernetes/kubernetes/blob/master/plugin/pkg/admission/alwayspullimages/admission_test.go 5 | 6 | # Allow only if all containers have PullPolicy set to Always 7 | default admit = false 8 | 9 | admit { 10 | not deny 11 | } 12 | 13 | deny { 14 | overwrite[path] 15 | } 16 | 17 | # Overwrite imagePullPolicy so it is always "Always" 18 | overwrite[path] = "Always" { 19 | input.kind = "Pod" 20 | input.spec.containers[i].imagePullPolicy != "Always" 21 | path = sprintf("spec.containers[%v].imagePullPolicy", [i]) 22 | } 23 | 24 | overwrite[path] = "Always" { 25 | input.kind = "Pod" 26 | container = input.spec.containers[i] 27 | not container.imagePullPolicy 28 | path = sprintf("spec.containers[%v].imagePullPolicy", [i]) 29 | } 30 | 31 | overwrite[path] = "Always" { 32 | input.kind = "Pod" 33 | input.spec.initContainers[i].imagePullPolicy != "Always" 34 | path = sprintf("spec.initContainers[%v].imagePullPolicy", [i]) 35 | } 36 | 37 | overwrite[path] = "Always" { 38 | input.kind = "Pod" 39 | container = input.spec.initContainers[i] 40 | not container.imagePullPolicy 41 | path = sprintf("spec.initContainers[%v].imagePullPolicy", [i]) 42 | } 43 | -------------------------------------------------------------------------------- /terraform/example.rego: -------------------------------------------------------------------------------- 1 | package terraform.example 2 | 3 | import data.terraform.library 4 | 5 | import input as tfplan 6 | 7 | ######################## 8 | # Parameters for Policy 9 | ######################## 10 | 11 | # acceptable score for automated authorization 12 | blast_radius = 30 13 | 14 | # weights assigned for each operation on each resource-type 15 | weights = { 16 | "aws_autoscaling_group": {"delete": 100, "create": 10, "modify": 1}, 17 | "aws_instance": {"delete": 10, "create": 1, "modify": 1}, 18 | } 19 | 20 | ######### 21 | # Policy 22 | ######### 23 | 24 | # Authorization holds if score for the plan is acceptable and no changes are made to IAM 25 | default authz = false 26 | 27 | authz { 28 | score < blast_radius 29 | not touches_iam 30 | } 31 | 32 | # Compute the score for a Terraform plan as the weighted sum of deletions, creations, modifications 33 | score = s { 34 | all := [x | 35 | weights[resource_type] = crud 36 | del = crud.delete * library.num_deletes_of_type[resource_type] 37 | new = crud.create * library.num_creates_of_type[resource_type] 38 | mod = crud.modify * library.num_modifies_of_type[resource_type] 39 | x1 = del + new 40 | x = x1 + mod 41 | ] 42 | 43 | sum(all, s) 44 | } 45 | 46 | # Whether there is any change to IAM 47 | touches_iam { 48 | all := library.instance_names_of_type.aws_iam 49 | count(all, c) 50 | c > 0 51 | } 52 | -------------------------------------------------------------------------------- /kubernetes/mutating-admission/example_mutation.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.mutating 2 | 3 | ############################################################ 4 | # PATCH rules 5 | # 6 | # Note: All patch rules should start with `isValidRequest` and `isCreateOrUpdate` 7 | ############################################################ 8 | 9 | # add foo label to Dogs if not present 10 | patch[patchCode] { 11 | isValidRequest 12 | isCreateOrUpdate 13 | input.request.kind.kind == "Dog" 14 | not hasLabelValue(input.request.object, "foo", "bar") 15 | patchCode = makeLabelPatch("add", "foo", "bar", "") 16 | } 17 | 18 | # add baz label if it has label foo=bar 19 | patch[patchCode] { 20 | isValidRequest 21 | isCreateOrUpdate 22 | input.request.kind.kind == "Dog" 23 | hasLabelValue(input.request.object, "foo", "bar") 24 | not hasLabelValue(input.request.object, "baz", "quux") 25 | patchCode = makeLabelPatch("add", "baz", "quux", "") 26 | } 27 | 28 | # add quuz label to Dogs if it's asking 29 | patch[patchCode] { 30 | isValidRequest 31 | isCreateOrUpdate 32 | input.request.kind.kind == "Dog" 33 | hasLabelValue(input.request.object, "moar-labels", "pleez") 34 | patchCode = makeLabelPatch("add", "quuz", "corge", "") 35 | } 36 | 37 | # Dogs get a rating 38 | patch[patchCode] { 39 | isValidRequest 40 | isCreateOrUpdate 41 | input.request.kind.kind == "Dog" 42 | not hasAnnotation(input.request.object, "dogs.io/rating") 43 | patchCode = makeAnnotationPatch("add", "dogs.io/rating", "14/10", "") 44 | } 45 | -------------------------------------------------------------------------------- /kubernetes/admission/test_loadbalancer.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.test_loadbalancer 2 | 3 | import data.library.kubernetes.admission.example_loadbalancer as loadbalancer 4 | import data.library.kubernetes.admission.input.service 5 | 6 | v1beta1 := "admission.k8s.io/v1beta1" 7 | 8 | v1 := "admission.k8s.io/v1" 9 | 10 | test_clusterip { 11 | i := service.loadbalancer 12 | count(loadbalancer.deny) == 0 with input as i 13 | } 14 | 15 | test_nodeport { 16 | i := service.gen_input("NodePort", {}, null, null, v1beta1, null) 17 | count(loadbalancer.deny) > 0 with input as i 18 | } 19 | 20 | test_externalname { 21 | i := service.gen_input("ExternalName", {}, null, null, v1beta1, null) 22 | count(loadbalancer.deny) > 0 with input as i 23 | } 24 | 25 | test_externalLB { 26 | i := service.gen_input("LoadBalancer", {}, null, null, v1beta1, null) 27 | count(loadbalancer.deny) > 0 with input as i 28 | } 29 | 30 | test_whitelisted_elb { 31 | i := service.gen_input("LoadBalancer", {}, "retail", "payment_lb", v1beta1, null) 32 | count(loadbalancer.deny) == 0 with input as i 33 | } 34 | 35 | test_internalLB { 36 | annot := {"cloud.google.com/load-balancer-type": "Internal"} 37 | i := service.gen_input("LoadBalancer", annot, null, null, v1beta1, null) 38 | count(loadbalancer.deny) == 0 with input as i 39 | } 40 | 41 | test_externalLB_apiv1 { 42 | uid := "mock-request-uid" 43 | i := service.gen_input("LoadBalancer", {}, null, null, v1, uid) 44 | count(loadbalancer.deny) > 0 with input as i 45 | result := loadbalancer.main with input as i 46 | result.apiVersion == v1 47 | result.response.uid == uid 48 | } 49 | -------------------------------------------------------------------------------- /istio/audit/mesh_version.rego: -------------------------------------------------------------------------------- 1 | package istio.audit.vetter.mesh_version 2 | 3 | import data.istio.audit.util 4 | import data.kubernetes.deployments 5 | 6 | info[result] { 7 | istio_version = "latest" 8 | result = {"type": "missing-version"} 9 | } 10 | 11 | warning[result] { 12 | istio_version != pilot_version 13 | result = { 14 | "type": "istio-component-mismatch", 15 | "name": "pilot", 16 | "version": pilot_version, 17 | "istio_version": istio_version, 18 | } 19 | } 20 | 21 | warning[result] { 22 | pod = util.sidecar_injected_pods[namespace][name] 23 | v = proxy_version(pod) 24 | v != "latest" 25 | v != istio_version 26 | result = { 27 | "type": "sidecar-mismatch", 28 | "name": name, 29 | "namespace": namespace, 30 | "proxy_version": v, 31 | "istio_version": istio_version, 32 | } 33 | } 34 | 35 | pilot_version = v { 36 | container = deployments["istio-system"]["istio-pilot"].spec.template.spec.containers[_] 37 | container.name = "discovery" 38 | v = get_version(container.image) 39 | } 40 | 41 | istio_version = v { 42 | container = deployments["istio-system"]["istio-mixer"].spec.template.spec.containers[_] 43 | container.name = "mixer" 44 | v = get_version(container.image) 45 | } 46 | 47 | proxy_version(pod) = v { 48 | container = proxy_container(pod) 49 | v = get_version(container.image) 50 | } 51 | 52 | proxy_container(pod) = container { 53 | pod.spec.containers[_] = container 54 | container.name = "istio-proxy" 55 | } 56 | 57 | get_version(image) = v { 58 | parts = split(image, ":") 59 | v = parts[1] 60 | } 61 | 62 | get_version(image) = "latest" { 63 | parts = split(image, ":") 64 | num_parts = count(parts) 65 | num_parts < 2 66 | } 67 | -------------------------------------------------------------------------------- /kubernetes/admission/example_loadbalancer2.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.example_loadbalancer2 2 | 3 | import data.library.kubernetes.admission.loadbalancer 4 | 5 | # Note: same as example_loadbalancer, but define whitelist differently 6 | 7 | # Deny requests that include external-facing load balancer whose name is not 8 | # whitelisted 9 | deny[explanation] { 10 | input.request.kind.kind == "Service" 11 | input.request.operation == "CREATE" 12 | loadbalancer.is_external_lb 13 | not whitelisted 14 | namespace := input.request.namespace 15 | name := input.request.object.metadata.name 16 | explanation = sprintf("Service %v/%v is an external load balancer but has not been whitelisted", [namespace, name]) 17 | } 18 | 19 | # WHITELISTED is a boolean 20 | whitelisted { 21 | input.request.namespace != "prod" 22 | } 23 | 24 | whitelisted { 25 | input.request.userInfo.username == "alice_root" 26 | } 27 | 28 | ############################################################ 29 | # Boilerplate--implementation of the k8s admission control external webhook interface. 30 | # No need to modify the code below. 31 | default apiVersion = "admission.k8s.io/v1beta1" 32 | 33 | apiVersion = input.apiVersion 34 | 35 | # missing uid defaults to empty string 36 | # this will produce a warning in kube apiserver logs 37 | default response_uid = "" 38 | 39 | response_uid = input.request.uid 40 | 41 | main = { 42 | "apiVersion": apiVersion, 43 | "kind": "AdmissionReview", 44 | "response": response, 45 | } 46 | 47 | response = x { 48 | x := { 49 | "allowed": false, 50 | "uid": response_uid, 51 | "status": {"reason": reason}, 52 | } 53 | 54 | reason = concat(", ", deny) 55 | reason != "" 56 | } 57 | 58 | else = x { 59 | x := { 60 | "allowed": true, 61 | "uid": response_uid, 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /kubernetes/admission/example_fluxinterval.rego: -------------------------------------------------------------------------------- 1 | # This example demonstrates how to ensure consumers of your kubernetes cluster don't slam 2 | # your cluster's API or git repositories by configuring [flux](https://fluxcd.io/) to sync too frequently. 3 | package library.kubernetes.validating.fluxinterval 4 | 5 | image := "fluxcd/flux" 6 | 7 | deny[msg] { 8 | some i 9 | 10 | # Ensure only applies to flux images 11 | container := input.spec.template.spec.containers[i] 12 | contains(container.image, image) 13 | 14 | some j 15 | arg := container.args[j] 16 | 17 | # Extract interval argument value 18 | split_interval := split(arg, "--git-poll-interval=") 19 | interval := split_interval[1] 20 | seconds := convert_to_seconds(interval) 21 | 22 | # Ensure value is at least 10 minutes 23 | seconds < 600 24 | msg := "--git-poll-interval must be at least 10m" 25 | } 26 | 27 | deny[msg] { 28 | some i 29 | 30 | # Ensure only applies to flux images 31 | container := input.spec.template.spec.containers[i] 32 | contains(container.image, image) 33 | 34 | some j 35 | arg := container.args[j] 36 | 37 | # Extract interval argument value 38 | split_interval := split(arg, "--sync-interval=") 39 | interval := split_interval[1] 40 | seconds := convert_to_seconds(interval) 41 | 42 | # Ensure value is at least 10 minutes 43 | seconds < 600 44 | msg := "--sync-interval must be at least 10m" 45 | } 46 | 47 | convert_to_seconds(interval) = result { 48 | len := count(interval) 49 | number := to_number(substring(interval, 0, len - 1)) 50 | unit := substring(interval, len - 1, len) 51 | result := convert_to_seconds_aux(number, unit) 52 | } 53 | 54 | convert_to_seconds_aux(number, "s") = number 55 | 56 | convert_to_seconds_aux(number, "m") = number * 60 57 | 58 | convert_to_seconds_aux(number, "h") = number * 3600 59 | -------------------------------------------------------------------------------- /kubernetes/admission/example_loadbalancer.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.example_loadbalancer 2 | 3 | import data.library.kubernetes.admission.loadbalancer 4 | 5 | # Deny requests that include external-facing load balancer whose name is not 6 | # whitelisted 7 | deny[explanation] { 8 | input.request.kind.kind == "Service" 9 | input.request.operation == "CREATE" 10 | loadbalancer.is_external_lb 11 | namespace := input.request.namespace 12 | name := input.request.object.metadata.name 13 | not whitelisted[{"name": name, "namespace": namespace}] 14 | explanation = sprintf("Service %v/%v is an external load balancer but has not been whitelisted", [namespace, name]) 15 | } 16 | 17 | # Simple white list. 18 | # WHITELISTED is a set of dictionaries each of which have a NAMESPACE and a NAME field. 19 | whitelisted[{"namespace": "retail", "name": "payment_lb"}] 20 | 21 | whitelisted[{"namespace": "retail", "name": "frontdoor_lb"}] 22 | 23 | ############################################################ 24 | # Boilerplate--implementation of the k8s admission control external webhook interface. 25 | # No need to modify the code below. 26 | default apiVersion = "admission.k8s.io/v1beta1" 27 | 28 | apiVersion = input.apiVersion 29 | 30 | # missing uid defaults to empty string 31 | # this will produce a warning in kube apiserver logs 32 | default response_uid = "" 33 | 34 | response_uid = input.request.uid 35 | 36 | main = { 37 | "apiVersion": apiVersion, 38 | "kind": "AdmissionReview", 39 | "response": response, 40 | } 41 | 42 | response = x { 43 | x := { 44 | "allowed": false, 45 | "uid": response_uid, 46 | "status": {"reason": reason}, 47 | } 48 | 49 | reason = concat(", ", deny) 50 | reason != "" 51 | } 52 | 53 | else = x { 54 | x := { 55 | "allowed": true, 56 | "uid": response_uid, 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /kubernetes/admission/loadbalancer.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.loadbalancer 2 | 3 | # case: exposing to world via NodePort or ExternalName 4 | is_external_lb { 5 | # https://kubernetes.io/docs/concepts/services-networking/service/#nodeport 6 | # https://kubernetes.io/docs/concepts/services-networking/service/#externalname 7 | types := {"NodePort", "ExternalName"} 8 | types[input.request.object.spec.type] 9 | } 10 | 11 | # case: exposing externalIPs directly 12 | is_external_lb { 13 | # https://kubernetes.io/docs/concepts/services-networking/service/#external-ips 14 | count(input.request.object.externalIPs) > 0 15 | } 16 | 17 | # case: external load balancer (not overridden to be internal load balancer 18 | is_external_lb { 19 | # https://kubernetes.io/docs/concepts/services-networking/service/#loadbalancer 20 | # Using contains(....) instead of == based on recommendations from the field 21 | contains(input.request.object.spec.type, "LoadBalancer") 22 | not is_internal_lb 23 | } 24 | 25 | is_internal_lb { 26 | # https://kubernetes.io/docs/concepts/services-networking/service/#internal-load-balancer 27 | # iterate over all the annotations 28 | input.request.object.metadata.annotations[key] = value 29 | 30 | # check if the annotation indicates the LB is internal-only 31 | # TODO: how forgiving is k8s about the format of the values of annotations: 32 | # IP, case-sensitive, booleans versus strings? 33 | internal_annotations[key] == value 34 | } 35 | 36 | # define dictionary of annotations that make a loadbalancer private 37 | internal_annotations = { 38 | "service.beta.kubernetes.io/aws-load-balancer-internal": "0.0.0.0/0", # aws 39 | "cloud.google.com/load-balancer-type": "Internal", # gcp 40 | "service.beta.kubernetes.io/azure-load-balancer-internal": "true", # azure 41 | "service.beta.kubernetes.io/openstack-internal-load-balancer": "true", # openstack 42 | } 43 | -------------------------------------------------------------------------------- /kubernetes/admission/test_fluxinterval.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.validating.fluxinterval 2 | 3 | test_ten_minutes_allowed { 4 | count(deny) == 0 with input as {"spec": {"template": {"spec": {"containers": [{"image": "fluxcd/flux:1.20.2", "args": ["--git-poll-interval=10m", "--sync-interval=10m"]}]}}}} 5 | } 6 | 7 | test_one_hour_allowed { 8 | count(deny) == 0 with input as {"spec": {"template": {"spec": {"containers": [{"image": "fluxcd/flux:1.20.2", "args": ["--git-poll-interval=1h", "--sync-interval=1h"]}]}}}} 9 | } 10 | 11 | test_five_minutes_denied { 12 | count(deny) == 2 with input as {"spec": {"template": {"spec": {"containers": [{"image": "fluxcd/flux:1.20.2", "args": ["--git-poll-interval=5m", "--sync-interval=5m"]}]}}}} 13 | } 14 | 15 | test_seconds_denied { 16 | count(deny) == 2 with input as {"spec": {"template": {"spec": {"containers": [{"image": "fluxcd/flux:1.20.2", "args": ["--git-poll-interval=1s", "--sync-interval=10s"]}]}}}} 17 | } 18 | 19 | test_five_minutes_denied_git_poll { 20 | count(deny) == 1 with input as {"spec": {"template": {"spec": {"containers": [{"image": "fluxcd/flux:1.20.2", "args": ["--git-poll-interval=5m", "--sync-interval=10m"]}]}}}} 21 | } 22 | 23 | test_five_minutes_denied_sync_interval { 24 | count(deny) == 1 with input as {"spec": {"template": {"spec": {"containers": [{"image": "fluxcd/flux:1.20.2", "args": ["--git-poll-interval=10m", "--sync-interval=5m"]}]}}}} 25 | } 26 | 27 | test_denied_multiple_containers { 28 | count(deny) == 2 with input as {"spec": {"template": {"spec": {"containers": [{"image": "fluxcd/flux:1.20.2", "args": ["--git-poll-interval=10m", "--sync-interval=5m"]}, {"image": "fluxcd/flux:latest", "args": ["--git-poll-interval=1s"]}]}}}} 29 | } 30 | 31 | test_allowed_multiple_containers { 32 | count(deny) == 0 with input as {"spec": {"template": {"spec": {"containers": [{"image": "fluxcd/flux:1.20.2", "args": ["--git-poll-interval=10m", "--sync-interval=10m"]}, {"image": "foo:latest", "args": ["--git-poll-interval=1s"]}]}}}} 33 | } 34 | 35 | test_convert { 36 | convert_to_seconds("10m") == 600 37 | convert_to_seconds("10s") == 10 38 | convert_to_seconds("10h") == 36000 39 | } 40 | -------------------------------------------------------------------------------- /kubernetes/mutating-admission/test_validation.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.mutating 2 | 3 | import data.library.kubernetes.admission.mutating.test as k8s 4 | 5 | ############################################################ 6 | # DENY tests 7 | ############################################################ 8 | 9 | #----------------------------------------------------------- 10 | # Test: the default validation rule is ALLOW 11 | #----------------------------------------------------------- 12 | test_main_default_allow { 13 | res := main with input as k8s.request_default 14 | res.response.allowed 15 | res.response.uid == "" 16 | res.apiVersion == "admission.k8s.io/v1" 17 | } 18 | 19 | #----------------------------------------------------------- 20 | # Test: Dogs with isGood = true are allowed 21 | #----------------------------------------------------------- 22 | test_main_dog_good_allow { 23 | res := main with input as k8s.request_dog_good 24 | res.response.allowed = true 25 | } 26 | 27 | #----------------------------------------------------------- 28 | # Test: Dogs with isGood = false are rejected (They're good dogs, Brent) 29 | #----------------------------------------------------------- 30 | test_main_dog_bad_deny { 31 | res := main with input as k8s.request_dog_bad 32 | res.response.allowed = false 33 | } 34 | 35 | #----------------------------------------------------------- 36 | # Test: Deployment container images must have version tags 37 | #----------------------------------------------------------- 38 | test_container_images_must_have_versions { 39 | res := main with input as k8s.request_deployment_no_versions 40 | trace(sprintf("[test_container_images_must_have_versions] msg = %s", [res.response.status.reason])) 41 | res.response.allowed = false 42 | } 43 | 44 | #----------------------------------------------------------- 45 | # Test: Deployment container images with valid version tags are allowed 46 | #----------------------------------------------------------- 47 | test_container_images_with_versions_are_allowed { 48 | res := main with input as k8s.request_deployment_with_versions 49 | res.response.allowed = true 50 | } 51 | -------------------------------------------------------------------------------- /terraform/test_library.rego: -------------------------------------------------------------------------------- 1 | package terraform.test.library 2 | 3 | import data.terraform.inputs 4 | import data.terraform.library 5 | 6 | test_small_create { 7 | i = inputs.lineage0 8 | library.num_creates = 3 with input as i 9 | library.num_deletes = 0 with input as i 10 | library.num_modifies = 0 with input as i 11 | } 12 | 13 | test_resource_types { 14 | i = inputs.lineage0 15 | x = library.resource_types with input as i 16 | x = {"aws_autoscaling_group", "aws_instance", "aws_launch_configuration"} 17 | } 18 | 19 | test_small_create_of_type { 20 | i = inputs.lineage0 21 | library.num_creates_of_type.aws_instance = 1 with input as i 22 | library.num_creates_of_type.aws_autoscaling_group = 1 with input as i 23 | library.num_creates_of_type.aws_launch_configuration = 1 with input as i 24 | not has_non_zero_value(library.num_deletes_of_type, true) with input as i 25 | not has_non_zero_value(library.num_modifies_of_type, true) with input as i 26 | } 27 | 28 | test_mix { 29 | i = inputs.lineage1 30 | library.num_creates = 1 with input as i 31 | library.num_deletes = 1 with input as i 32 | library.num_modifies = 1 with input as i 33 | } 34 | 35 | test_mix_of_type { 36 | i = inputs.lineage1 37 | library.num_creates_of_type.aws_instance = 1 with input as i 38 | library.num_modifies_of_type.aws_autoscaling_group = 1 with input as i 39 | library.num_deletes_of_type.aws_instance = 1 with input as i 40 | } 41 | 42 | test_large_create { 43 | i = inputs.large_create 44 | library.num_creates = 5 with input as i 45 | library.num_deletes = 0 with input as i 46 | library.num_modifies = 0 with input as i 47 | } 48 | 49 | test_large_create_of_type { 50 | i = inputs.large_create 51 | library.num_creates_of_type.aws_instance = 1 with input as i 52 | library.num_creates_of_type.aws_autoscaling_group = 3 with input as i 53 | library.num_creates_of_type.aws_launch_configuration = 1 with input as i 54 | not has_non_zero_value(library.num_deletes_of_type, true) with input as i 55 | not has_non_zero_value(library.num_modifies_of_type, true) with input as i 56 | } 57 | 58 | has_non_zero_value(dictionary) { 59 | dictionary[_] = x 60 | x != 0 61 | } 62 | -------------------------------------------------------------------------------- /kubernetes/mutating-admission/README.md: -------------------------------------------------------------------------------- 1 | # Validating + Mutating Kubernetes Admission Controller in pure Rego 2 | 3 | `main.rego` implements a simple framework that combines both validating and mutating admission controller rules, as well as some common helpers for working with labels and annotations. 4 | 5 | It was based on the existing examples at [Kubernetes Admission Control](https://www.openpolicyagent.org/docs/kubernetes-admission-control.html) and [MutatingAdmissionWebhook Example with OPA](https://gist.github.com/tsandall/a9b2b57f7c6768f49b25271776b72dee). 6 | 7 | ## A note about labels and annotations 8 | 9 | When adding a label or annotation to some object's metadata Kubernetes requires that the `.../metadata/labels` or `.../metadata/annotations` node exists. The patch framework manages this through the `ensureParentPathsExist()` function, which will create the base `labels` or `annotations` nodes where required. 10 | 11 | ## Helper functions 12 | 13 | A common use case for mutating admission controllers is adding or modifying labels and annotations, so a small set of helper functions is provided to aid readability. See `example_mutation.rego` for some examples, and `test_mutation.rego` for examples of unit tests. 14 | 15 | Note that the `makeLabelPatch()` and `makeAnnotationPatch()` helper functions also handle the common case where labels or annotations may have a slash in the key name, for example `kubernetes.io/role`. This needs to be escaped to `kubernetes.io~1role`, and this is handled automatically in the helper functions. 16 | 17 | ## Mutating vs Validating Admission Controllers 18 | 19 | Mutating Admission Controllers can also return `allowed=false` statuses, to deny the request. This can be handy in simple cases, but be aware that in this library the validation policies (the `deny` rules) will override any patches. In some use cases the mutations applied might be the thing that fixes up raw requests in order to pass validation (adding required labels, for example). In that case you would need to configure two separate OPA instances, one for validation and one for mutation, as Kubernetes will call any mutating controllers before calling any validating controllers. -------------------------------------------------------------------------------- /kubernetes/inputs/pods.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.inputs.pods 2 | 3 | nginx_busybox = { 4 | "apiVersion": "v1", 5 | "kind": "Pod", 6 | "metadata": { 7 | "name": "nginx", 8 | "namespace": "default", 9 | }, 10 | "spec": { 11 | "containers": [ 12 | { 13 | "name": "nginx", 14 | "image": "nginx", 15 | "imagePullPolicy": "Always", 16 | "volumeMounts": [{ 17 | "name": "test", 18 | "mountPath": "/data", 19 | }], 20 | "ports": [{"containerPort": 80}], 21 | }, 22 | { 23 | "name": "busybox", 24 | "image": "busybox", 25 | "imagePullPolicy": "IfNotPresent", 26 | "ports": [{"containerPort": 8080}], 27 | }, 28 | ], 29 | "initContainers": [ 30 | { 31 | "name": "nginx", 32 | "image": "nginx", 33 | "imagePullPolicy": "Always", 34 | "volumeMounts": [{ 35 | "name": "test", 36 | "mountPath": "/data", 37 | }], 38 | "ports": [{"containerPort": 80}], 39 | }, 40 | { 41 | "name": "busybox", 42 | "image": "busybox", 43 | "imagePullPolicy": "IfNotPresent", 44 | "ports": [{"containerPort": 8080}], 45 | }, 46 | ], 47 | }, 48 | } 49 | 50 | affinity1 = { 51 | "apiVersion": "v1", 52 | "kind": "Pod", 53 | "metadata": {"name": "with-pod-affinity"}, 54 | "spec": { 55 | "affinity": {"podAntiAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": [{ 56 | "weight": 100, 57 | "podAffinityTerm": { 58 | "labelSelector": {"matchExpressions": [{ 59 | "key": "security", 60 | "operator": "In", 61 | "values": ["S2"], 62 | }]}, 63 | "topologyKey": "kubernetes.io/hostname", 64 | }, 65 | }]}}, 66 | "containers": [{ 67 | "name": "with-pod-affinity", 68 | "image": "gcr.io/google_containers/pause:2.0", 69 | }], 70 | }, 71 | } 72 | 73 | # spec.affinity.podAntiAffinity.requiredDuringSchedulingIgnoredDuringExecution 74 | affinity2 = { 75 | "apiVersion": "v1", 76 | "kind": "Pod", 77 | "metadata": {"name": "with-pod-affinity"}, 78 | "spec": { 79 | "affinity": {"podAntiAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": [{ 80 | "weight": 100, 81 | "podAffinityTerm": { 82 | "labelSelector": {"matchExpressions": [{ 83 | "key": "security", 84 | "operator": "In", 85 | "values": ["S2"], 86 | }]}, 87 | "topologyKey": "failure-domain.beta.kubernetes.io/zone", 88 | }, 89 | }]}}, 90 | "containers": [{ 91 | "name": "with-pod-affinity", 92 | "image": "gcr.io/google_containers/pause:2.0", 93 | }], 94 | }, 95 | } 96 | -------------------------------------------------------------------------------- /kubernetes/admission/input/input_pod_nginx.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission_inputs.pod 2 | 3 | # kubectl-create on the following resources causes an admission control request to OPA shown below. 4 | # kind: Pod 5 | # apiVersion: v1 6 | # metadata: 7 | # name: nginx 8 | # labels: 9 | # app: nginx 10 | # spec: 11 | # containers: 12 | # - image: nginx 13 | # name: nginx 14 | 15 | nginx = { 16 | "apiVersion": "admission.k8s.io/v1beta1", 17 | "kind": "AdmissionReview", 18 | "request": { 19 | "kind": { 20 | "group": "", 21 | "kind": "Pod", 22 | "version": "v1", 23 | }, 24 | "namespace": "opa", 25 | "object": { 26 | "metadata": { 27 | "creationTimestamp": "2018-10-27T02:12:20Z", 28 | "labels": {"app": "nginx"}, 29 | "name": "nginx", 30 | "namespace": "opa", 31 | "uid": "bbfee96d-d98d-11e8-b280-080027868e77", 32 | }, 33 | "spec": { 34 | "containers": [{ 35 | "image": "nginx", 36 | "imagePullPolicy": "Always", 37 | "name": "nginx", 38 | "resources": {}, 39 | "terminationMessagePath": "/dev/termination-log", 40 | "terminationMessagePolicy": "File", 41 | "volumeMounts": [{ 42 | "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", 43 | "name": "default-token-tm9v8", 44 | "readOnly": true, 45 | }], 46 | }], 47 | "dnsPolicy": "ClusterFirst", 48 | "restartPolicy": "Always", 49 | "schedulerName": "default-scheduler", 50 | "securityContext": {}, 51 | "serviceAccount": "default", 52 | "serviceAccountName": "default", 53 | "terminationGracePeriodSeconds": 30, 54 | "tolerations": [ 55 | { 56 | "effect": "NoExecute", 57 | "key": "node.kubernetes.io/not-ready", 58 | "operator": "Exists", 59 | "tolerationSeconds": 300, 60 | }, 61 | { 62 | "effect": "NoExecute", 63 | "key": "node.kubernetes.io/unreachable", 64 | "operator": "Exists", 65 | "tolerationSeconds": 300, 66 | }, 67 | ], 68 | "volumes": [{ 69 | "name": "default-token-tm9v8", 70 | "secret": {"secretName": "default-token-tm9v8"}, 71 | }], 72 | }, 73 | "status": { 74 | "phase": "Pending", 75 | "qosClass": "BestEffort", 76 | }, 77 | }, 78 | "oldObject": null, 79 | "operation": "CREATE", 80 | "resource": { 81 | "group": "", 82 | "resource": "pods", 83 | "version": "v1", 84 | }, 85 | "uid": "bbfeef88-d98d-11e8-b280-080027868e77", 86 | "userInfo": { 87 | "groups": [ 88 | "system:masters", 89 | "system:authenticated", 90 | ], 91 | "username": "minikube-user", 92 | }, 93 | }, 94 | } 95 | -------------------------------------------------------------------------------- /kubernetes/admission/input/input_service.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.input.service 2 | 3 | # kubectl-create on the following resources causes an admission control request to OPA shown below. 4 | 5 | # kind: Service 6 | # apiVersion: v1 7 | # metadata: 8 | # name: my-service 9 | # spec: 10 | # selector: 11 | # app: MyApp 12 | # ports: 13 | # - protocol: TCP 14 | # port: 80 15 | # targetPort: 9376 16 | # type: LoadBalancer 17 | 18 | loadbalancer = { 19 | "apiVersion": "admission.k8s.io/v1beta1", 20 | "kind": "AdmissionReview", 21 | "request": { 22 | "kind": { 23 | "group": "", 24 | "kind": "Service", 25 | "version": "v1", 26 | }, 27 | "namespace": "opa", 28 | "object": { 29 | "metadata": { 30 | "annotations": {"cloud.google.com/load-balancer-type": "Internal"}, 31 | "creationTimestamp": "2018-10-30T23:30:00Z", 32 | "name": "my-service", 33 | "namespace": "opa", 34 | "uid": "b82becfa-dc9b-11e8-9aa6-080027ca3112", 35 | }, 36 | "spec": { 37 | "clusterIP": "10.97.228.185", 38 | "externalTrafficPolicy": "Cluster", 39 | "ports": [{ 40 | "nodePort": 30431, 41 | "port": 80, 42 | "protocol": "TCP", 43 | "targetPort": 9376, 44 | }], 45 | "selector": {"app": "MyApp"}, 46 | "sessionAffinity": "None", 47 | "type": "LoadBalancer", 48 | }, 49 | "status": {"loadBalancer": {}}, 50 | }, 51 | "oldObject": null, 52 | "operation": "CREATE", 53 | "resource": { 54 | "group": "", 55 | "resource": "services", 56 | "version": "v1", 57 | }, 58 | "uid": "b82bef5f-dc9b-11e8-9aa6-080027ca3112", 59 | "userInfo": { 60 | "groups": [ 61 | "system:masters", 62 | "system:authenticated", 63 | ], 64 | "username": "minikube-user", 65 | }, 66 | }, 67 | } 68 | 69 | endpoint = { 70 | "apiVersion": "admission.k8s.io/v1beta1", 71 | "kind": "AdmissionReview", 72 | "request": { 73 | "kind": { 74 | "group": "", 75 | "kind": "Endpoints", 76 | "version": "v1", 77 | }, 78 | "namespace": "opa", 79 | "object": {"metadata": { 80 | "creationTimestamp": "2018-10-30T22:27:53Z", 81 | "name": "my-service", 82 | "namespace": "opa", 83 | "uid": "0aa3ffe1-dc93-11e8-9aa6-080027ca3112", 84 | }}, 85 | "oldObject": null, 86 | "operation": "CREATE", 87 | "resource": { 88 | "group": "", 89 | "resource": "endpoints", 90 | "version": "v1", 91 | }, 92 | "uid": "0aa40243-dc93-11e8-9aa6-080027ca3112", 93 | "userInfo": { 94 | "groups": [ 95 | "system:serviceaccounts", 96 | "system:serviceaccounts:kube-system", 97 | "system:authenticated", 98 | ], 99 | "uid": "1c8daa54-dc91-11e8-9aa6-080027ca3112", 100 | "username": "system:serviceaccount:kube-system:endpoint-controller", 101 | }, 102 | }, 103 | } 104 | 105 | gen_input(type, annotations, namespace, name, apiVersion, uid) = x { 106 | x = { 107 | "apiVersion": apiVersion, 108 | "kind": "AdmissionReview", 109 | "request": { 110 | "kind": { 111 | "group": "", 112 | "kind": "Service", 113 | "version": "v1", 114 | }, 115 | "namespace": namespace, 116 | "object": { 117 | "metadata": { 118 | "annotations": annotations, 119 | "creationTimestamp": "2018-10-30T22:27:53Z", 120 | "name": name, 121 | "namespace": namespace, 122 | "uid": "0aa31220-dc93-11e8-9aa6-080027ca3112", 123 | }, 124 | "spec": { 125 | "clusterIP": "10.106.113.106", 126 | "externalTrafficPolicy": "Cluster", 127 | "ports": [{ 128 | "nodePort": 32153, 129 | "port": 80, 130 | "protocol": "TCP", 131 | "targetPort": 9376, 132 | }], 133 | "selector": {"app": "MyApp"}, 134 | "sessionAffinity": "None", 135 | "type": type, 136 | }, 137 | "status": {"loadBalancer": {}}, 138 | }, 139 | "oldObject": null, 140 | "operation": "CREATE", 141 | "resource": { 142 | "group": "", 143 | "resource": "services", 144 | "version": "v1", 145 | }, 146 | "uid": uid, 147 | "userInfo": { 148 | "groups": [ 149 | "system:masters", 150 | "system:authenticated", 151 | ], 152 | "username": "minikube-user", 153 | }, 154 | }, 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /terraform/library.rego: -------------------------------------------------------------------------------- 1 | # The Terraform library provides analysis capabilities over Terraform plans. 2 | # In particular, it identifies resources, their types, and whether each 3 | # resource is being created, deleted, or modified. It also provides 4 | # aggregate information for creations, deletions, and modifications, 5 | # optionally organized by the type of resource. 6 | # This library was designed to make it easy to compute a risk score 7 | # for a plan. That score could depend on weights assigned to 8 | # each create/delete/modification of each resource-type, who 9 | # authored the changes in the plan, the state of the resources being 10 | # impacted, and so on. 11 | package terraform.library 12 | 13 | # This library expects a single, global Terraform plan as input named tfplan. 14 | # All functions and virtual documents are computed using that Terraform plan. 15 | # tfplan is a dictionary mapping the name of an instance to its plan entry. 16 | # If you're using Terraform modules, you need to flatten the resource hierarchy 17 | # before handing it to OPA. 18 | import input as tfplan 19 | 20 | # Set of all the types of resources appearing in the plan 21 | # Note: written as a comprehension to eliminate duplicates proactively 22 | # https://github.com/open-policy-agent/opa/issues/429 23 | resource_types = all { 24 | all := {y | tfplan[name]; split(name, ".", outs); y = outs[0]} 25 | } 26 | 27 | # Dictionary that maps the instance name to its full object 28 | instance[name] = obj { 29 | tfplan[name] = obj 30 | name != "destroy" 31 | } 32 | 33 | # Dictionary mapping each resource-type into all the instance names with that type 34 | instance_names_of_type[resource_type] = all { 35 | resource_types[resource_type] 36 | all := {name | 37 | tfplan[name] = _ 38 | has_type(name, resource_type, true) 39 | } 40 | } 41 | 42 | # Function that checks if a given resource-instance name has a given type 43 | has_type(name, resource_type) { 44 | startswith(name, resource_type) 45 | } 46 | 47 | # Total number of deletions 48 | num_deletes = num { 49 | count(deletes, num) 50 | } 51 | 52 | # Set of all the resource-instance names being deleted 53 | deletes = deletions { 54 | deletions := {name | obj = instance[name]; is_delete(obj, true)} 55 | } 56 | 57 | # Dictionary mapping each resource-type to the number of deletions of that type 58 | num_deletes_of_type[resource_type] = num { 59 | count(deletes_of_type[resource_type], num) 60 | } 61 | 62 | # Dictionary mapping each resource-type to the list of deleted resource-instance names 63 | deletes_of_type[resource_type] = deletions { 64 | resource_types[resource_type] 65 | deletions := {name | name = deletes[_]; has_type(name, resource_type, true)} 66 | } 67 | 68 | # Function defining whether a resource-instance is a deletion. 69 | is_delete(obj) { 70 | obj.destroy = true 71 | } 72 | 73 | # Total number of creations 74 | num_creates = num { 75 | count(creates, num) 76 | } 77 | 78 | # Set of created resource-instance names 79 | creates = makes { 80 | makes = {name | obj = instance[name]; is_create(obj, true)} 81 | } 82 | 83 | # Dictionary mapping each resource-type to the number of creations of that type 84 | num_creates_of_type[resource_type] = num { 85 | count(creates_of_type[resource_type], num) 86 | } 87 | 88 | # Dictionary mapping each resource-type to the list of created resource-instance names 89 | creates_of_type[resource_type] = makes { 90 | all := instance_names_of_type[resource_type] 91 | makes := {name | all[_] = name; obj = instance[name]; is_create(obj, true)} 92 | } 93 | 94 | # Function defining whether a resource-instance is a creation 95 | is_create(obj) { 96 | obj.id = "" 97 | } 98 | 99 | # Total number of modifications (other than creates and deletes) 100 | num_modifies = num { 101 | count(modifies, num) 102 | } 103 | 104 | # Set of resource-instance names being modified 105 | modifies = mods { 106 | mods = {name | obj = instance[name]; is_modify(obj, true)} 107 | } 108 | 109 | # Dictionary mapping each resource-type to the number of modified resource-instances 110 | num_modifies_of_type[resource_type] = num { 111 | count(modifies_of_type[resource_type], num) 112 | } 113 | 114 | # Dictionary mapping each resource-type to the list of modified resource-instance names 115 | modifies_of_type[resource_type] = mods { 116 | all := instance_names_of_type[resource_type] 117 | mods := {name | all[_] = name; obj = instance[name]; is_modify(obj, true)} 118 | } 119 | 120 | # Function defining whether a resource-instance is a modification 121 | is_modify(obj) { 122 | obj.destroy = false 123 | not obj.id 124 | } 125 | -------------------------------------------------------------------------------- /kubernetes/audit/pods.rego: -------------------------------------------------------------------------------- 1 | package kubernetes.audit.pods 2 | 3 | import data.kubernetes.audit.warn_images 4 | import data.kubernetes.pods 5 | 6 | error[result] { 7 | containers[[namespace, name, container]] 8 | missing_resources(container) 9 | result = { 10 | "type": "missing-resources", 11 | "name": name, 12 | "container_name": container.name, 13 | "namespace": namespace, 14 | } 15 | } 16 | 17 | error[result] { 18 | pod = pods[namespace][name] 19 | not pod.metadata.labels.app 20 | result = { 21 | "type": "missing-app-label", 22 | "name": name, 23 | "namespace": namespace, 24 | } 25 | } 26 | 27 | warning[result] { 28 | containers[[namespace, name, container]] 29 | container.securityContext.privileged 30 | result = { 31 | "type": "privileged-security-context", 32 | "name": name, 33 | "container_name": container.name, 34 | "namespace": namespace, 35 | } 36 | } 37 | 38 | warning[result] { 39 | pod = pods[namespace][name] 40 | pod.spec.hostNetwork 41 | result = { 42 | "type": "connects-to-host-network", 43 | "name": name, 44 | "namespace": namespace, 45 | } 46 | } 47 | 48 | warning[result] { 49 | containers[[namespace, name, container]] 50 | not container.securityContext.allowPrivilegeEscalation = false 51 | result = { 52 | "type": "bad-privilege-escalation", 53 | "name": name, 54 | "container_name": container.name, 55 | "namespace": namespace, 56 | } 57 | } 58 | 59 | warning[result] { 60 | containers[[namespace, name, container]] 61 | dropped = {cap | cap = container.securityContext.capabilities.drop[_]} 62 | remaining = recommended_cap_drop - dropped 63 | count(remaining) > 0 64 | result = { 65 | "type": "bad-cap-not-dropped", 66 | "name": name, 67 | "container_name": container.name, 68 | "namespace": namespace, 69 | "not_dropped": remaining, 70 | } 71 | } 72 | 73 | warning[result] { 74 | containers[[namespace, name, container]] 75 | added = {cap | cap = container.securityContext.capabilities.add[_]} 76 | remaining = recommended_cap_drop & added 77 | count(remaining) > 0 78 | result = { 79 | "type": "bad-cap-added", 80 | "name": name, 81 | "container_name": container.name, 82 | "namespace": namespace, 83 | "not_dropped": remaining, 84 | } 85 | } 86 | 87 | warning[result] { 88 | containers[[namespace, name, container]] 89 | [image_name, image_tag] = split_image(container.image) 90 | warn_images[image_name][_] = image_tag 91 | result = { 92 | "type": "bad-image", 93 | "name": name, 94 | "namespace": namespace, 95 | "container_name": container.name, 96 | "image_name": image_name, 97 | "image_tag": image_tag, 98 | } 99 | } 100 | 101 | warning[result] { 102 | containers[[namespace, name, container]] 103 | [image_name, "latest"] = split_image(container.image) 104 | result = { 105 | "type": "bad-latest-image", 106 | "name": name, 107 | "namespace": namespace, 108 | "container_name": container.name, 109 | "image_name": image_name, 110 | } 111 | } 112 | 113 | warning[result] { 114 | containers[[namespace, name, container]] 115 | not container.securityContext.readOnlyRootFilesystem = true 116 | result = { 117 | "type": "read-only-root-fs", 118 | "name": name, 119 | "namespace": namespace, 120 | "container_name": container.name, 121 | } 122 | } 123 | 124 | warning[result] { 125 | containers[[namespace, name, container]] 126 | not container.securityContext.runAsNonRoot = true 127 | result = { 128 | "type": "run-as-non-root", 129 | "name": name, 130 | "namespace": namespace, 131 | "container_name": container.name, 132 | } 133 | } 134 | 135 | containers[[namespace, name, container]] { 136 | pod = pods[namespace][name] 137 | cs = pod_containers(pod) 138 | container = cs[_] 139 | } 140 | 141 | pod_containers(pod) = cs { 142 | keys = {"containers", "initContainers"} 143 | cs = [c | keys[k]; c = pod.spec[k][_]] 144 | } 145 | 146 | split_image(image) = [image, "latest"] { 147 | not contains(image, ":") 148 | } 149 | 150 | split_image(image) = [name, tag] { 151 | [name, tag] = split(image, ":") 152 | } 153 | 154 | missing_resources(container) { 155 | not container.resources.limits.cpu 156 | } 157 | 158 | recommended_cap_drop = { 159 | "AUDIT_WRITE", 160 | "CHOWN", 161 | "DAC_OVERRIDE", 162 | "FOWNER", 163 | "FSETID", 164 | "KILL", 165 | "MKNOD", 166 | "NET_BIND_SERVICE", 167 | "NET_RAW", 168 | "SETFCAP", 169 | "SETGID", 170 | "SETUID", 171 | "SETPCAP", 172 | "SYS_CHROOT", 173 | } 174 | 175 | missing_resources(container) { 176 | not container.resources.limits.memory 177 | } 178 | 179 | missing_resources(container) { 180 | not container.resources.requests.cpu 181 | } 182 | 183 | missing_resources(container) { 184 | not container.resources.requests.memory 185 | } 186 | -------------------------------------------------------------------------------- /aws/input.rego: -------------------------------------------------------------------------------- 1 | package aws.inputs 2 | 3 | simple_example = {"SecurityGroups": [ 4 | { 5 | "Description": "Private Networks", 6 | "GroupId": "sg-1", 7 | "GroupName": "private", 8 | "IpPermissions": [ 9 | { 10 | "FromPort": 80, 11 | "IpProtocol": "tcp", 12 | "IpRanges": [ 13 | { 14 | "CidrIp": "10.23.1.192/26", 15 | "Description": null, 16 | }, 17 | { 18 | "CidrIp": "10.23.1.64/26", 19 | "Description": null, 20 | }, 21 | ], 22 | "Ipv6Ranges": null, 23 | "PrefixListIds": null, 24 | "ToPort": 80, 25 | "UserIdGroupPairs": null, 26 | }, 27 | { 28 | "FromPort": null, 29 | "IpProtocol": "-1", 30 | "IpRanges": null, 31 | "Ipv6Ranges": null, 32 | "PrefixListIds": null, 33 | "ToPort": null, 34 | "UserIdGroupPairs": [{ 35 | "Description": null, 36 | "GroupId": "sg-2", 37 | "GroupName": null, 38 | "PeeringStatus": null, 39 | "UserId": "123456789", 40 | "VpcId": null, 41 | "VpcPeeringConnectionId": null, 42 | }], 43 | }, 44 | { 45 | "FromPort": 22, 46 | "IpProtocol": "tcp", 47 | "IpRanges": [{ 48 | "CidrIp": "0.0.0.0/0", 49 | "Description": null, 50 | }], 51 | "Ipv6Ranges": null, 52 | "PrefixListIds": null, 53 | "ToPort": 22, 54 | "UserIdGroupPairs": null, 55 | }, 56 | { 57 | "FromPort": 1234, 58 | "IpProtocol": "udp", 59 | "IpRanges": [{ 60 | "CidrIp": "0.0.0.0/0", 61 | "Description": null, 62 | }], 63 | "Ipv6Ranges": null, 64 | "PrefixListIds": null, 65 | "ToPort": 7946, 66 | "UserIdGroupPairs": null, 67 | }, 68 | { 69 | "FromPort": 1234, 70 | "IpProtocol": "tcp", 71 | "IpRanges": [{ 72 | "CidrIp": "0.0.0.0/0", 73 | "Description": null, 74 | }], 75 | "Ipv6Ranges": null, 76 | "PrefixListIds": null, 77 | "ToPort": 7946, 78 | "UserIdGroupPairs": null, 79 | }, 80 | { 81 | "FromPort": 8089, 82 | "IpProtocol": "tcp", 83 | "IpRanges": [ 84 | { 85 | "CidrIp": "10.23.0.0/22", 86 | "Description": null, 87 | }, 88 | { 89 | "CidrIp": "10.23.4.0/22", 90 | "Description": null, 91 | }, 92 | { 93 | "CidrIp": "10.23.8.0/24", 94 | "Description": null, 95 | }, 96 | ], 97 | "Ipv6Ranges": null, 98 | "PrefixListIds": null, 99 | "ToPort": 8089, 100 | "UserIdGroupPairs": null, 101 | }, 102 | { 103 | "FromPort": 9997, 104 | "IpProtocol": "tcp", 105 | "IpRanges": [ 106 | { 107 | "CidrIp": "10.23.0.0/22", 108 | "Description": null, 109 | }, 110 | { 111 | "CidrIp": "10.23.4.0/22", 112 | "Description": null, 113 | }, 114 | { 115 | "CidrIp": "10.23.8.0/24", 116 | "Description": null, 117 | }, 118 | ], 119 | "Ipv6Ranges": null, 120 | "PrefixListIds": null, 121 | "ToPort": 9997, 122 | "UserIdGroupPairs": null, 123 | }, 124 | { 125 | "FromPort": 443, 126 | "IpProtocol": "tcp", 127 | "IpRanges": [ 128 | { 129 | "CidrIp": "10.23.9.192/26", 130 | "Description": null, 131 | }, 132 | { 133 | "CidrIp": "10.23.9.64/26", 134 | "Description": null, 135 | }, 136 | ], 137 | "Ipv6Ranges": null, 138 | "PrefixListIds": null, 139 | "ToPort": 443, 140 | "UserIdGroupPairs": null, 141 | }, 142 | ], 143 | "IpPermissionsEgress": [{ 144 | "FromPort": null, 145 | "IpProtocol": "-1", 146 | "IpRanges": [{ 147 | "CidrIp": "0.0.0.0/0", 148 | "Description": null, 149 | }], 150 | "Ipv6Ranges": null, 151 | "PrefixListIds": null, 152 | "ToPort": null, 153 | "UserIdGroupPairs": null, 154 | }], 155 | "OwnerId": "123456789", 156 | "Tags": [{ 157 | "Key": "Name", 158 | "Value": "private", 159 | }], 160 | "VpcId": "vpc-a123456", 161 | }, 162 | { 163 | "Description": "Security group for public", 164 | "GroupId": "sg-2", 165 | "GroupName": "public", 166 | "IpPermissions": [{ 167 | "FromPort": 22, 168 | "IpProtocol": "tcp", 169 | "IpRanges": [{ 170 | "CidrIp": "10.23.10.10/0", 171 | "Description": null, 172 | }], 173 | "Ipv6Ranges": null, 174 | "PrefixListIds": null, 175 | "ToPort": 22, 176 | "UserIdGroupPairs": null, 177 | }], 178 | "IpPermissionsEgress": [{ 179 | "FromPort": null, 180 | "IpProtocol": "-1", 181 | "IpRanges": [{ 182 | "CidrIp": "0.0.0.0/0", 183 | "Description": null, 184 | }], 185 | "Ipv6Ranges": null, 186 | "PrefixListIds": null, 187 | "ToPort": null, 188 | "UserIdGroupPairs": null, 189 | }], 190 | "OwnerId": "123456789", 191 | "Tags": [{ 192 | "Key": "Name", 193 | "Value": "private", 194 | }], 195 | "VpcId": "vpc-a123456", 196 | }, 197 | ]} 198 | -------------------------------------------------------------------------------- /aws/library.rego: -------------------------------------------------------------------------------- 1 | # The AWS library provides analysis capabilities of Security Groups discovered from an AWS environment. 2 | # This is designed to audit the objects for compliance with some rules like the ones defined in NIST 800-53 (e.g. CM-8(3)) 3 | 4 | package aws.library 5 | 6 | # This Library expects a single document named aws. 7 | 8 | import input as aws 9 | 10 | # List of ports that should not appear in rules 11 | bad_ports = {23, 69, 87, 111, 21} 12 | 13 | security_groups[groupid] = obj { 14 | aws.SecurityGroups[_] = obj 15 | obj.GroupId = groupid 16 | } 17 | 18 | # create a map of all security groups with their score 19 | # For example 20 | # { 21 | # "sg-123456": 11 22 | # } 23 | score_threshold = 1 24 | 25 | score_for_sg[sgid] = score { 26 | security_groups[sgid] = obj 27 | wildcard_ingress_count(obj, i) 28 | wildcard_egress_count(obj, e) 29 | wide_egress_count(obj, we) 30 | wide_ingress_count(obj, wi) 31 | prohibited_ingress_count(obj, pi) 32 | prohibited_egress_count(obj, pe) 33 | sum([i, e, we, wi, pi, pe], score) 34 | score > score_threshold 35 | } 36 | 37 | # Count the number of ingress Permissions with wildcards 38 | # Input : SecurityGroup 39 | 40 | wildcard_ingress_count(obj) = num { 41 | wildcards = {r | x = obj.IpPermissions[r]; is_wildcard_permission(x, true)} 42 | count(wildcards, c) 43 | num = c * 10 44 | } 45 | 46 | # Count the number of ingress Permissions with prohibited ports 47 | # Input : SecurityGroup 48 | 49 | prohibited_ingress_count(obj) = num { 50 | prohibited = {r | x = obj.IpPermissions[r]; has_prohibited_port_open(x, true)} 51 | count(prohibited, c) 52 | num = c * 10 53 | } 54 | 55 | # Count the number of ingress Permissions with wide port range 56 | # Input : SecurityGroup 57 | 58 | wide_ingress_count(obj) = num { 59 | wide = {r | x = obj.IpPermissions[r]; is_broad_permission(x, true)} 60 | count(wide, c) 61 | num = c * 10 62 | } 63 | 64 | # Count the number of egress Permissions with wide port range 65 | # Input : SecurityGroup 66 | 67 | wide_egress_count(obj) = num { 68 | wide = {r | x = obj.IpPermissionsEgress[r]; is_broad_permission(x, true)} 69 | count(wide, c) 70 | num = c * 1 71 | } 72 | 73 | # Count the number of egress Permissions with wildcards 74 | # Input : SecurityGroup 75 | 76 | wildcard_egress_count(obj) = num { 77 | wildcards = {r | x = obj.IpPermissionsEgress[r]; is_wildcard_permission(x, true)} 78 | count(wildcards, c) 79 | num = c * 1 80 | } 81 | 82 | # Count the number of egress Permissions with prohibited ports 83 | # Input : SecurityGroup 84 | 85 | prohibited_egress_count(obj) = num { 86 | prohibited = {r | x = obj.IpPermissionsEgress[r]; has_prohibited_port_open(x, true)} 87 | count(prohibited, c) 88 | num = c * 1 89 | } 90 | 91 | # Check if security group permission has a wildcard CIDR 92 | # Input : IpPermissions 93 | 94 | has_wildcard_cidr(obj) { 95 | obj.IpRanges[_].CidrIp = "0.0.0.0/0" 96 | } 97 | 98 | # Check if security group permission has wildcard protocol and ports 99 | # Input : IpPermissions 100 | 101 | has_wildcard_ports(obj) { 102 | obj.ToPort = null 103 | obj.FromPort = null 104 | obj.IpProtocol = "-1" 105 | } 106 | 107 | # Check if rule has more than one port open - Eventually the number of ports could be returned instead of boolean 108 | # Input : IpPermissions 109 | 110 | has_wide_range(obj) { 111 | obj.ToPort != null 112 | obj.FromPort != null 113 | 114 | x = obj.ToPort - obj.FromPort 115 | x > 0 116 | } 117 | 118 | # Check if security group permission is allowing all traffic on all ports 119 | # looking like this in AWS Security groups : 120 | # { 121 | # "FromPort": null, 122 | # "IpProtocol": "-1", 123 | # "IpRanges": [ 124 | # { 125 | # "CidrIp": "0.0.0.0/0", 126 | # } 127 | # ], 128 | # "ToPort": null, 129 | # } 130 | # Input : IpPermissions 131 | 132 | is_wildcard_permission(obj) { 133 | has_wildcard_ports(obj, true) 134 | has_wildcard_cidr(obj, true) 135 | } 136 | 137 | # Check if security group permission is allowing all traffic on too many ports 138 | # looking like this in AWS Security groups : 139 | # { 140 | # "FromPort": 0, 141 | # "IpProtocol": "tcp", 142 | # "IpRanges": [ 143 | # { 144 | # "CidrIp": "0.0.0.0/0", 145 | # } 146 | # ], 147 | # "ToPort": 65535, 148 | # } 149 | # Input : IpPermissions 150 | 151 | is_broad_permission(obj) { 152 | has_wide_range(obj, true) 153 | has_wildcard_cidr(obj, true) 154 | } 155 | 156 | ipperm_key = {"IpPermissions", "IpPermissionsEgress"} 157 | 158 | # Check if any of the prohibited ports are opened in either ingress or egress 159 | # Input : SecurityGroup 160 | 161 | has_prohibited_port_open(obj) { 162 | from = obj[perm_key][j].FromPort # instead of _, using a variable name 163 | to = obj[perm_key][j].ToPort 164 | ipperm_key[perm_key] # check if perm_key is "IpPermissionEgress" or "IpPermissionsIngress" 165 | bad_ports[port] 166 | from <= port 167 | port <= to 168 | } 169 | -------------------------------------------------------------------------------- /kubernetes/mutating-admission/main.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.mutating 2 | 3 | ########################################################################### 4 | # Implementation of the k8s admission control external webhook interface, 5 | # combining validating and mutating admission controllers 6 | ########################################################################### 7 | default apiVersion = "admission.k8s.io/v1beta1" 8 | 9 | apiVersion = input.apiVersion 10 | 11 | # missing uid defaults to empty string 12 | # this will produce a warning in kube apiserver logs 13 | default response_uid = "" 14 | 15 | response_uid = input.request.uid 16 | 17 | main = { 18 | "apiVersion": apiVersion, 19 | "kind": "AdmissionReview", 20 | "response": response, 21 | } 22 | 23 | # non-patch response i.e. validation response 24 | response = x { 25 | count(patch) == 0 26 | 27 | x := { 28 | "allowed": false, 29 | "uid": response_uid, 30 | "status": {"reason": reason}, 31 | } 32 | 33 | reason = concat(", ", deny) 34 | reason != "" 35 | } 36 | 37 | # patch response i.e. mutating respone 38 | else = x { 39 | count(patch) > 0 40 | 41 | # if there are missing leaves e.g. trying to add a label to something that doesn't 42 | # yet have any, we need to create the leaf nodes as well 43 | 44 | fullPatches := ensureParentPathsExist(cast_array(patch)) 45 | 46 | x := { 47 | "allowed": true, 48 | "uid": response_uid, 49 | "patchType": "JSONPatch", 50 | "patch": base64.encode(json.marshal(fullPatches)), 51 | } 52 | } 53 | 54 | # default response 55 | else = x { 56 | x := { 57 | "allowed": true, 58 | "uid": response_uid, 59 | } 60 | } 61 | 62 | isValidRequest { 63 | # not sure if this might be a race condition, it might get called before 64 | # all the validation rules have been run 65 | count(deny) == 0 66 | } 67 | 68 | isCreateOrUpdate { 69 | isCreate 70 | } 71 | 72 | isCreateOrUpdate { 73 | isUpdate 74 | } 75 | 76 | isCreate { 77 | input.request.operation == "CREATE" 78 | } 79 | 80 | isUpdate { 81 | input.request.operation == "UPDATE" 82 | } 83 | 84 | ########################################################################### 85 | # PATCH helpers 86 | # Note: These rules assume that the input is an object 87 | # not an AdmissionRequest, because labels and annotations 88 | # can apply to various sub-objects within a request 89 | # So from the context of an AdmissionRequest they need to 90 | # be called like 91 | # hasLabelValue("foo", "bar") with input as input.request.object 92 | # or 93 | # hasLabelValue("foo", "bar") with input as input.request.oldObject 94 | ########################################################################### 95 | 96 | hasLabels(obj) { 97 | obj.metadata.labels 98 | } 99 | 100 | hasLabel(obj, label) { 101 | obj.metadata.labels[label] 102 | } 103 | 104 | hasLabelValue(obj, key, val) { 105 | obj.metadata.labels[key] = val 106 | } 107 | 108 | hasAnnotations(obj) { 109 | obj.metadata.annotations 110 | } 111 | 112 | hasAnnotation(obj, annotation) { 113 | obj.metadata.annotations[annotation] 114 | } 115 | 116 | hasAnnotationValue(obj, key, val) { 117 | obj.metadata.annotations[key] = val 118 | } 119 | 120 | ########################################################################### 121 | # makeLabelPatch creates a label patch 122 | # Labels can exist on numerous child objects e.g. Deployment.template.metadata 123 | # Use pathPrefix to specify a lower level object, or pass "" to select the 124 | # top level object 125 | # Note: pathPrefix should have a leading '/' but no trailing '/' 126 | ########################################################################### 127 | 128 | makeLabelPatch(op, key, value, pathPrefix) = patchCode { 129 | patchCode = { 130 | "op": op, 131 | "path": concat("/", [pathPrefix, "metadata/labels", replace(key, "/", "~1")]), 132 | "value": value, 133 | } 134 | } 135 | 136 | makeAnnotationPatch(op, key, value, pathPrefix) = patchCode { 137 | patchCode = { 138 | "op": op, 139 | "path": concat("/", [pathPrefix, "metadata/annotations", replace(key, "/", "~1")]), 140 | "value": value, 141 | } 142 | } 143 | 144 | # Given array of JSON patches create and prepend new patches that create missing paths. 145 | ensureParentPathsExist(patches) = result { 146 | # Convert patches to a set 147 | paths := {p.path | p := patches[_]} 148 | 149 | # Compute all missing subpaths. 150 | # Iterate over all paths and over all subpaths 151 | # If subpath doesn't exist, add it to the set after making it a string 152 | missingPaths := {sprintf("/%s", [concat("/", prefixPath)]) | 153 | paths[path] 154 | pathArray := split(path, "/") 155 | pathArray[i] # walk over path 156 | i > 0 # skip initial element 157 | 158 | # array of all elements in path up to i 159 | prefixPath := [pathArray[j] | pathArray[j]; j < i; j > 0] # j > 0: skip initial element 160 | walkPath := [toWalkElement(x) | x := prefixPath[_]] 161 | not inputPathExists(walkPath) with input as input.request.object 162 | } 163 | 164 | # Sort paths, to ensure they apply in correct order 165 | ordered_paths := sort(missingPaths) 166 | 167 | # Return new patches prepended to original patches. 168 | # Don't forget to prepend all paths with a / 169 | new_patches := [{"op": "add", "path": p, "value": {}} | 170 | p := ordered_paths[_] 171 | ] 172 | 173 | result := array.concat(new_patches, patches) 174 | } 175 | 176 | # Check that the given @path exists as part of the input object. 177 | inputPathExists(path) { 178 | walk(input, [path, _]) 179 | } 180 | 181 | toWalkElement(str) = str { 182 | not re_match("^[0-9]+$", str) 183 | } 184 | 185 | toWalkElement(str) = x { 186 | re_match("^[0-9]+$", str) 187 | x := to_number(str) 188 | } 189 | 190 | # Dummy deny and patch to please the compiler 191 | 192 | deny[msg] { 193 | input.request.kind == "AdmissionReview" 194 | msg = "Input must be Kubernetes AdmissionRequest" 195 | } 196 | 197 | patch[patchCode] { 198 | input.kind == "ThisHadBetterNotBeARealKind" 199 | patchCode = {} 200 | } 201 | -------------------------------------------------------------------------------- /terraform/input.rego: -------------------------------------------------------------------------------- 1 | package terraform.inputs 2 | 3 | # Garden of eden. Create a few resources 4 | lineage0 = { 5 | "aws_autoscaling_group.lamb": { 6 | "arn": "", 7 | "availability_zones.#": "1", 8 | "availability_zones.3205754986": "us-west-1a", 9 | "default_cooldown": "", 10 | "desired_capacity": "4", 11 | "destroy": false, 12 | "destroy_tainted": false, 13 | "force_delete": "true", 14 | "health_check_grace_period": "300", 15 | "health_check_type": "ELB", 16 | "id": "", 17 | "launch_configuration": "kitten", 18 | "load_balancers.#": "", 19 | "max_size": "5", 20 | "metrics_granularity": "1Minute", 21 | "min_size": "1", 22 | "name": "lamb", 23 | "protect_from_scale_in": "false", 24 | "vpc_zone_identifier.#": "", 25 | "wait_for_capacity_timeout": "10m", 26 | }, 27 | "aws_instance.puppy": { 28 | "ami": "ami-09b4b74c", 29 | "associate_public_ip_address": "", 30 | "availability_zone": "", 31 | "destroy": false, 32 | "destroy_tainted": false, 33 | "ebs_block_device.#": "", 34 | "ephemeral_block_device.#": "", 35 | "id": "", 36 | "instance_state": "", 37 | "instance_type": "t2.micro", 38 | "ipv6_addresses.#": "", 39 | "key_name": "", 40 | "network_interface_id": "", 41 | "placement_group": "", 42 | "private_dns": "", 43 | "private_ip": "", 44 | "public_dns": "", 45 | "public_ip": "", 46 | "root_block_device.#": "", 47 | "security_groups.#": "", 48 | "source_dest_check": "true", 49 | "subnet_id": "", 50 | "tenancy": "", 51 | "vpc_security_group_ids.#": "", 52 | }, 53 | "aws_launch_configuration.kitten": { 54 | "associate_public_ip_address": "false", 55 | "destroy": false, 56 | "destroy_tainted": false, 57 | "ebs_block_device.#": "", 58 | "ebs_optimized": "", 59 | "enable_monitoring": "true", 60 | "id": "", 61 | "image_id": "ami-09b4b74c", 62 | "instance_type": "t2.micro", 63 | "key_name": "", 64 | "name": "kitten", 65 | "root_block_device.#": "", 66 | }, 67 | "destroy": false, 68 | } 69 | 70 | # Create, modify, and delelete resources 71 | lineage1 = { 72 | "aws_autoscaling_group.lamb": { 73 | "destroy": false, 74 | "destroy_tainted": false, 75 | "max_size": "4", 76 | }, 77 | "aws_instance.pony": { 78 | "ami": "ami-09b4b74c", 79 | "associate_public_ip_address": "", 80 | "availability_zone": "", 81 | "destroy": false, 82 | "destroy_tainted": false, 83 | "ebs_block_device.#": "", 84 | "ephemeral_block_device.#": "", 85 | "id": "", 86 | "instance_state": "", 87 | "instance_type": "t2.micro", 88 | "ipv6_addresses.#": "", 89 | "key_name": "", 90 | "network_interface_id": "", 91 | "placement_group": "", 92 | "private_dns": "", 93 | "private_ip": "", 94 | "public_dns": "", 95 | "public_ip": "", 96 | "root_block_device.#": "", 97 | "security_groups.#": "", 98 | "source_dest_check": "true", 99 | "subnet_id": "", 100 | "tenancy": "", 101 | "vpc_security_group_ids.#": "", 102 | }, 103 | "aws_instance.puppy": { 104 | "destroy": true, 105 | "destroy_tainted": false, 106 | }, 107 | "destroy": false, 108 | } 109 | 110 | # Create several resources 111 | large_create = { 112 | "aws_autoscaling_group.my_asg": { 113 | "arn": "", 114 | "availability_zones.#": "1", 115 | "availability_zones.3205754986": "us-west-1a", 116 | "default_cooldown": "", 117 | "desired_capacity": "4", 118 | "destroy": false, 119 | "destroy_tainted": false, 120 | "force_delete": "true", 121 | "health_check_grace_period": "300", 122 | "health_check_type": "ELB", 123 | "id": "", 124 | "launch_configuration": "my_web_config", 125 | "load_balancers.#": "", 126 | "max_size": "5", 127 | "metrics_granularity": "1Minute", 128 | "min_size": "1", 129 | "name": "my_asg", 130 | "protect_from_scale_in": "false", 131 | "vpc_zone_identifier.#": "", 132 | "wait_for_capacity_timeout": "10m", 133 | }, 134 | "aws_autoscaling_group.my_asg2": { 135 | "arn": "", 136 | "availability_zones.#": "1", 137 | "availability_zones.2487133097": "us-west-2a", 138 | "default_cooldown": "", 139 | "desired_capacity": "4", 140 | "destroy": false, 141 | "destroy_tainted": false, 142 | "force_delete": "true", 143 | "health_check_grace_period": "300", 144 | "health_check_type": "ELB", 145 | "id": "", 146 | "launch_configuration": "my_web_config", 147 | "load_balancers.#": "", 148 | "max_size": "6", 149 | "metrics_granularity": "1Minute", 150 | "min_size": "1", 151 | "name": "my_asg2", 152 | "protect_from_scale_in": "false", 153 | "vpc_zone_identifier.#": "", 154 | "wait_for_capacity_timeout": "10m", 155 | }, 156 | "aws_autoscaling_group.my_asg3": { 157 | "arn": "", 158 | "availability_zones.#": "1", 159 | "availability_zones.221770259": "us-west-2b", 160 | "default_cooldown": "", 161 | "desired_capacity": "4", 162 | "destroy": false, 163 | "destroy_tainted": false, 164 | "force_delete": "true", 165 | "health_check_grace_period": "300", 166 | "health_check_type": "ELB", 167 | "id": "", 168 | "launch_configuration": "my_web_config", 169 | "load_balancers.#": "", 170 | "max_size": "7", 171 | "metrics_granularity": "1Minute", 172 | "min_size": "1", 173 | "name": "my_asg3", 174 | "protect_from_scale_in": "false", 175 | "vpc_zone_identifier.#": "", 176 | "wait_for_capacity_timeout": "10m", 177 | }, 178 | "aws_instance.web": { 179 | "ami": "ami-09b4b74c", 180 | "associate_public_ip_address": "", 181 | "availability_zone": "", 182 | "destroy": false, 183 | "destroy_tainted": false, 184 | "ebs_block_device.#": "", 185 | "ephemeral_block_device.#": "", 186 | "id": "", 187 | "instance_state": "", 188 | "instance_type": "t2.micro", 189 | "ipv6_addresses.#": "", 190 | "key_name": "", 191 | "network_interface_id": "", 192 | "placement_group": "", 193 | "private_dns": "", 194 | "private_ip": "", 195 | "public_dns": "", 196 | "public_ip": "", 197 | "root_block_device.#": "", 198 | "security_groups.#": "", 199 | "source_dest_check": "true", 200 | "subnet_id": "", 201 | "tenancy": "", 202 | "vpc_security_group_ids.#": "", 203 | }, 204 | "aws_launch_configuration.my_web_config": { 205 | "associate_public_ip_address": "false", 206 | "destroy": false, 207 | "destroy_tainted": false, 208 | "ebs_block_device.#": "", 209 | "ebs_optimized": "", 210 | "enable_monitoring": "true", 211 | "id": "", 212 | "image_id": "ami-09b4b74c", 213 | "instance_type": "t2.micro", 214 | "key_name": "", 215 | "name": "my_web_config", 216 | "root_block_device.#": "", 217 | }, 218 | "destroy": false, 219 | } 220 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /kubernetes/mutating-admission/test_mutation.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.mutating 2 | 3 | import data.library.kubernetes.admission.mutating.test as k8s 4 | 5 | ############################################################ 6 | # PATCH helper tests 7 | ############################################################ 8 | 9 | #----------------------------------------------------------- 10 | # Test: hasLabels is true when there are labels 11 | #----------------------------------------------------------- 12 | test_hasLabels_true { 13 | hasLabels(k8s.object_with_label_foo_bar) 14 | } 15 | 16 | #----------------------------------------------------------- 17 | # Test: hasLabels is false when there are no labels 18 | #----------------------------------------------------------- 19 | test_no_labels_true { 20 | not hasLabels(k8s.object_without_labels) 21 | } 22 | 23 | #----------------------------------------------------------- 24 | # Test: hasLabel is true when the label exists 25 | #----------------------------------------------------------- 26 | test_hasLabel_foo { 27 | hasLabel(k8s.object_with_label_foo_bar, "foo") 28 | } 29 | 30 | #----------------------------------------------------------- 31 | # Test: hasLabel is false when the label doesn't exist 32 | #----------------------------------------------------------- 33 | test_not_hasLabel_foo1 { 34 | not hasLabel(k8s.object_with_label_foo_bar, "foo1") 35 | } 36 | 37 | #----------------------------------------------------------- 38 | # Test: hasLabelValue is true when the label has the correct value 39 | #----------------------------------------------------------- 40 | test_hasLabelValue_fooeqbar { 41 | hasLabelValue(k8s.object_with_label_foo_bar, "foo", "bar") 42 | } 43 | 44 | #----------------------------------------------------------- 45 | # Test: hasAnnotations is true when there are annotations 46 | #----------------------------------------------------------- 47 | test_hasAnnotations_true { 48 | hasAnnotations(k8s.object_with_annotation_foo_bar) 49 | } 50 | 51 | #----------------------------------------------------------- 52 | # Test: hasAnnotations is false when there are no annotations 53 | #----------------------------------------------------------- 54 | test_no_annotations_true { 55 | not hasAnnotations(k8s.object_without_annotations) 56 | } 57 | 58 | #----------------------------------------------------------- 59 | # Test: hasAnnotation is true when the annotation exists 60 | #----------------------------------------------------------- 61 | test_hasAnnotation_foo { 62 | hasAnnotation(k8s.object_with_annotation_foo_bar, "foo") 63 | } 64 | 65 | #----------------------------------------------------------- 66 | # Test: hasAnnotation is false when the annotation doesn't exist 67 | #----------------------------------------------------------- 68 | test_not_hasAnnotation_foo1 { 69 | not hasAnnotation(k8s.object_with_annotation_foo_bar, "foo1") 70 | } 71 | 72 | #----------------------------------------------------------- 73 | # Test: hasAnnotationValue is true when the annotation has the correct value 74 | #----------------------------------------------------------- 75 | test_hasAnnotation_fooeqbar { 76 | hasAnnotationValue(k8s.object_with_annotation_foo_bar, "foo", "bar") 77 | } 78 | 79 | #----------------------------------------------------------- 80 | # Test: makeLabelPatch creates a valid patch 81 | #----------------------------------------------------------- 82 | test_makeLabelPatch { 83 | l := makeLabelPatch("add", "foo", "bar", "") with input as k8s.object_with_label_foo_bar 84 | l = {"op": "add", "path": "/metadata/labels/foo", "value": "bar"} 85 | 86 | # test pathPrefix e.g. if the label is on the Pod template in a Deployment 87 | m := makeLabelPatch("add", "foo", "bar", "/spec/template") with input as k8s.object_with_label_foo_bar 88 | m = {"op": "add", "path": "/spec/template/metadata/labels/foo", "value": "bar"} 89 | } 90 | 91 | ############################################################ 92 | # PATCH tests 93 | ############################################################ 94 | 95 | #----------------------------------------------------------- 96 | # Sample patch values to test against 97 | #----------------------------------------------------------- 98 | patchCode_labels_base = { 99 | "op": "add", 100 | "path": "/metadata/labels", 101 | "value": {}, 102 | } 103 | 104 | patchCode_label_foobar = { 105 | "op": "add", 106 | "path": "/metadata/labels/foo", 107 | "value": "bar", 108 | } 109 | 110 | patchCode_label_bazquux = { 111 | "op": "add", 112 | "path": "/metadata/labels/baz", 113 | "value": "quux", 114 | } 115 | 116 | patchCode_label_quuzcorge = { 117 | "op": "add", 118 | "path": "/metadata/labels/quuz", 119 | "value": "corge", 120 | } 121 | 122 | patchCode_annotations_base = { 123 | "op": "add", 124 | "path": "/metadata/annotations", 125 | "value": {}, 126 | } 127 | 128 | patchCode_annotation_rating = { 129 | "op": "add", 130 | "path": "/metadata/annotations/dogs.io~1rating", 131 | "value": "14/10", 132 | } 133 | 134 | hasPatch(patches, patch) { 135 | patches[_] = patch 136 | } 137 | 138 | isPatchResponse(res) { 139 | res.response.patchType = "JSONPatch" 140 | res.response.patch 141 | } 142 | 143 | #----------------------------------------------------------- 144 | # Test: patches are created for Dogs with no labels 145 | #----------------------------------------------------------- 146 | test_main_dog_no_labels_or_annotations { 147 | res := main with input as k8s.request_dog_no_labels_or_annotations 148 | res.response.allowed = true 149 | isPatchResponse(res) 150 | patches = json.unmarshal(base64.decode(res.response.patch)) 151 | trace(sprintf("[test_main_dog_no_labels] patches = '%s'", [patches])) 152 | hasPatch(patches, patchCode_labels_base) 153 | hasPatch(patches, patchCode_label_foobar) 154 | hasPatch(patches, patchCode_annotations_base) 155 | hasPatch(patches, patchCode_annotation_rating) 156 | } 157 | 158 | #----------------------------------------------------------- 159 | # Test: patches are created for Dogs with existing labels but not foo 160 | #----------------------------------------------------------- 161 | test_main_dog_some_labels { 162 | res := main with input as k8s.request_dog_some_labels_and_annotations 163 | res.response.allowed = true 164 | isPatchResponse(res) 165 | patches = json.unmarshal(base64.decode(res.response.patch)) 166 | trace(sprintf("[test_main_dog_some_labels] patches = '%s'", [patches])) 167 | not hasPatch(patches, patchCode_labels_base) 168 | hasPatch(patches, patchCode_label_foobar) 169 | not hasPatch(patches, patchCode_annotations_base) 170 | hasPatch(patches, patchCode_annotation_rating) 171 | } 172 | 173 | #----------------------------------------------------------- 174 | # Test: patches are not created for Dogs with existing labels foo and quuz and annotation rating 175 | # We need to test for either no patches at all are created, or 176 | # if some other rule creates some patches, it's not trying to 177 | # add any that already exist 178 | #----------------------------------------------------------- 179 | test_main_dog_existing_labels_and_annotations { 180 | res := main with input as k8s.request_dog_existing_labels_and_annotations 181 | trace(sprintf("[test_main_dog_existing_labels_and_annotations] res = '%s'", [res])) 182 | res.response.allowed = true 183 | t_main_dog_existing_labels_and_annotations_detail with input as res 184 | } 185 | 186 | t_main_dog_existing_labels_and_annotations_detail { 187 | not input.response.patchType 188 | trace("[t_main_dog_existing_labels_and_annotations] patchType not set") 189 | } 190 | 191 | t_main_dog_existing_labels_and_annotations_detail { 192 | input.response.patchType = "JSONPatch" 193 | input.response.patch 194 | patches = json.unmarshal(base64.decode(input.response.patch)) 195 | trace(sprintf("[t_main_dog_existing_labels_and_annotations] patches = '%s'", [patches])) 196 | not hasPatch(patches, patchCode_labels_base) 197 | not hasPatch(patches, patchCode_label_foobar) 198 | not hasPatch(patches, patchCode_label_quuzcorge) 199 | not hasPatch(patches, patchCode_annotations_base) 200 | not hasPatch(patches, patchCode_annotation_rating) 201 | } 202 | 203 | #----------------------------------------------------------- 204 | # Test: patches are created for Dogs wanting more labels 205 | #----------------------------------------------------------- 206 | test_main_dog_missing_label_quuzcorge { 207 | res := main with input as k8s.request_dog_some_labels_and_annotations 208 | res.response.allowed = true 209 | res.response.patchType = "JSONPatch" 210 | patches = json.unmarshal(base64.decode(res.response.patch)) 211 | trace(sprintf("[test_main_dog_good_missing_label_quuzcorge] patches = '%s'", [patches])) 212 | hasPatch(patches, patchCode_label_quuzcorge) 213 | } 214 | 215 | #----------------------------------------------------------- 216 | # Test: patches are created for Dogs with no anotations 217 | #----------------------------------------------------------- 218 | test_main_dog_add_first_annotation { 219 | res := main with input as k8s.request_dog_no_labels_or_annotations 220 | res.response.allowed = true 221 | res.response.patchType = "JSONPatch" 222 | patches = json.unmarshal(base64.decode(res.response.patch)) 223 | trace(sprintf("[test_main_dog_add_first_annotation] patches = '%s'", [patches])) 224 | hasPatch(patches, patchCode_annotations_base) 225 | hasPatch(patches, patchCode_annotation_rating) 226 | } 227 | 228 | #----------------------------------------------------------- 229 | # Test: patches are created for Dogs with existing annotation 230 | #----------------------------------------------------------- 231 | test_main_dog_add_subsequent_annotation { 232 | res := main with input as k8s.request_dog_some_labels_and_annotations 233 | res.response.allowed = true 234 | res.response.patchType = "JSONPatch" 235 | patches = json.unmarshal(base64.decode(res.response.patch)) 236 | trace(sprintf("[test_main_dog_add_subsequent_annotation] patches = '%s'", [patches])) 237 | not hasPatch(patches, patchCode_annotations_base) 238 | hasPatch(patches, patchCode_annotation_rating) 239 | } 240 | 241 | #----------------------------------------------------------- 242 | # Test: ensureParentPathsExist 243 | #----------------------------------------------------------- 244 | test_ensureParentPathsExist_array { 245 | actual := ensureParentPathsExist([{"op": "replace", "path": "/spec/template/spec/containers/0/imagePullPolicy", "value": "IfNotPresent"}]) with input as {"request": {"object": {"spec": {"template": {"spec": {"containers": [{"foo": "bar"}]}}}}}} 246 | 247 | correct := [{"op": "replace", "path": "/spec/template/spec/containers/0/imagePullPolicy", "value": "IfNotPresent"}] 248 | 249 | actual == correct 250 | } 251 | 252 | test_ensureParentPathsExist_noop { 253 | actual := ensureParentPathsExist([{"op": "add", "path": "/metadata/labels/foo", "value": "bar"}]) with input as k8s.request_dog_some_labels_and_annotations 254 | 255 | correct := [{"op": "add", "path": "/metadata/labels/foo", "value": "bar"}] 256 | 257 | actual == correct 258 | } 259 | 260 | test_ensureParentPathsExist_noop_multi { 261 | actual := ensureParentPathsExist([ 262 | {"op": "add", "path": "/metadata/labels/foo", "value": "bar"}, 263 | {"op": "add", "path": "/metadata/labels/bar", "value": "bar"}, 264 | ]) with input as k8s.request_dog_some_labels_and_annotations 265 | 266 | correct := [ 267 | {"op": "add", "path": "/metadata/labels/foo", "value": "bar"}, 268 | {"op": "add", "path": "/metadata/labels/bar", "value": "bar"}, 269 | ] 270 | 271 | actual == correct 272 | } 273 | 274 | test_ensureParentPathsExist_simple { 275 | actual := ensureParentPathsExist([{"op": "add", "path": "/metadata/labels/foo/bar", "value": "baz"}]) with input as k8s.request_dog_some_labels_and_annotations 276 | 277 | correct := [ 278 | {"op": "add", "path": "/metadata/labels/foo", "value": {}}, 279 | {"op": "add", "path": "/metadata/labels/foo/bar", "value": "baz"}, 280 | ] 281 | 282 | actual == correct 283 | } 284 | 285 | test_ensureParentPathsExist_simple_multi { 286 | actual := ensureParentPathsExist([ 287 | {"op": "add", "path": "/metadata/labels/foo/bar", "value": "baz"}, 288 | {"op": "add", "path": "/metadata/labels/foo/baz", "value": "baz"}, 289 | ]) with input as k8s.request_dog_some_labels_and_annotations 290 | 291 | correct := [ 292 | {"op": "add", "path": "/metadata/labels/foo", "value": {}}, 293 | {"op": "add", "path": "/metadata/labels/foo/bar", "value": "baz"}, 294 | {"op": "add", "path": "/metadata/labels/foo/baz", "value": "baz"}, 295 | ] 296 | 297 | actual == correct 298 | } 299 | 300 | test_ensureParentPathsExist_long_multi { 301 | actual := ensureParentPathsExist([ 302 | {"op": "add", "path": "/metadata/labels/foo/bar/abc", "value": "def"}, 303 | {"op": "add", "path": "/metadata/labels/foo/bar/baz/qux", "value": "abc"}, 304 | {"op": "add", "path": "/metadata/labels/foo/bar/baz/abc", "value": "def"}, 305 | {"op": "add", "path": "/metadata/labels/foo/bar/def", "value": "ghi"}, 306 | {"op": "add", "path": "/metadata/annot/foo/bar/def", "value": "ghi"}, 307 | {"op": "add", "path": "/root/foo/bar/def", "value": "ghi"}, 308 | ]) with input as k8s.request_dog_some_labels_and_annotations 309 | 310 | correct := [ 311 | # new 312 | {"op": "add", "path": "/metadata/annot", "value": {}}, 313 | {"op": "add", "path": "/metadata/annot/foo", "value": {}}, 314 | {"op": "add", "path": "/metadata/annot/foo/bar", "value": {}}, 315 | {"op": "add", "path": "/metadata/labels/foo", "value": {}}, 316 | {"op": "add", "path": "/metadata/labels/foo/bar", "value": {}}, 317 | {"op": "add", "path": "/metadata/labels/foo/bar/baz", "value": {}}, 318 | {"op": "add", "path": "/root", "value": {}}, 319 | {"op": "add", "path": "/root/foo", "value": {}}, 320 | {"op": "add", "path": "/root/foo/bar", "value": {}}, 321 | # originals 322 | {"op": "add", "path": "/metadata/labels/foo/bar/abc", "value": "def"}, 323 | {"op": "add", "path": "/metadata/labels/foo/bar/baz/qux", "value": "abc"}, 324 | {"op": "add", "path": "/metadata/labels/foo/bar/baz/abc", "value": "def"}, 325 | {"op": "add", "path": "/metadata/labels/foo/bar/def", "value": "ghi"}, 326 | {"op": "add", "path": "/metadata/annot/foo/bar/def", "value": "ghi"}, 327 | {"op": "add", "path": "/root/foo/bar/def", "value": "ghi"}, 328 | ] 329 | 330 | actual == correct 331 | } 332 | -------------------------------------------------------------------------------- /kubernetes/mutating-admission/data_kubernetes.rego: -------------------------------------------------------------------------------- 1 | package library.kubernetes.admission.mutating.test 2 | 3 | request_default = { 4 | "kind": "AdmissionReview", 5 | "apiVersion": "admission.k8s.io/v1", 6 | "request": {""}, 7 | } 8 | 9 | # Using a CRD for a resource called Dog, with a CRD definition as follows: 10 | # apiVersion: apiextensions.k8s.io/v1beta1 11 | # kind: CustomResourceDefinition 12 | # metadata: 13 | # name: dogs.frens.teq0.com 14 | # spec: 15 | # group: frens.teq0.com 16 | # versions: 17 | # - name: v1 18 | # served: true 19 | # storage: true 20 | # version: v1 21 | # scope: Cluster 22 | # names: 23 | # plural: dogs 24 | # singular: dog 25 | # kind: Dog 26 | # shortNames: 27 | # - dogue 28 | # validation: 29 | # openAPIV3Schema: 30 | # properties: 31 | # spec: 32 | # properties: 33 | # name: 34 | # type: string 35 | # isGood: 36 | # type: boolean 37 | # food: 38 | # type: string 39 | 40 | request_dog_good = { 41 | "kind": "AdmissionReview", 42 | "apiVersion": "admission.k8s.io/v1beta1", 43 | "request": { 44 | "uid": "836c0cc6-096c-11e9-9a47-080027f60d22", 45 | "kind": { 46 | "group": "frens.teq0.com", 47 | "version": "v1", 48 | "kind": "Dog", 49 | }, 50 | "resource": { 51 | "group": "frens.teq0.com", 52 | "version": "v1", 53 | "resource": "dogs", 54 | }, 55 | "name": "spike", 56 | "operation": "UPDATE", 57 | "userInfo": { 58 | "username": "minikube-user", 59 | "groups": [ 60 | "system:masters", 61 | "system:authenticated", 62 | ], 63 | }, 64 | "object": { 65 | "apiVersion": "frens.teq0.com/v1", 66 | "kind": "Dog", 67 | "metadata": { 68 | "annotations": {"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"frens.teq0.com/v1\",\"kind\":\"Dog\",\"metadata\":{\"annotations\":{},\"labels\":{\"foo\":\"bar1\"},\"name\":\"rex\",\"namespace\":\"\"},\"spec\":{\"food\":\"meat\",\"isGood\":false,\"name\":\"Rex\"}}\n"}, 69 | "creationTimestamp": "2018-12-26T02:36:30Z", 70 | "generation": 1, 71 | "labels": {"foo": "bar"}, 72 | "name": "spike", 73 | "resourceVersion": "61919", 74 | "uid": "0d0f9b6a-08b7-11e9-9a47-080027f60d22", 75 | }, 76 | "spec": { 77 | "food": "meat", 78 | "isGood": true, 79 | "name": "Spike", 80 | }, 81 | }, 82 | "oldObject": { 83 | "apiVersion": "frens.teq0.com/v1", 84 | "kind": "Dog", 85 | "metadata": { 86 | "annotations": {"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"frens.teq0.com/v1\",\"kind\":\"Dog\",\"metadata\":{\"annotations\":{},\"labels\":{\"foo\":\"bar1\"},\"name\":\"rex\",\"namespace\":\"\"},\"spec\":{\"food\":\"meat\",\"isGood\":false,\"name\":\"Rex\"}}\n"}, 87 | "creationTimestamp": "2018-12-26T02:36:30Z", 88 | "generation": 1, 89 | "labels": {"foo": "bar1"}, 90 | "name": "spike", 91 | "resourceVersion": "61919", 92 | "uid": "0d0f9b6a-08b7-11e9-9a47-080027f60d22", 93 | }, 94 | "spec": { 95 | "food": "meat", 96 | "isGood": false, 97 | "name": "Spike", 98 | }, 99 | }, 100 | "dryRun": false, 101 | }, 102 | } 103 | 104 | request_dog_some_labels_and_annotations = { 105 | "kind": "AdmissionReview", 106 | "apiVersion": "admission.k8s.io/v1beta1", 107 | "request": { 108 | "uid": "836c0cc6-096c-11e9-9a47-080027f60d22", 109 | "kind": { 110 | "group": "frens.teq0.com", 111 | "version": "v1", 112 | "kind": "Dog", 113 | }, 114 | "resource": { 115 | "group": "frens.teq0.com", 116 | "version": "v1", 117 | "resource": "dogs", 118 | }, 119 | "name": "spike", 120 | "operation": "UPDATE", 121 | "userInfo": { 122 | "username": "minikube-user", 123 | "groups": [ 124 | "system:masters", 125 | "system:authenticated", 126 | ], 127 | }, 128 | "object": { 129 | "apiVersion": "frens.teq0.com/v1", 130 | "kind": "Dog", 131 | "metadata": { 132 | "annotations": { 133 | "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"frens.teq0.com/v1\",\"kind\":\"Dog\",\"metadata\":{\"annotations\":{},\"labels\":{\"foo\":\"bar1\"},\"name\":\"rex\",\"namespace\":\"\"},\"spec\":{\"food\":\"meat\",\"isGood\":false,\"name\":\"Rex\"}}\n", 134 | "allthethings": "automate", 135 | }, 136 | "labels": { 137 | "gamma-rays": "on", 138 | "yobba-rays": "on", 139 | "moar-labels": "pleez", 140 | }, 141 | "creationTimestamp": "2018-12-26T02:36:30Z", 142 | "generation": 1, 143 | "name": "spike", 144 | "resourceVersion": "61919", 145 | "uid": "0d0f9b6a-08b7-11e9-9a47-080027f60d22", 146 | }, 147 | "spec": { 148 | "food": "meat", 149 | "isGood": true, 150 | "name": "Spike", 151 | }, 152 | }, 153 | "oldObject": { 154 | "apiVersion": "frens.teq0.com/v1", 155 | "kind": "Dog", 156 | "metadata": { 157 | "annotations": {"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"frens.teq0.com/v1\",\"kind\":\"Dog\",\"metadata\":{\"annotations\":{},\"labels\":{\"foo\":\"bar1\"},\"name\":\"rex\",\"namespace\":\"\"},\"spec\":{\"food\":\"meat\",\"isGood\":false,\"name\":\"Rex\"}}\n"}, 158 | "creationTimestamp": "2018-12-26T02:36:30Z", 159 | "generation": 1, 160 | "name": "spike", 161 | "resourceVersion": "61919", 162 | "uid": "0d0f9b6a-08b7-11e9-9a47-080027f60d22", 163 | }, 164 | "spec": { 165 | "food": "meat", 166 | "isGood": false, 167 | "name": "Spike", 168 | }, 169 | }, 170 | "dryRun": false, 171 | }, 172 | } 173 | 174 | request_dog_existing_labels_and_annotations = { 175 | "kind": "AdmissionReview", 176 | "apiVersion": "admission.k8s.io/v1beta1", 177 | "request": { 178 | "uid": "836c0cc6-096c-11e9-9a47-080027f60d22", 179 | "kind": { 180 | "group": "frens.teq0.com", 181 | "version": "v1", 182 | "kind": "Dog", 183 | }, 184 | "resource": { 185 | "group": "frens.teq0.com", 186 | "version": "v1", 187 | "resource": "dogs", 188 | }, 189 | "name": "spike", 190 | "operation": "UPDATE", 191 | "userInfo": { 192 | "username": "minikube-user", 193 | "groups": [ 194 | "system:masters", 195 | "system:authenticated", 196 | ], 197 | }, 198 | "object": { 199 | "apiVersion": "frens.teq0.com/v1", 200 | "kind": "Dog", 201 | "metadata": { 202 | "annotations": {"dogs.io/rating": "14/10"}, 203 | "labels": { 204 | "foo": "bar", 205 | "quuz": "corge", 206 | }, 207 | "creationTimestamp": "2018-12-26T02:36:30Z", 208 | "generation": 1, 209 | "name": "spike", 210 | "resourceVersion": "61919", 211 | "uid": "0d0f9b6a-08b7-11e9-9a47-080027f60d22", 212 | }, 213 | "spec": { 214 | "food": "meat", 215 | "isGood": true, 216 | "name": "Spike", 217 | }, 218 | }, 219 | "oldObject": { 220 | "apiVersion": "frens.teq0.com/v1", 221 | "kind": "Dog", 222 | "metadata": { 223 | "annotations": {"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"frens.teq0.com/v1\",\"kind\":\"Dog\",\"metadata\":{\"annotations\":{},\"labels\":{\"foo\":\"bar1\"},\"name\":\"rex\",\"namespace\":\"\"},\"spec\":{\"food\":\"meat\",\"isGood\":false,\"name\":\"Rex\"}}\n"}, 224 | "creationTimestamp": "2018-12-26T02:36:30Z", 225 | "generation": 1, 226 | "name": "spike", 227 | "resourceVersion": "61919", 228 | "uid": "0d0f9b6a-08b7-11e9-9a47-080027f60d22", 229 | }, 230 | "spec": { 231 | "food": "meat", 232 | "isGood": false, 233 | "name": "Spike", 234 | }, 235 | }, 236 | "dryRun": false, 237 | }, 238 | } 239 | 240 | request_dog_no_labels_or_annotations = { 241 | "kind": "AdmissionReview", 242 | "apiVersion": "admission.k8s.io/v1beta1", 243 | "request": { 244 | "uid": "836c0cc6-096c-11e9-9a47-080027f60d22", 245 | "kind": { 246 | "group": "frens.teq0.com", 247 | "version": "v1", 248 | "kind": "Dog", 249 | }, 250 | "resource": { 251 | "group": "frens.teq0.com", 252 | "version": "v1", 253 | "resource": "dogs", 254 | }, 255 | "name": "spike", 256 | "operation": "UPDATE", 257 | "userInfo": { 258 | "username": "minikube-user", 259 | "groups": [ 260 | "system:masters", 261 | "system:authenticated", 262 | ], 263 | }, 264 | "object": { 265 | "apiVersion": "frens.teq0.com/v1", 266 | "kind": "Dog", 267 | "metadata": { 268 | "creationTimestamp": "2018-12-26T02:36:30Z", 269 | "generation": 1, 270 | "name": "spike", 271 | "resourceVersion": "61919", 272 | "uid": "0d0f9b6a-08b7-11e9-9a47-080027f60d22", 273 | }, 274 | "spec": { 275 | "food": "meat", 276 | "isGood": true, 277 | "name": "Spike", 278 | }, 279 | }, 280 | "oldObject": { 281 | "apiVersion": "frens.teq0.com/v1", 282 | "kind": "Dog", 283 | "metadata": { 284 | "creationTimestamp": "2018-12-26T02:36:30Z", 285 | "generation": 1, 286 | "name": "spike", 287 | "resourceVersion": "61919", 288 | "uid": "0d0f9b6a-08b7-11e9-9a47-080027f60d22", 289 | }, 290 | "spec": { 291 | "food": "meat", 292 | "isGood": false, 293 | "name": "Spike", 294 | }, 295 | }, 296 | "dryRun": false, 297 | }, 298 | } 299 | 300 | request_dog_bad = { 301 | "kind": "AdmissionReview", 302 | "apiVersion": "admission.k8s.io/v1beta1", 303 | "request": { 304 | "uid": "836c0cc6-096c-11e9-9a47-080027f60d22", 305 | "kind": { 306 | "group": "frens.teq0.com", 307 | "version": "v1", 308 | "kind": "Dog", 309 | }, 310 | "resource": { 311 | "group": "frens.teq0.com", 312 | "version": "v1", 313 | "resource": "dogs", 314 | }, 315 | "name": "rex", 316 | "operation": "UPDATE", 317 | "userInfo": { 318 | "username": "minikube-user", 319 | "groups": [ 320 | "system:masters", 321 | "system:authenticated", 322 | ], 323 | }, 324 | "object": { 325 | "apiVersion": "frens.teq0.com/v1", 326 | "kind": "Dog", 327 | "metadata": { 328 | "annotations": {"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"frens.teq0.com/v1\",\"kind\":\"Dog\",\"metadata\":{\"annotations\":{},\"labels\":{\"foo\":\"bar1\"},\"name\":\"rex\",\"namespace\":\"\"},\"spec\":{\"food\":\"meat\",\"isGood\":false,\"name\":\"Rex\"}}\n"}, 329 | "creationTimestamp": "2018-12-26T02:36:30Z", 330 | "generation": 1, 331 | "labels": {"foo": "bar1"}, 332 | "name": "rex", 333 | "resourceVersion": "61919", 334 | "uid": "0d0f9b6a-08b7-11e9-9a47-080027f60d22", 335 | }, 336 | "spec": { 337 | "food": "meat", 338 | "isGood": false, 339 | "name": "Rex", 340 | }, 341 | }, 342 | "oldObject": { 343 | "apiVersion": "frens.teq0.com/v1", 344 | "kind": "Dog", 345 | "metadata": { 346 | "annotations": {"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"frens.teq0.com/v1\",\"kind\":\"Dog\",\"metadata\":{\"annotations\":{},\"labels\":{\"foo\":\"bar1\"},\"name\":\"rex\",\"namespace\":\"\"},\"spec\":{\"food\":\"meat\",\"isGood\":false,\"name\":\"Rex\"}}\n"}, 347 | "creationTimestamp": "2018-12-26T02:36:30Z", 348 | "generation": 1, 349 | "labels": {"foo1": "bar1"}, 350 | "name": "rex", 351 | "resourceVersion": "61919", 352 | "uid": "0d0f9b6a-08b7-11e9-9a47-080027f60d22", 353 | }, 354 | "spec": { 355 | "food": "meat", 356 | "isGood": false, 357 | "name": "Rex", 358 | }, 359 | }, 360 | "dryRun": false, 361 | }, 362 | } 363 | 364 | # Simple sub-objects for testing the helper functions 365 | object_with_label_foo_bar = {"metadata": {"labels": {"foo": "bar"}}} 366 | 367 | object_without_labels = {"metadata": {"annotations": {"foo": "bar"}}} 368 | 369 | object_with_annotation_foo_bar = {"metadata": {"annotations": {"foo": "bar"}}} 370 | 371 | object_without_annotations = {"metadata": {"labels": {"foo": "bar"}}} 372 | 373 | object_without_labels_or_annotations = {"metadata": {}} 374 | 375 | # Standard K8s Deployment requests 376 | 377 | request_deployment_no_versions = { 378 | "kind": "AdmissionReview", 379 | "apiVersion": "admission.k8s.io/v1beta1", 380 | "request": { 381 | "uid": "7916f3dc-1393-11e9-8ef2-080027da5735", 382 | "kind": { 383 | "group": "extensions", 384 | "version": "v1beta1", 385 | "kind": "Deployment", 386 | }, 387 | "resource": { 388 | "group": "extensions", 389 | "version": "v1beta1", 390 | "resource": "deployments", 391 | }, 392 | "namespace": "default", 393 | "operation": "CREATE", 394 | "userInfo": { 395 | "username": "minikube-user", 396 | "groups": [ 397 | "system:masters", 398 | "system:authenticated", 399 | ], 400 | }, 401 | "object": { 402 | "metadata": { 403 | "name": "deployment-demo-bad-no-version", 404 | "namespace": "default", 405 | "creationTimestamp": null, 406 | "labels": { 407 | "demo": "deployment", 408 | "version": "v1", 409 | }, 410 | "annotations": {"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"extensions/v1beta1\",\"kind\":\"Deployment\",\"metadata\":{\"annotations\":{},\"name\":\"deployment-demo-bad-no-version\",\"namespace\":\"default\"},\"spec\":{\"replicas\":2,\"selector\":{\"matchLabels\":{\"demo\":\"deployment\"}},\"strategy\":{\"rollingUpdate\":{\"maxSurge\":1,\"maxUnavailable\":0},\"type\":\"RollingUpdate\"},\"template\":{\"metadata\":{\"labels\":{\"demo\":\"deployment\",\"version\":\"v1\"}},\"spec\":{\"containers\":[{\"command\":[\"sh\",\"-c\",\"while true; do echo $(hostname) v1 \\u003e /data/index.html; sleep 60; done\"],\"image\":\"busybox\",\"name\":\"busybox\",\"volumeMounts\":[{\"mountPath\":\"/data\",\"name\":\"content\"}]},{\"image\":\"nginx\",\"name\":\"nginx\",\"volumeMounts\":[{\"mountPath\":\"/usr/share/nginx/html\",\"name\":\"content\",\"readOnly\":true}]}],\"volumes\":[{\"name\":\"content\"}]}}}}\n"}, 411 | }, 412 | "spec": { 413 | "replicas": 2, 414 | "selector": {"matchLabels": {"demo": "deployment"}}, 415 | "template": { 416 | "metadata": { 417 | "creationTimestamp": null, 418 | "labels": { 419 | "demo": "deployment", 420 | "version": "v1", 421 | }, 422 | }, 423 | "spec": { 424 | "volumes": [{ 425 | "name": "content", 426 | "emptyDir": {}, 427 | }], 428 | "containers": [ 429 | { 430 | "name": "busybox", 431 | "image": "busybox", 432 | "command": [ 433 | "sh", 434 | "-c", 435 | "while true; do echo $(hostname) v1 > /data/index.html; sleep 60; done", 436 | ], 437 | "resources": {}, 438 | "volumeMounts": [{ 439 | "name": "content", 440 | "mountPath": "/data", 441 | }], 442 | "terminationMessagePath": "/dev/termination-log", 443 | "terminationMessagePolicy": "File", 444 | "imagePullPolicy": "Always", 445 | }, 446 | { 447 | "name": "nginx", 448 | "image": "nginx", 449 | "resources": {}, 450 | "volumeMounts": [{ 451 | "name": "content", 452 | "readOnly": true, 453 | "mountPath": "/usr/share/nginx/html", 454 | }], 455 | "terminationMessagePath": "/dev/termination-log", 456 | "terminationMessagePolicy": "File", 457 | "imagePullPolicy": "Always", 458 | }, 459 | ], 460 | "restartPolicy": "Always", 461 | "terminationGracePeriodSeconds": 30, 462 | "dnsPolicy": "ClusterFirst", 463 | "securityContext": {}, 464 | "schedulerName": "default-scheduler", 465 | }, 466 | }, 467 | "strategy": { 468 | "type": "RollingUpdate", 469 | "rollingUpdate": { 470 | "maxUnavailable": 0, 471 | "maxSurge": 1, 472 | }, 473 | }, 474 | "revisionHistoryLimit": 2147483647, 475 | "progressDeadlineSeconds": 2147483647, 476 | }, 477 | "status": {}, 478 | }, 479 | "oldObject": null, 480 | "dryRun": false, 481 | }, 482 | } 483 | 484 | request_deployment_with_versions = { 485 | "kind": "AdmissionReview", 486 | "apiVersion": "admission.k8s.io/v1beta1", 487 | "request": { 488 | "uid": "7916f3dc-1393-11e9-8ef2-080027da5735", 489 | "kind": { 490 | "group": "extensions", 491 | "version": "v1beta1", 492 | "kind": "Deployment", 493 | }, 494 | "resource": { 495 | "group": "extensions", 496 | "version": "v1beta1", 497 | "resource": "deployments", 498 | }, 499 | "namespace": "default", 500 | "operation": "CREATE", 501 | "userInfo": { 502 | "username": "minikube-user", 503 | "groups": [ 504 | "system:masters", 505 | "system:authenticated", 506 | ], 507 | }, 508 | "object": { 509 | "metadata": { 510 | "name": "deployment-demo-bad-no-version", 511 | "namespace": "default", 512 | "creationTimestamp": null, 513 | "labels": { 514 | "demo": "deployment", 515 | "version": "v1", 516 | }, 517 | "annotations": {"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"extensions/v1beta1\",\"kind\":\"Deployment\",\"metadata\":{\"annotations\":{},\"name\":\"deployment-demo-bad-no-version\",\"namespace\":\"default\"},\"spec\":{\"replicas\":2,\"selector\":{\"matchLabels\":{\"demo\":\"deployment\"}},\"strategy\":{\"rollingUpdate\":{\"maxSurge\":1,\"maxUnavailable\":0},\"type\":\"RollingUpdate\"},\"template\":{\"metadata\":{\"labels\":{\"demo\":\"deployment\",\"version\":\"v1\"}},\"spec\":{\"containers\":[{\"command\":[\"sh\",\"-c\",\"while true; do echo $(hostname) v1 \\u003e /data/index.html; sleep 60; done\"],\"image\":\"busybox\",\"name\":\"busybox\",\"volumeMounts\":[{\"mountPath\":\"/data\",\"name\":\"content\"}]},{\"image\":\"nginx\",\"name\":\"nginx\",\"volumeMounts\":[{\"mountPath\":\"/usr/share/nginx/html\",\"name\":\"content\",\"readOnly\":true}]}],\"volumes\":[{\"name\":\"content\"}]}}}}\n"}, 518 | }, 519 | "spec": { 520 | "replicas": 2, 521 | "selector": {"matchLabels": {"demo": "deployment"}}, 522 | "template": { 523 | "metadata": { 524 | "creationTimestamp": null, 525 | "labels": { 526 | "demo": "deployment", 527 | "version": "v1", 528 | }, 529 | }, 530 | "spec": { 531 | "volumes": [{ 532 | "name": "content", 533 | "emptyDir": {}, 534 | }], 535 | "containers": [ 536 | { 537 | "name": "busybox", 538 | "image": "busybox:1.30.0", 539 | "command": [ 540 | "sh", 541 | "-c", 542 | "while true; do echo $(hostname) v1 > /data/index.html; sleep 60; done", 543 | ], 544 | "resources": {}, 545 | "volumeMounts": [{ 546 | "name": "content", 547 | "mountPath": "/data", 548 | }], 549 | "terminationMessagePath": "/dev/termination-log", 550 | "terminationMessagePolicy": "File", 551 | "imagePullPolicy": "Always", 552 | }, 553 | { 554 | "name": "nginx", 555 | "image": "nginx:1.15.8", 556 | "resources": {}, 557 | "volumeMounts": [{ 558 | "name": "content", 559 | "readOnly": true, 560 | "mountPath": "/usr/share/nginx/html", 561 | }], 562 | "terminationMessagePath": "/dev/termination-log", 563 | "terminationMessagePolicy": "File", 564 | "imagePullPolicy": "Always", 565 | }, 566 | ], 567 | "restartPolicy": "Always", 568 | "terminationGracePeriodSeconds": 30, 569 | "dnsPolicy": "ClusterFirst", 570 | "securityContext": {}, 571 | "schedulerName": "default-scheduler", 572 | }, 573 | }, 574 | "strategy": { 575 | "type": "RollingUpdate", 576 | "rollingUpdate": { 577 | "maxUnavailable": 0, 578 | "maxSurge": 1, 579 | }, 580 | }, 581 | "revisionHistoryLimit": 2147483647, 582 | "progressDeadlineSeconds": 2147483647, 583 | }, 584 | "status": {}, 585 | }, 586 | "oldObject": null, 587 | "dryRun": false, 588 | }, 589 | } 590 | --------------------------------------------------------------------------------