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

Support Naming Policy #17

Merged
merged 20 commits into from
Nov 11, 2021
Merged
Show file tree
Hide file tree
Changes from 18 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
2 changes: 1 addition & 1 deletion charts/accurate/Chart.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ type: application
# This is the chart version. This version number should be incremented each time you make changes
# to the chart and its templates, including the app version.
# Versions are expected to follow Semantic Versioning (https://semver.org/)
version: 0.2.0
version: 0.2.1

# This is the version number of the application being deployed. This version number should be
# incremented each time you make changes to the application. Versions are not expected to
Expand Down
19 changes: 19 additions & 0 deletions charts/accurate/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,25 @@ controller:
- version: v1
kind: ResourceQuota

# controller.config.namingPolicies -- List of nameing policy for SubNamespaces.
# root and match are both regular expressions.
# When a SubNamespace is created in a tree starting from a root namespace and the root namespace's name matches the "root" regular expression, the SubNamespace name is validated with the "match" regular expression.
#
# "match" namingPolicies can use variables of regexp capture group naming of "root" namingPolicies.
# example:
# root: ^app-(?P<team>.*)
# match: ^app-${team}-.*
# root namespace: app-team1
# compiled match naming policy: ^app-team1-.*
# This feature is provided using https://pkg.go.dev/regexp#Regexp.Expand
# namingPolicies:
# - root: foo
# match: foo_.*
# - root: bar
# match: bar_.*
# - root: ^app-(?P<team>.*)
# match: ^app-${team}-.*

additionalRBAC:
# controller.additionalRBAC.rules -- Specify the RBAC rules to be added to the controller.
# ClusterRole and ClusterRoleBinding are created with the names `{{ release name }}-additional-resources`.
Expand Down
4 changes: 3 additions & 1 deletion cmd/accurate-controller/sub/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,9 @@ func subMain(ns, addr string, port int) error {
}).SetupWithManager(mgr); err != nil {
return fmt.Errorf("unable to create SubNamespace controller: %w", err)
}
hooks.SetupSubNamespaceWebhook(mgr, dec)
if err = hooks.SetupSubNamespaceWebhook(mgr, dec, cfg.NamingPolicyRegexps); err != nil {
return fmt.Errorf("unable to create SubNamespace webhook: %w", err)
}

