Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for namespaceselector #131

Merged
merged 2 commits into from
Jun 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ Note the `match` field, which defines the scope of objects to which a given cons
* `kinds` accepts a list of objects with `apiGroups` and `kinds` fields that list the groups/kinds of objects to which the constraint will apply. If multiple groups/kinds objects are specified, only one match is needed for the resource to be in scope.
* `namespaces` is a list of namespace names. If defined, a constraint will only apply to resources in a listed namespace.
* `labelSelector` is a standard Kubernetes label selector.
* `namespaceSelector` is a standard Kubernetes namespace selector. If defined, make sure to add `Namespaces` to your `configs.config.gatekeeper.sh` object to ensure namespaces are synced into OPA. Refer to the [Replicating Data section](#replicating-data) for more details.

Note that if multiple matchers are specified, a resource must satisfy each top-level matcher (`kinds`, `namespaces`, etc.) to be in scope. Each top-level matcher has its own semantics for what qualifies as a match. An empty matcher is deemed to be inclusive (matches everything).

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
apiVersion: constraints.gatekeeper.sh/v1alpha1
kind: K8sRequiredLabels
metadata:
name: pod-must-have-gk
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
namespaceSelector:
matchExpressions:
- key: workloadtype
operator: In
values: [prodworkload]
parameters:
labels: ["gatekeeper"]
6 changes: 6 additions & 0 deletions example/resources/bad_ns_namespaceselector.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
apiVersion: v1
kind: Namespace
metadata:
name: bad-prod-ns
labels:
workloadtype: prodworkload
13 changes: 13 additions & 0 deletions example/resources/bad_pod_namespaceselector.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
apiVersion: v1
kind: Pod
metadata:
name: opa
namespace: bad-prod-ns
spec:
containers:
- name: opa
image: openpolicyagent/opa:0.9.2
args:
- "run"
- "--server"
- "--addr=localhost:8080"
31 changes: 31 additions & 0 deletions example/templates/k8srequiredlabels_template.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
apiVersion: templates.gatekeeper.sh/v1alpha1
kind: ConstraintTemplate
metadata:
name: k8srequiredlabels
spec:
crd:
spec:
names:
kind: K8sRequiredLabels
listKind: K8sRequiredLabelsList
plural: k8srequiredlabels
singular: k8srequiredlabels
validation:
# Schema for the `parameters` field
openAPIV3Schema:
properties:
labels:
type: array
items: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8srequiredlabels

deny[{"msg": msg, "details": {"missing_labels": missing}}] {
provided := {label | input.review.object.metadata.labels[label]}
required := {label | label := input.constraint.spec.parameters.labels[_]}
missing := required - provided
count(missing) > 0
msg := sprintf("you must provide labels: %v", [missing])
}
23 changes: 22 additions & 1 deletion pkg/target/regolib/src.rego
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ matching_constraints[constraint] {

matches_namespaces(match)

matches_nsselector(match)

label_selector := get_default(match, "labelSelector", {})
obj := get_default(input.review, "object", {})
metadata := get_default(obj, "metadata", {})
Expand Down Expand Up @@ -192,4 +194,23 @@ matches_namespaces(match) {
has_field(match, "namespaces")
ns := {n | n = match.namespaces[_]}
count({input.review.namespace} - ns) == 0
}
}

matches_nsselector(match) {
not has_field(match, "namespaceSelector")
}

matches_nsselector(match) {
has_field(match, "namespaceSelector")
ns := data["{{.DataRoot}}"].cluster["v1"]["Namespace"][input.review.namespace]
matches_namespace_selector(match, ns)
}

# Checks to see if a kubernetes NamespaceSelector matches a namespace with a given set of labels
# A non-existent selector or labels should be represented by an empty object ("{}")
matches_namespace_selector(match, ns) {
metadata := get_default(ns, "metadata", {})
nslabels := get_default(metadata, "labels", {})
namespace_selector := get_default(match, "namespaceSelector", {})
matches_label_selector(namespace_selector, nslabels)
}
77 changes: 73 additions & 4 deletions pkg/target/target.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ matching_constraints[constraint] {

matches_namespaces(match)

matches_nsselector(match)

label_selector := get_default(match, "labelSelector", {})
obj := get_default(input.review, "object", {})
metadata := get_default(obj, "metadata", {})
Expand Down Expand Up @@ -221,6 +223,24 @@ matches_namespaces(match) {
ns := {n | n = match.namespaces[_]}
count({input.review.namespace} - ns) == 0
}

matches_nsselector(match) {
not has_field(match, "namespaceSelector")
}

matches_nsselector(match) {
has_field(match, "namespaceSelector")
ns := {{.DataRoot}}.cluster["v1"]["Namespace"][input.review.namespace]
matches_namespace_selector(match, ns)
}

matches_namespace_selector(match, ns) {
metadata := get_default(ns, "metadata", {})
nslabels := get_default(metadata, "labels", {})
namespace_selector := get_default(match, "namespaceSelector", {})
matches_label_selector(namespace_selector, nslabels)
}

`

var libTempl = template.Must(template.New("library").Parse(templSrc))
Expand Down Expand Up @@ -390,6 +410,41 @@ func (h *K8sValidationTarget) MatchSchema() apiextensionsv1beta1.JSONSchemaProps
},
},
},
"namespaceSelector": apiextensionsv1beta1.JSONSchemaProps{
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
// Map schema validation will only work in kubernetes versions > 1.10. See https://github.com/kubernetes/kubernetes/pull/62333
//"matchLabels": apiextensionsv1beta1.JSONSchemaProps{
// AdditionalProperties: &apiextensionsv1beta1.JSONSchemaPropsOrBool{
// Allows: true,
// Schema: &apiextensionsv1beta1.JSONSchemaProps{Type: "string"},
// },
//},
"matchExpressions": apiextensionsv1beta1.JSONSchemaProps{
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &apiextensionsv1beta1.JSONSchemaProps{
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
"key": apiextensionsv1beta1.JSONSchemaProps{Type: "string"},
"operator": apiextensionsv1beta1.JSONSchemaProps{
Type: "string",
Enum: []apiextensionsv1beta1.JSON{
apiextensionsv1beta1.JSON{Raw: []byte(`"In"`)},
apiextensionsv1beta1.JSON{Raw: []byte(`"NotIn"`)},
apiextensionsv1beta1.JSON{Raw: []byte(`"Exists"`)},
apiextensionsv1beta1.JSON{Raw: []byte(`"DoesNotExist"`)},
}},
"values": apiextensionsv1beta1.JSONSchemaProps{
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &apiextensionsv1beta1.JSONSchemaProps{Type: "string"},
},
},
},
},
},
},
},
},
},
}
}
Expand All @@ -399,10 +454,8 @@ func (h *K8sValidationTarget) ValidateConstraint(u *unstructured.Unstructured) e
if err != nil {
return err
}
if !found {
return nil
}
if labelSelector != nil {

if found && labelSelector != nil {
labelSelectorObj, err := convertToLabelSelector(labelSelector)
if err != nil {
return err
Expand All @@ -412,6 +465,22 @@ func (h *K8sValidationTarget) ValidateConstraint(u *unstructured.Unstructured) e
return errorList.ToAggregate()
}
}

namespaceSelector, found, err := unstructured.NestedMap(u.Object, "spec", "match", "namespaceSelector")
if err != nil {
return err
}

if found && namespaceSelector != nil {
namespaceSelectorObj, err := convertToLabelSelector(namespaceSelector)
if err != nil {
return err
}
errorList := validation.ValidateLabelSelector(namespaceSelectorObj, field.NewPath("spec", "labelSelector"))
if len(errorList) > 0 {
return errorList.ToAggregate()
}
}
return nil
}

Expand Down
96 changes: 96 additions & 0 deletions pkg/target/target_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,102 @@ func TestValidateConstraint(t *testing.T) {
}
}
}
`,
ErrorExpected: true,
},
{
Name: "No NamespaceSelector",
Constraint: `
{
"apiVersion": "constraints.gatekeeper.sh/v1alpha1",
"kind": "K8sAllowedRepos",
"metadata": {
"name": "prod-nslabels-is-openpolicyagent"
},
"spec": {
"match": {
"kinds": [
{
"apiGroups": [""],
"kinds": ["Pod"]
}],
"labelSelector": {
"matchExpressions": [{
"key": "someKey",
"operator": "In",
"values": ["some value"]
}]
}
},
"parameters": {
"repos": ["openpolicyagent"]
}
}
}
`,
ErrorExpected: false,
},
{
Name: "Valid NamespaceSelector",
Constraint: `
{
"apiVersion": "constraints.gatekeeper.sh/v1alpha1",
"kind": "K8sAllowedRepos",
"metadata": {
"name": "prod-nslabels-is-openpolicyagent"
},
"spec": {
"match": {
"kinds": [
{
"apiGroups": [""],
"kinds": ["Pod"]
}],
"namespaceSelector": {
"matchExpressions": [{
"key": "someKey",
"operator": "In",
"values": ["some value"]
}]
}
},
"parameters": {
"repos": ["openpolicyagent"]
}
}
}
`,
ErrorExpected: false,
},
{
Name: "Invalid NamespaceSelector",
Constraint: `
{
"apiVersion": "constraints.gatekeeper.sh/v1alpha1",
"kind": "K8sAllowedRepos",
"metadata": {
"name": "prod-nslabels-is-openpolicyagent"
},
"spec": {
"match": {
"kinds": [
{
"apiGroups": [""],
"kinds": ["Pod"]
}],
"namespaceSelector": {
"matchExpressions": [{
"key": "someKey",
"operator": "Blah",
"values": ["some value"]
}]
}
},
"parameters": {
"repos": ["openpolicyagent"]
}
}
}
`,
ErrorExpected: true,
},
Expand Down
49 changes: 47 additions & 2 deletions pkg/webhook/policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,39 @@ spec:
key: "something"
values: ["anything"]
`

bad_namespaceselector = `
apiVersion: constraints.gatekeeper.sh/v1alpha1
kind: K8sGoodRego
metadata:
name: bad-namespaceselector
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
namespaceSelector:
matchExpressions:
- operator: "In"
key: "something"
`

good_namespaceselector = `
apiVersion: constraints.gatekeeper.sh/v1alpha1
kind: K8sGoodRego
metadata:
name: good-namespaceselector
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
namespaceSelector:
matchExpressions:
- operator: "In"
key: "something"
values: ["anything"]
`
)

func makeOpaClient() (client.Client, error) {
Expand Down Expand Up @@ -170,17 +203,29 @@ func TestConstraintValidation(t *testing.T) {
ErrorExpected bool
}{
{
Name: "Valid Constraint",
Name: "Valid Constraint labelselector",
Template: good_rego_template,
Constraint: good_labelselector,
ErrorExpected: false,
},
{
Name: "Invalid Constraint",
Name: "Invalid Constraint labelselector",
Template: good_rego_template,
Constraint: bad_labelselector,
ErrorExpected: true,
},
{
Name: "Valid Constraint namespaceselector",
Template: good_rego_template,
Constraint: good_namespaceselector,
ErrorExpected: false,
},
{
Name: "Invalid Constraint namespaceselector",
Template: good_rego_template,
Constraint: bad_namespaceselector,
ErrorExpected: true,
},
}
for _, tt := range tc {
t.Run(tt.Name, func(t *testing.T) {
Expand Down