// Resource propagation controller
for _, res := range watched {
Expand Down
13 changes: 13 additions & 0 deletions config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,16 @@ watches:
kind: Secret
- version: v1
kind: ResourceQuota

# List of nameing policy for SubNamespaces.
# root and match are both regular expressions.
# When a SubNamespace is created in a tree starting from a root namespace and the root namespace's name matches the "root" regular expression, the SubNamespace name is validated with the "match" regular expression.
#
# "match" namingPolicies can use variables of regexp capture group naming of "root" namingPolicies.
# example:
# root: ^app-(?P<team>.*)
# match: ^app-${team}-.*
# root namespace: app-team1
# compiled match naming policy: ^app-team1-.*
# This feature is provided using https://pkg.go.dev/regexp#Regexp.Expand
namingPolicies: []
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add comments just like in the other fields.

19 changes: 19 additions & 0 deletions docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,25 @@ controller:
kind: RoleBinding
- version: v1
kind: Secret

# controller.config.namingPolicies -- List of nameing policy for SubNamespaces.
# root and match are both regular expressions.
# When a SubNamespace is created in a tree starting from a root namespace and the root namespace's name matches the "root" regular expression, the SubNamespace name is validated with the "match" regular expression.
#
# "match" namingPolicies can use variables of regexp capture group naming of "root" namingPolicies.
# example:
# root: ^app-(?P<team>.*)
# match: ^app-${team}-.*
# root namespace: app-team1
# compiled match naming policy: ^app-team1-.*
# This feature is provided using https://pkg.go.dev/regexp#Regexp.Expand
namingPolicies:
- root: foo
match: foo_.*
- root: bar
match: bar_.*
- root: ^app-(?P<team>.*)
match: ^app-${team}-.*
<snip>
```

Expand Down
67 changes: 60 additions & 7 deletions hooks/subnamespace.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ import (
"encoding/json"
"fmt"
"net/http"
"regexp"

accuratev1 "github.com/cybozu-go/accurate/api/v1"
"github.com/cybozu-go/accurate/pkg/config"
"github.com/cybozu-go/accurate/pkg/constants"
admissionv1 "k8s.io/api/admission/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/webhook"
Expand Down Expand Up @@ -47,7 +50,8 @@ func (m *subNamespaceMutator) Handle(ctx context.Context, req admission.Request)

type subNamespaceValidator struct {
client.Client
dec *admission.Decoder
dec *admission.Decoder
namingPolicies []config.NamingPolicyRegexp
}

var _ admission.Handler = &subNamespaceValidator{}
Expand All @@ -67,15 +71,62 @@ func (v *subNamespaceValidator) Handle(ctx context.Context, req admission.Reques
return admission.Errored(http.StatusInternalServerError, err)
}

if ns.Labels[constants.LabelType] == constants.NSTypeRoot || ns.Labels[constants.LabelParent] != "" {
return admission.Allowed("")
if ns.Labels[constants.LabelType] != constants.NSTypeRoot && ns.Labels[constants.LabelParent] == "" {
return admission.Denied(fmt.Sprintf("namespace %s is neither a root nor a sub namespace", ns.Name))
}

root, err := v.getRootNamespace(ctx, ns)
if err != nil {
return admission.Denied(err.Error())
}
ok, msg, err := v.notMatchingNamingPolicy(ctx, sn.Name, root.Name)
if err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
if !ok {
return admission.Denied(fmt.Sprintf("namespace %s is not match naming policies: %s", ns.Name, msg))
}
return admission.Allowed("")
}

func (v *subNamespaceValidator) getRootNamespace(ctx context.Context, ns *corev1.Namespace) (*corev1.Namespace, error) {
if ns.Labels[constants.LabelType] == constants.NSTypeRoot {
return ns, nil
}

return admission.Denied(fmt.Sprintf("namespace %s is neither a root nor a sub namespace", ns.Name))
parent := &corev1.Namespace{}
if err := v.Get(ctx, client.ObjectKey{Name: ns.Labels[constants.LabelParent]}, parent); err != nil {
if !apierrors.IsNotFound(err) {
return nil, fmt.Errorf("failed to get namespace %s: %w", ns.Labels[constants.LabelParent], err)
}
return nil, fmt.Errorf("namespace %s is not found", ns.Labels[constants.LabelParent])
}
return v.getRootNamespace(ctx, parent)
}

func (v *subNamespaceValidator) notMatchingNamingPolicy(ctx context.Context, ns, root string) (bool, string, error) {
for _, policy := range v.namingPolicies {
matches := policy.Root.FindAllStringSubmatchIndex(root, -1)
if len(matches) > 0 {
m := []byte{}
for _, match := range matches {
m = policy.Root.ExpandString(m, policy.Match, root, match)
}
r, err := regexp.Compile(string(m))
if err != nil {
return false, "", fmt.Errorf("invalid naming policy: %w", err)
}

if !r.MatchString(ns) {
return false, fmt.Sprintf("namespace - target=%s root=%s denied policy - root=%s match=%s", ns, root, policy.Root, policy.Match), nil
}
}
}
return true, "", nil
}

// SetupSubNamespaceWebhook registers the webhooks for SubNamespace
func SetupSubNamespaceWebhook(mgr manager.Manager, dec *admission.Decoder) {
func SetupSubNamespaceWebhook(mgr manager.Manager, dec *admission.Decoder, namingPolicyRegexps []config.NamingPolicyRegexp) error {
serv := mgr.GetWebhookServer()

m := &subNamespaceMutator{
Expand All @@ -84,8 +135,10 @@ func SetupSubNamespaceWebhook(mgr manager.Manager, dec *admission.Decoder) {
serv.Register("/mutate-accurate-cybozu-com-v1-subnamespace", &webhook.Admission{Handler: m})

v := &subNamespaceValidator{
Client: mgr.GetClient(),
dec: dec,
Client: mgr.GetClient(),
dec: dec,
namingPolicies: namingPolicyRegexps,
}
serv.Register("/validate-accurate-cybozu-com-v1-subnamespace", &webhook.Admission{Handler: v})
return nil
}
174 changes: 174 additions & 0 deletions hooks/subnamespace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,178 @@ var _ = Describe("SubNamespace webhook", func() {

Expect(controllerutil.ContainsFinalizer(sn, constants.Finalizer)).To(BeTrue())
})

Context("Naming Policy", func() {
When("the root namespace name is matched some Root Naming Policies", func() {
When("the SubNamespace name is matched to the Root's Match Naming Policy", func() {
It("should allow creation of SubNamespace in a root namespace - pattern1", func() {
ns := &corev1.Namespace{}
ns.Name = "naming-policy-root-1"
ns.Labels = map[string]string{constants.LabelType: constants.NSTypeRoot}
err := k8sClient.Create(ctx, ns)
Expect(err).NotTo(HaveOccurred())

sn := &accuratev1.SubNamespace{}
sn.Namespace = "naming-policy-root-1"
sn.Name = "naming-policy-root-1-child"
err = k8sClient.Create(ctx, sn)
Expect(err).NotTo(HaveOccurred())
})

It("should allow creation of SubNamespace in a root namespace - pattern2", func() {
ns := &corev1.Namespace{}
ns.Name = "root-ns-match-1"
ns.Labels = map[string]string{constants.LabelType: constants.NSTypeRoot}
err := k8sClient.Create(ctx, ns)
Expect(err).NotTo(HaveOccurred())

sn := &accuratev1.SubNamespace{}
sn.Namespace = "root-ns-match-1"
sn.Name = "child-match-1"
err = k8sClient.Create(ctx, sn)
Expect(err).NotTo(HaveOccurred())
})

It("should allow creation of SubNamespace in a root namespace - pattern3", func() {
root := &corev1.Namespace{}
root.Name = "ns-root-1"
root.Labels = map[string]string{constants.LabelType: constants.NSTypeRoot}
err := k8sClient.Create(ctx, root)
Expect(err).NotTo(HaveOccurred())

parent := &corev1.Namespace{}
parent.Name = "ns-root-1-parent"
parent.Labels = map[string]string{constants.LabelParent: "ns-root-1"}
err = k8sClient.Create(ctx, parent)
Expect(err).NotTo(HaveOccurred())

sn := &accuratev1.SubNamespace{}
sn.Namespace = "ns-root-1-parent"
sn.Name = "ns-root-1-parent-child"
err = k8sClient.Create(ctx, sn)
Expect(err).NotTo(HaveOccurred())
})

It("should allow creation of SubNamespace in a root namespace - pattern4", func() {
root := &corev1.Namespace{}
root.Name = "app-team1"
root.Labels = map[string]string{constants.LabelType: constants.NSTypeRoot}
err := k8sClient.Create(ctx, root)
Expect(err).NotTo(HaveOccurred())

sn := &accuratev1.SubNamespace{}
sn.Namespace = "app-team1"
sn.Name = "app-team1-child"
err = k8sClient.Create(ctx, sn)
Expect(err).NotTo(HaveOccurred())
})

It("should allow creation of SubNamespace in a root namespace - pattern5", func() {
root := &corev1.Namespace{}
root.Name = "app-team2-app1"
root.Labels = map[string]string{constants.LabelType: constants.NSTypeRoot}
err := k8sClient.Create(ctx, root)
Expect(err).NotTo(HaveOccurred())

sn := &accuratev1.SubNamespace{}
sn.Namespace = "app-team2-app1"
sn.Name = "app-team2-app1-subapp1"
err = k8sClient.Create(ctx, sn)
Expect(err).NotTo(HaveOccurred())
})

It("should allow creation of SubNamespace in a root namespace - pattern6", func() {
root := &corev1.Namespace{}
root.Name = "unuse-naming-group-team1"
root.Labels = map[string]string{constants.LabelType: constants.NSTypeRoot}
err := k8sClient.Create(ctx, root)
Expect(err).NotTo(HaveOccurred())

sn := &accuratev1.SubNamespace{}
sn.Namespace = "unuse-naming-group-team1"
sn.Name = "unuse-naming-group-child1"
err = k8sClient.Create(ctx, sn)
Expect(err).NotTo(HaveOccurred())
})
})

When("the SubNamespace name is not matched to the Root's Match Naming Policy", func() {
It("should deny creation of SubNamespace in a root namespace - pattern1", func() {
ns := &corev1.Namespace{}
ns.Name = "naming-policy-root-2"
ns.Labels = map[string]string{constants.LabelType: constants.NSTypeRoot}
err := k8sClient.Create(ctx, ns)
Expect(err).NotTo(HaveOccurred())

sn := &accuratev1.SubNamespace{}
sn.Namespace = "naming-policy-root-2"
sn.Name = "naming-policy-root-2--child"
err = k8sClient.Create(ctx, sn)
Expect(err).To(HaveOccurred())
})

It("should deny creation of SubNamespace in a root namespace - pattern2", func() {
ns := &corev1.Namespace{}
ns.Name = "root-ns-match-2"
ns.Labels = map[string]string{constants.LabelType: constants.NSTypeRoot}
err := k8sClient.Create(ctx, ns)
Expect(err).NotTo(HaveOccurred())

sn := &accuratev1.SubNamespace{}
sn.Namespace = "root-ns-match-2"
sn.Name = "child-2"
err = k8sClient.Create(ctx, sn)
Expect(err).To(HaveOccurred())
})

It("should deny creation of SubNamespace in a root namespace - pattern3", func() {
root := &corev1.Namespace{}
root.Name = "ns-root-2"
root.Labels = map[string]string{constants.LabelType: constants.NSTypeRoot}
err := k8sClient.Create(ctx, root)
Expect(err).NotTo(HaveOccurred())

parent := &corev1.Namespace{}
parent.Name = "ns-root-2-parent"
parent.Labels = map[string]string{constants.LabelParent: "ns-root-1"}
err = k8sClient.Create(ctx, parent)
Expect(err).NotTo(HaveOccurred())

sn := &accuratev1.SubNamespace{}
sn.Namespace = "ns-root-2-parent"
sn.Name = "not-ns-root-2-parent-child"
err = k8sClient.Create(ctx, sn)
Expect(err).To(HaveOccurred())
})

It("should deny creation of SubNamespace in a root namespace - pattern4", func() {
root := &corev1.Namespace{}
root.Name = "app-team10"
root.Labels = map[string]string{constants.LabelType: constants.NSTypeRoot}
err := k8sClient.Create(ctx, root)
Expect(err).NotTo(HaveOccurred())

sn := &accuratev1.SubNamespace{}
sn.Namespace = "app-team10"
sn.Name = "app-team20-child"
err = k8sClient.Create(ctx, sn)
Expect(err).To(HaveOccurred())
})

It("should deny creation of SubNamespace in a root namespace - pattern5", func() {
root := &corev1.Namespace{}
root.Name = "unuse-naming-group-team2"
root.Labels = map[string]string{constants.LabelType: constants.NSTypeRoot}
err := k8sClient.Create(ctx, root)
Expect(err).NotTo(HaveOccurred())

sn := &accuratev1.SubNamespace{}
sn.Namespace = "unuse-naming-group-team2"
sn.Name = "unuse-naming-group-team2-foo"
err = k8sClient.Create(ctx, sn)
Expect(err).To(HaveOccurred())
})
})
})
})
})
Loading